Giter VIP home page Giter VIP logo

alirezanet / husky.net Goto Github PK

View Code? Open in Web Editor NEW
590.0 8.0 29.0 765 KB

Git hooks made easy with Husky.Net internal task runner! 🐶 It brings the dev-dependency concept to the .NET world!

Home Page: https://alirezanet.github.io/Husky.Net/

License: MIT License

C# 97.72% Shell 1.07% Batchfile 0.18% Dockerfile 1.03%
git git-hooks dotnet husky hooks linting lint-staged developer-experience stylelint linter

husky.net's People

Contributors

abdulrhman5 avatar acesyde avatar aliasadidev avatar alirezanet avatar atifaziz avatar dependabot[bot] avatar donalfenwick avatar nugetninja avatar sajjadhosseinpour avatar sondr3 avatar tychus avatar weihanli avatar xemrox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

husky.net's Issues

Husky throws an ArgumentException when I try to commit through Sourcetree

Version

0.6.2

Details

I am not so sure if this should be opened as a bug or a discussion would be a better fit so apologies in advance but basically
whenever I try to commit changes through Sourcetree Husky throws an ArgumentException.

husky-exception

Here's the stack trace:

Unhandled exception. System.ArgumentException: An item with the same key has already been added. Key: HOME
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at CliFx.Utils.Extensions.CollectionExtensions.ToDictionary[TKey,TValue](IDictionary dictionary, IEqualityComparer`1 comparer) in /_/CliFx/Utils/Extensions/CollectionExtensions.cs:line 38
   at CliFx.CliApplication.RunAsync(IReadOnlyList`1 commandLineArguments) in /_/CliFx/CliApplication.cs:line 216
   at Program.<Main>$(String[] args) in /home/runner/work/Husky.Net/Husky.Net/src/Husky/Program.cs:line 31
   at Program.<Main>(String[] args)

It works as expected if I try to commit either from the CLI, VS or VSCode but not on Sourcetree. I had a very quick look at the source code to try and figure out what could be happening but couldn't figure anything out immediately. Any idea what that Key: HOME might be or where it comes from? is it an environment variable? I'd appreciate any feedback on this, we'd really like to use your tool but without having to sacrificing Sourcetree in the process 😄. Thanks!

OS: Windows 11 Pro 22621.2428
Sourcetree version: 3.4.15

Steps to reproduce

Husky exec can't find file or assembly in cache

Version

0.5.3

Details

I've installed husky commit-msg hook as example:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
dotnet husky run --name "commit-message-linter" --args "$1"

And task in task-runner.json is:

{
     "name": "commit-message-linter",
     "command": "dotnet",
     "args": ["husky", "exec", ".husky/csx/commit-lint.csx", "--args", "${args}"]
},

But when it runs it say me:

Could not load file or assembly 'C:\...\.husky\_\cache\4D72B7ADBD7784997E1BB84765FAAEB70E0070C7CDCC0CD5A26506CEE37777A324ECB98D7D0485C05D1739A944786193B1E96A9026E5F636C8BF952157B5ECBC'. Impossibile trovare il modulo specificato.

(read as "Impossible to find the specified module)

The content of that file is cryptic for me.

Steps to reproduce

Follow this guide on official site https://alirezanet.github.io/Husky.Net/guide/csharp-script.html#examples and try to commit using a convential commit compilant commit message as build: ok.

ANSI mode

Details

There happen to be situations in which I run Husky inside a cmd.exe-derived terminal. There, the console has no idea about miscellaneous Unicode symbols - what I get instead are question marks:

$ dotnet husky run
[Husky] ?? Loading tasks...
--------------------------------------------------
[Husky] ? Preparing task 'Lint staged code'

While I know about chcp 65001, there are situations in which I am unable to use it; therefore, it would be great if this project supported some sort of "ANSI mode" switch that, when enabled, would produce symbols renderable in cmd.exe so that one would see at a glance at which step Husky is right now with the added bonus of a monospace output.

Example:

$ dotnet husky run
[Husky] 🚀 Loading tasks...
--------------------------------------------------
[Husky] ⚡ Preparing task 'Lint staged code'
$ dotnet husky run --ansi
[Husky] @ Loading tasks...
--------------------------------------------------
[Husky] # Preparing task 'Lint staged code'

Is this a reasonable feature to request?

Support broader environmental global skip flag

Details

In an MSBuild environment its quite common to set variables to false instead of 0.
Therefore I recommend to add a test to the $env:HUSKY variable for some kind of false in order to skip husky execution.

git commit 提示 dotnet-format 不存在

Version

0.4.4

Details

[Husky] Matches:
  microservices/IdentityService.Host/IdentityServiceHostModule.cs
  microservices/IdentityService.Host/Program.cs
  microservices/IdentityService.Host/Startup.cs
  microservices/IdentityService.Host/Controllers/HomeController.cs
  microservices/IdentityService.Host/Tenants/TenantCreatedDistributedEventHandler.cs
[Husky] ? Executing task 'dotnet-format' ...
无法执行,因为找不到指定的命令或文件。
可能的原因包括:
  *内置的 dotnet 命令拼写错误。
  *你打算执行 .NET 程序,但 dotnet-dotnet-format 不存在。
  *你打算运行全局工具,但在路径上找不到具有此名称且前缀为 dotnet 的可执行文件。

Steps to reproduce

  • 1、git commit -m "feat: 添加IdentityService.Host"

fatal: cannot run .husky/pre-commit: No such file or directory on Mac-os

Version

0.5.4

Details

Hi, i have an issue for v0.5.4, my project already has pre-commit file in .husky folder
image

My pre-commit file is

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

#Run the command group in .husky/task-runner.json
dotnet husky run --group pre-commit

#Allow Committing
exit 0

My task-runner.json file is

{
  "tasks": [
    {
      "name": "dotnet-format",
      "group": "pre-commit",
      "command": "dotnet",
      "args": ["dotnet-format", "--include", "${staged}"],
      "include": ["**/*.cs", "**/*.vb"]
    }
  ]
}

My .confif/dotnet-tool.json file is

{
  "version": 1,
  "isRoot": true,
  "tools": {
    "husky": {
      "version": "0.5.4",
      "commands": [
        "husky"
      ]
    },
    "dotnet-format": {
      "version": "5.1.250801",
      "commands": [
        "dotnet-format"
      ]
    }
  }
}

Steps to reproduce

  • I am on a branch with Husky installed in my project.
  • Then, I switch to a branch without Husky installation.
  • When I switch back to a branch with Husky installed and commit anything than I encounter this error.
  • fatal: cannot run .husky/pre-commit: No such file or directory

It gives this error in different situations sometimes as well. For instance, I clone the project from scratch and then face this issue on a branch with Husky already installed. As far as I can understand, I encounter this error when changing branches locally.

husky install fails when project is a submodule

Version

0.5.4

Details

when running dotnet husky install from the root of my project directory, or as part of automated installation, I get an error message

.git can't be found (see https://alirezanet.github.io/Husky.Net/guide/getting-started)
Git hooks installation failed

Steps to reproduce

  1. create a new git repository
mkdir new_repo
cd new_repo
git init
  1. add existing project with husky as a sub-module
git submodule add [email protected]:alirezanet/Husky.Net.git
  1. build the submodule to trigger husky installation
cd Husky.Net
dotnet build

you will get the following error

MSBuild version 17.5.0+6f08c67f3 for .NET
  Determining projects to restore...
  .git can't be found (see https://alirezanet.github.io/Husky.Net/guide/getting-started)
  Git hooks installation failed
D:\source\repos\new_repo\Husky.Net\src\Husky\Husky.csproj(61,5): error MSB3073: The command "dotnet husky install" exit
ed with code 1.

Build FAILED.

D:\source\repos\new_repo\Husky.Net\src\Husky\Husky.csproj(61,5): error MSB3073: The command "dotnet husky install" exit
ed with code 1.
    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:03.52

not working on repos that haven't run dotnet husky install

Version

latest

Details

Husky dotnet is not working with error unable to find git (or something along that manner) unless a user actually manually writes dotnet husky install (even though others have done this and pushed to the repo).

I assume this is due to .git folder not being in version control which is where the precommit hooks are written to, but is there a way for this to actually setup automatically? Its very odd to me that each user will need to setup husky locally unless I'm missing something and git folder shouldn't be in version control from my knowledge.

Steps to reproduce

install husky dotnet with precommit hooks in a repo on one computer
download the repo and try command:

dotnet husky run

Remove requirement for .net7, allow .net 8 only

Details

currently, husky .net requires .net7 to work.

image

this happens when trying to restore a project that I just pulled, without having .net 7 on the machine

installing .net7 sdk resolves this issue

Support .NET 7.0

Details

.NET 7.0 came out a little bit ago, and I was wondering whether you were planning on adding support for it. I tried doing a quick PR for it, but I'm not sure what the .NET support is supposed to be, so I'm holding off until some feedback.

`${matched}` doesn't work on Windows

Using ${matched} returns an empty list.

To Reproduce

Update task-runner.json to read as follows:

{
   "tasks": [
      {
         "name": "test",
         "command": "bash",
         "args": [ "-c", "echo", "${matched}" ],
         "include": [ "**/*.cs", "**/*.vb" ],
         "windows": {
            "command": "cmd",
            "args": [ "/c", "echo", "${matched}" ]
         }
      }
   ]
}

This is based on the dotnet-format task that comes pre-configured when Husky is installed.

Run the task with:

dotnet husky run --name test

Expected behavior

Expected matching files names to be echoed.

Actual behavior

The task is skipped because no matching files are found:

[Husky] ?? Preparing tasks ...
[Husky] ?? Using task name 'test'
--------------------------------------------------
[Husky] ? Preparing task 'test'
[Husky] ?? Skipped, no matched files
--------------------------------------------------
[Husky] Execution completed ??

I ran this on a Windows 11 machine with a Git repo containing a C# project.

bash exit 1 doesn't work

Version

0.5.4

Details

The tool doesn't care about the errors, the information attached into Steps to reproduce section

Steps to reproduce

setup and config

dotnet new console -n App1
git init

dotnet new tool-manifest
dotnet tool install Husky
dotnet husky install

dotnet husky add pre-commit -c "dotnet husky run --group pre-commit'"

add .editorconfig file

https://github.com/RehanSaeed/EditorConfig/blob/main/.editorconfig

pre-commit file content

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

dotnet husky run --group pre-commit

# I want to run a condition here, e.g if dotnet format updated some files then the git commit would be rejected 
exit 1 # <============ didn't work for c# files

Task-runner.json

{
  "tasks": [
    {
      "name": "Dotnet Format",
      "command": "cmd",
      "pathMode": "relative",
      "args": [
        "/c",
        "dotnet",
        "format",
        "--include",
        "${staged}"
      ],
      "group": "pre-commit"
    }
  ]
}

Update program.cs (with bad format)

using App1;

internal class Program
{
    private static void Main(string[] args)
    {
   int x=100;
int xx=x;
    }
}

Add all files

git add .
git commit -m "init"

The problem is when I send the git commit, it will be stored successfully, but it shouldn't be.

image

As you can see the file should be placed in the change section.

image

Dotnet format worked correctly (added the file as a new file changed)

image

Doesn't support the dotnet tools (e.g jb)

Version

0.5.4

Details

I've installed jb tool with dotnet cli, the husky tool added a dash between dotnet and tool name; for this reason, the execution failed.

dotnet config file

{
  "version": 1,
  "isRoot": false,
  "tools": {
    "jetbrains.resharper.globaltools": {
      "version": "2022.3.2",
      "commands": [
        "jb"
      ]
    },
    "husky": {
      "version": "0.5.4",
      "commands": [
        "husky"
      ]
    }
  }
}

husky's runner task

 {
      "name": "Run JB Clean Up Code",
      "command": "dotnet",
      "args": [
        "jb cleanupcode myproj.sln --profile='proj: Full Cleanup'"
      ],
      "group": "pre-commit",
      "cwd": "."
    }

image

Steps to reproduce

  • Install jetbrains.resharper.globaltools locally with dotnet cli => dotnet tool install JetBrains.ReSharper.GlobalTools
  • add "jb cleanupcode myproj.sln --profile='proj: Full Cleanup'" into the arg property in the one task runner
  • this command works correctly => dotnet jb cleanupcode myproj.sln --profile='proj: Full Cleanup'

First `husky add` some command is not line-terminated

Running dotnet husky add with some command is not line-terminated. Another execution will put the second command together with the first one. The bug only happens for the first invocation.

To Reproduce

Run the following commands in a shell, in a new directory and in the shown sequence:

git init
dotnet new tool-manifest
dotnet tool install Husky
dotnet husky install
dotnet husky add .husky/pre-commit "echo 'Husky is awesome!'"
dotnet husky add .husky/pre-commit "echo 'Husky is awesome!'"
git commit --allow-empty -m "Keep calm and commit"

The final git commit will print the following:

Husky is awesome!echo Husky is awesome!
[master (root-commit) 656c076] Keep calm and commit

Note that what gets printed from the hook is the single line Husky is awesome!echo Husky is awesome!.

Expected behavior

I would have expected the following output:

Husky is awesome!
Husky is awesome!
[master (root-commit) 656c076] Keep calm and commit

That is Husky is awesome! printed on two separate lines.

Additional information

It's clear why this is happening when one inspects the content of .husky/pre-commit:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

## husky task runner examples -------------------
## Note : for local installation use 'dotnet' prefix. e.g. 'dotnet husky'

## run all tasks
#husky run

### run all tasks with group: 'group-name'
#husky run --group group-name

## run task with name: 'task-name'
#husky run --name task-name

## or put your custom commands -------------------
#echo 'Husky.Net is awesome!'

echo 'Husky is awesome!'echo 'Husky is awesome!'

The first command was not line-terminated.

This does not happen for subsequent runs of husky add. For example, following-up with the commands:

dotnet husky add .husky/pre-commit "echo 'Husky is awesome!'"
git commit --allow-empty -m "Keep calm and commit"

prints:

Husky is awesome!echo Husky is awesome!
Husky is awesome!
[master 51f1c2b] Keep calm and commit

The third addition correctly printed on its own line.

پیشنهاد

سلام
به نظرم در مورد کاربرد و کارایی
یه مقاله نیاز باشه
مرسی

Support install not in .git root

Details

Currently, husky checks that it's being installed in the repository root, i.e. cwd contains a .git folder.

Some repository contain more than a .net solution, it's not uncommon to have other folders at root such as docs, infra, front-end, etc. In our setup, dotnet solution and .config local tools live in a Source folder, under root.

The issue with this is that:

  1. Local dotnet tool can't run outside Source because they're local and do not exist outside of that folder.
  2. Local tool Husky can't run inside Source because it requires .git in the same folder where it runs.

As 1. and 2. are mutually exclusive, there's no working configuration :(

Note

Husky -- the NPM project that inspired Husky.Net -- has a "How to" for this topic in its documentation:
https://typicode.github.io/husky/how-to.html#project-not-in-git-root-directory

Their solution is simply to change working directory appropriately in install script and hook.
The blocker is that whereas cd .. & husky works in NPM scripts, there's no way parameter to change the working directory in dotnet run, so husky init can't be run in a different cwd.

Suggested solution

Add a --cwd parameter to install command, so that the working directory can be changed before it runs:

dotnet husky install --cwd ../..

The reverse cd command should be inferred automatically (using Path.GetRelativePath) and introduced in hook script so that they run in the correct folder (otherwise dotnet husky & other local .net tool tasks will not be found).

commit-lint.csx not working

Version

0.6.2

Details

I followed the guide and when running dotnet husky exex ..husky\csx\commit-lint.csx --args "something here" I get error message saying "Unable to execute cached script".

I then changed the line "private var msg = File.ReadAllLines(Args[0])[0];" to private var msg = Args[0]; and it runs fine

Am I missing something here, is the guide incomplete or what?

Steps to reproduce

  • Follow guide to run CSharp scripts
  • Run given example script

How to avoid empty commit?

Version

0.6.0

Details

I have a webapi project with environment specific appsettings.json file. I don't want the appsettings.Development.json to be committed or pushed(its already tracked). I have a pre-commit hook with one command - git reset appsettings.Development.json. When I have appsettings.Development.json as only file, the pre-commit is unstaging the appsettings.Development.json file, but it is also creating an empty commit with no files. How do I avoid the empty commit?

Steps to reproduce

  • Step 1: Once dotnet husky is installed, run the command - $ dotnet husky add pre-commit -c "git reset appsettings.Development.json".
  • Step 2: Then modify the file appsettings.Development.json.
  • Step 3: Then stage the file and try to commit it
  • Step 4: The git will unstage the appsettings.Development.json file and create an empty commit.

Support Partially Staged Files

Hi! 👋🏻

First off -- I love this tool. Thank you for all of your hard work and effort. ❤️

I'd like to incorporate this tool into our development process but can't because of a single issue: Partial stages

For a single file, it is very common for me to stage some changes while leaving other changes unstaged.

      {
         "name": "dotnet-format",
         "group": "pre-commit",
         "command": "dotnet",
         "args": [ "format", "--include", "${staged}" ],
         "include": [ "**/*.cs" ]
      }

I currently use a task similar to the one above ☝🏻. When I commit, the task reformats the entire file (which is fine), but then it stages and commits the entire file including the changes I did not want (or intend) to commit.

Question: Does the include property on the task declare what staged files to "re-stage"?

Potential fix: Can the task runner return an error code if a file that's going to be "re-staged" is in the list of unstaged files?

Again, thank you for this wonderful tool! Let me know if you need any further clarification. Cheers!

${staged} variable contains some temporary files

Version

0.4.0

Details

I was running a git hook with several steps configured. I was expecting only REAL staged files to be committed but unfortunately there were some additional staged files which shouldn't be added to ${staged} variable.

Steps to reproduce

  1. dotnet new tool-manifest
  2. dotnet tool install JetBrains.ReSharper.GlobalTools
  3. dotnet tool install ReGitLint
  4. dotnet tool install Husky
  5. configure Husky, using following task-runner.json
{
  "tasks": [
    {
      "name": "before - echo staged from husky",
      "command": "echo",
      "args": ["${staged}"]
    },
    {
      "name": "reglint",
      "command": "dotnet",
      "args": ["regitlint", "-f", "staged", "--jb", "--verbosity=WARN"]
    },
    {
      "name": "after - echo staged from husky",
      "command": "echo",
      "args": ["${staged}"]
    },
    {
      "name": "after - echo staged from git",
      "command": "git",
      "args": ["diff", "--name-only", "--cached"]
    },
    {
      "name": "after - echo staged from ???",
      "command": "git",
      "args": ["diff-index", "--cached", "--diff-filter=AM", "--no-renames", "--name-only", "HEAD"]
    }
  ]
}
  1. as you can see in git log output, echo of ${staged} variable includes other (temporary?) files, while those files aren't included while running git diff/diff-index commands manually. In our use case, we want to run git add ${staged} after regitlint but it results in committing those temporary files as well.

Emoji does not appear correctly in the Windows environment

Version

0.4.0

Details

When we are on the Windows environment emoji in console does not rendered correctly

Windows
image

Linux
image

Terminal => Windows terminal
OS : Windows 11 / Ubuntu 20.04 (WSL2)

Steps to reproduce

  • Install husky
  • Execute dotnet husky run

dotnet husky install fails if .git folder is in the parent folder of the #C project

Version

v0.5.2

Details

In my project we have a parent folder, project and then a child folder Project.Api that houses the actual C# project files.

I can install the tool as described in the documentation but when I run dotnet husky install from the Project.Api folder I get the following output.

.git can't be found (see https://alirezanet.github.io/Husky.Net/guide/getting-started)
Git hooks installation failed

The .git folder is in the parent project folder, so I guess that makes sense. If I change directories to the parent folder and try running it again, I get,

Could not execute because the specified command or file was not found.
Possible reasons for this include:
  * You misspelled a built-in dotnet command.
  * You intended to execute a .NET program, but dotnet-husky does not exist.
  * You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.

I attempted to install Husky globally and see if that eliminates this problem, but the output was the same afterwards.

I realize this might not be a bug and it might just be me using it in a way that was not intended. Any direction in how I could resolve this would be helpful.

Steps to reproduce

  • Create a new dotnet project
  • Put the new dotnet project inside a parent folder
  • Git init inside the parent folder
  • Attempt to install husky/run husky install

No hooks logs in Visual Studio with Husky.Net

Version

0.5.1

Details

In Visual Studio Enterprise 2022 (64 bits) - Preview Version 17.3.0 Preview 6.0,
I can't view hook error logs.

I can view an error message "One or more errors occurs" but no details when comiting.
No more details in Output window (Git source control section).

I can view logs only if I run a git command line in dos/powershell.

(if I copy the hook directly in Git Hooks folder, that work and I can see error message in VS window)

Any solutions ?

image

Steps to reproduce

  • open a VS solution with git hooks
  • try a bad commit
  • no more information about errors

Add an option to specify git path

Details

Hi!
On some environments we don't have git installed system-wide.
Is there any option to specify git path to a local installation folder?

Extended assembly support for execute

Details

Hello,

while writing a new csx for husky exec I tried to use System.Linq and failed to do so.
This results propably from the static assembly list here:

var opts = ScriptOptions.Default
.WithSourceResolver(new SourceFileResolver(ImmutableArray<string>.Empty, workingDirectory))
.WithImports("System", "System.IO", "System.Collections.Generic", "System.Text", "System.Threading.Tasks");

How about we create a mechanism like the following in a csx file:

// cs_reference System.Linq;
using System.Linq;

Which hints the execution to include that particular assembly.

Greetings
Xemrox

Can not find task-runner.json when running dotnet husky run on Windows

Version

0.4.2

Details

Hello! I have Husky.Net set up working great on my Mac with VS Code. However, my teammates using Visual Studio 2022 on Windows can't get our pre-commit hooks to work.

When I try dotnet husky run from PowerShell on Windows, I get an error message saying "Can not find task-runner.json" even though the file is there right next to pre-commit in the .husky folder. I've tried dotnet husky uninstall then dotnet husky install then dotnet huksy run with the default task-runner.json contents and get the same error.

My directory setup is a solution with multiple projects in their own folders. Husky.NET's .husky folder is at the root. My dotnet commands are all run from the root directory.

Any ideas? Thanks!

Steps to reproduce

On Windows 10
dotnet husky install
dotnet husky run

Get error saying "Can not find task-runner.json"

Attach husky do not work with GIT Worktree

Version

v0.4.2

Details

Husky is attached to my dotnet project as follow

  <Target Name="husky" BeforeTargets="Restore;CollectPackageReferences" Condition="$(MuteHusky) == '' or $(MuteHusky) == false">
    <Exec Command="dotnet tool restore" StandardOutputImportance="Low" StandardErrorImportance="High" />
    <Exec Command="dotnet husky install" StandardOutputImportance="Low" StandardErrorImportance="High" WorkingDirectory="$(BuildRoot)" />
  </Target>

It works fine except if I use GIT Worktree. In this case, I receive the following error:
> dotnet husky install .git can't be found (see https://alirezanet.github.io/Husky.Net/guide/getting-started) Git hooks installation failed
It seems that Husky cannot work with the link ".git" (found in the linked working tree) that references the ".git" directory.

Steps to reproduce

  • Step 1
    attach Husky to a project
  • Step 2
    create a GIT branch "test" and check it out as a new GIT worktree with the command "git worktree add test-dir test"
  • Step 3
    Go in directory "test-dir" and try to compile the project

Include parameter is ignored when no variable is used inside task

Version

0.6.4

Details

I was not super sure if to open this as a bug or as a feature request, still I think the expected behavior differs to how it works now.

If I use the include parameter inside a task, but no variable (e.g. {staged}) is used in the command args, the include filter is completely ignored and the task is executed always, even if there are no changes to files matched by the glob pattern.

e.g.

{
  "tasks": [    
    {
      "name": "npx-lint-staged",
      "group": "pre-commit",
      "command": "npx",
      "args": [
        "lint",
        "staged"
      ],
      "include": [
        "client/**/*"
      ]
    }
  ]
}

If I commit a change in another folder (e.g. server/test.txt), the task npx-lint-staged is executed.

Is this the intended behavior? I think it really confuses the user right now.

Thanks!

Steps to reproduce

  • create a task inside task-runner.json with an "include" parameter populated, but no variable in the command args
  • modify a file with a path not matched by the glob pattern used in step 1
  • commit changes

expected: the task created in step 1 is skipped because no file is matched
actual: the task created in step 1 is executed

`husky run` output doesn't show colors when run from git hooks.

Describe the bug
husky run output doesn't have colors when run from git hooks.

To Reproduce

dotnet husky add .husky/pre-commit "dotnet husky run"

Expected behavior
Should have colored output like normal dotnet husky run command from the terminal.

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows
  • Version 0.2.1

Change `${matched}` to match over results of `git ls-files`

${matched} casts too wide a net and scans/matches too many files by default. It's not usually what one wants because it can potentially end up returning hidden files and scanning the object database under .git/objects that could be very large. I would propose the default behaviour to return matches over files under version control, i.e. those returned by git ls-files. This way,
one shouldn't have to be (too) careful with the variable.

Using 'husky attach' inside multi-project solutions leads to compile errors due to 'husky install' running multiple times

Version

v0.4.4

Details

After you run dotnet husky attach someproject.csproj, and doing so on multiple projects inside a solution to ensure people working on individual projects are forced to use Husky (in my case: formatting in pre-commit hook), leads to the following error:

The process cannot access the file 'D:\Projects\MyProject\.husky\_\.gitignore' because it is being used by another process.
error MSB3073: The command "dotnet husky install" exited with code 1.

It is clear that the error is caused by the parallel build feature of MSBuild, as each project in a solution is being build. I have not yet found a stable, different way of ensuring the dotnet husky install is run only once.

Hand-crafted ways that probably work is do a file-exists test of the .husky folder. But by itself, that is not enough, as Husky won't run unless core.hooksPath of Git is set to .husky, which this command so conveniently does.

Ideally, dotnet husky install should not lock files it reads, or use a mutex of sorts (available cross-platform in dotnet nowadays) to prevent it from running multiple times.

Alternative, without using exclusive locks, dotnet husky install could just check if Husky is already installed and of the correct version. But that still leaves the issue that, if it is not installed yet, that "Rebuild All" will have multiple parallel dotnet husky install running.

Steps to reproduce

  • Create a solution with 2 or more projects (more is better)
  • Run dotnet husky attach for each project
  • Clean project, then Build All.

You will now get the above mentioned error.

PS: I really like Husky.Net. The above is just a minor inconvenience. After trying many different ways of creating cross-platform auto-installed pre-commit hooks for Git, basically nothing worked out of the box, but Husky did. It is awesome!!!!

Chunks tasks can't load csx files in parallel.

Discussed in #92

Originally posted by AlaiyaNetwork September 18, 2023
Hi all, I encountered a few errors when using pre-commit hook with a large number of files in a commit.

1 error:
fatal: Unable to create 'C:/WorkDirectory/.git/index.lock': File exists. Another git process seems to be running in this repository, e.g. an editor opened by 'git commit'. Please make sure all processes are terminated then try again. If it still fails, a git process may have crashed in this repository earlier: remove the file manually to continue.

2 error:
The process cannot access the file 'C:\WorkDirectory\.husky\csx\add-header-to-main.csx' because it is being used by another process.

The first error also occurs when using prettier, not only with custom scripts. But it doesn't cause the script to abort
[Husky] ⚡ Preparing task 'Run prettier'
[Husky] ⚠️ The Maximum argument length '8191' reached, splitting matched files into 16 chunks
[Husky] ⌛ Executing task 'Run prettier' ...
fatal: Unable to create 'C:/WorkDirectory/.git/index.lock': File exists. Another git process seems to be running in this repository, e.g. an editor opened by 'git commit'. Please make sure all processes are terminated then try again. If it still fails, a git process may have crashed in this repository earlier: remove the file manually to continue.
[Husky] ✔ Successfully executed in 2 304ms

This is my custom script:
[Husky] ⚡ Preparing task 'Run add header to main script'
[Husky] ⚠️ The Maximum argument length '8191' reached, splitting matched files into 9 chunks
[Husky] ⌛ Executing task 'Run add header to main script' ...
The process cannot access the file 'C:\WorkDirectory\.husky\csx\add-header-to-main.csx' because it is being used by another process.
The process cannot access the file 'C:\WorkDirectory\.husky\csx\add-header-to-main.csx' because it is being used by another process.
The process cannot access the file 'C:\WorkDirectory\.husky\csx\add-header-to-main.csx' because it is being used by another process.
The process cannot access the file 'C:\WorkDirectory\.husky\csx\add-header-to-main.csx' because it is being used by another process.
fatal: Unable to create 'C:/WorkDirectory/.git/index.lock': File exists. Another git process seems to be running in this repository, e.g. an editor opened by 'git commit'. Please make sure all processes are terminated then try again. If it still fails, a git process may have crashed in this repository earlier: remove the file manually to continue.
❌ Task 'Run add header to main script' failed in 487ms
husky - pre-commit hook exited with code 1 (error)

Prettier task:
{ "name": "Run prettier", "command": "npx", "cwd": "Paylater.BackOffice.ReactApp", "args": [ "prettier", "--plugin", "prettier-plugin-organize-imports", "--ignore-unknown", "--write", "${staged}" ], "pathMode": "absolute" }

Maybe someone has encountered a similar problem and can give me a solution.

error in dotnet husky install

I don't have this problem in version 0.5.4. That's why I use the old version

Version

0.6.0

Details

add command in root sln directory

dotnet husky install

error

failed to execute command 'git'
Could not determine git configuration

Steps to reproduce

  • dotnet new tool-manifest - success
  • dotnet tool install Husky - success
  • dotnet husky install - error

csx return not 0 but git commit sucess finally

Version

0.5.0

Details

image
return 1; has been executed , but the commit has been commited

may i need use Environment.Exit(1) replace return 1?

Steps to reproduce

  • offical demo
  • commit 'error commit message'

Customize Staged variable separator

Discussed in #98

Originally posted by AlaiyaNetwork December 4, 2023
I add this task

{
    "name": "Clean up code",
    "group": "clean-up-code",
    "command": "cmd",
    "pathMode": "relative",
    "args": [
        "/c",
        "dotnet",
        "jb",
        "cleanupcode",
        "My.sln",
        "--profile=Teams: Clean up code",
        "--settings=My.sln.DotSettings",
        "--include=${stages-files}"
    ]
}

And variables:

{
    "name": "stages-files",
    "command": "cmd",
    "args": [
        "/c",
        "git diff --staged --name-only --no-ext-diff --diff-filter=AM | tr '\\n' ';' | sed 's/;$//'"
    ]
}

If I commited none *.cs files:

[Husky]  Preparing task 'Clean up code'
[Husky]  Executing task 'Clean up code' ...
JetBrains Cleanup Code 2023.3 RC 1
Running on x64 OS in x64 architecture, .NET 8.0.0 under Microsoft Windows 10.0.22631
No items were found to cleanup.
  ❌ Task 'Clean up code' failed in 16 864ms
husky - pre-commit hook exited with code 1 (error)

Maybe someone has already had this problem and can suggest a good solution?

Unexpected parameter(s) error with ${staged} variable

Version

v0.5.4

Details

I want format my code with only staged files, so i test the ${staged} variable with an c# script for this.
If i change ${staged} to some hardcoded values e.g. "arg1" it works as expected.

When i run husky i got following errors:

Unexpected parameter(s):
<.husky/test.csx>

Husky v0.5.4

USAGE
  husky exec <path> [options]

DESCRIPTION
  Execute a csharp script (.csx) file

PARAMETERS
* path              The script file to execute

  -a|--args         Arguments to pass to the script Default: .
  --no-cache        Disable caching Default: "False".
  --no-color        Disable color output Default: "False".
  -v|--verbose      Enable verbose output Default: "False".
  -h|--help         Shows help text.

  ? Task 'exec-test' failed in 286ms

A simple echo task works fine but every arg to another command won't.

✔️

  {
      "command": "cmd",
      "args": [
        "/c",
        "echo",
        "${staged}"
      ]
    },

    {
      "name": "Run dotnet format",
      "command": "dotnet",
      "args": [
        "format",
        "--files",
        "${staged}"
      ],
      "include": [
        "**/*.cs"
      ]
    },

Steps to reproduce

  1. Create c# test script in .husky/test.csx to print the args
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Test: {0}", string.Join(",", Args));

return 1;
  1. Create a task step in .husky/task-runner.json
{
  "tasks": [
    {
      "name": "exec-test",
      "command": "dotnet",
      "args": [
        "husky",
        "exec",
        ".husky/test.csx",
        "--args",
        "${staged}"
      ]
    }
  ]
}
  1. Run it
dotnet husky run

Can not find task-runner.json when running dotnet husky run on Windows

Version

v0.5.4

Details

Hello, i'm trying to set up Husky.NET on a new project (.NET Core 6).

When running dotnet husky run keeps returning the error [Husky] ?? Loading tasks ... Can not find task-runner.json, try 'husky install'

When i run the following commands, i get the correct paths:

`// Git Repo Path
git rev-parse --show-toplevel // returns the repo path

// Husky Relative Path
git config --get core.hooksPath // returns the .husky folder`

Already uninstalled and installed, but keeps getting the same error.

Steps to reproduce

On Windows 10
dotnet husky install
dotnet husky run

Get error saying "Can not find task-runner.json"

Improve CSX execution time

Details

Currently, CSX execution is not so efficient it takes about 2 seconds on the first run which is not ideal, I opened this issue to evaluate possible options to solve this problem. the expected behavior is to minimize the Roslyn compiler warming up process.

the minimum execution time for the bellow command currently is about 1-2 seconds.

dotnet husky exec <fileNme.csx>

your current branch does not have any commits yet

Version

0.4.0

Details

Should prevent git exception In a clean new repo, when there are no commits.

Steps to reproduce

  • Step 1: Create a new repo git init
  • Step 2: Install Husky dotnet husky install
  • Step 3: Add pre-commit hook dotnet husky add pre-commit -c "dotnet husky run"
  • Step 4: Add dotnet-format staged task
{
   "tasks": [
      {
         "command": "dotnet",
         "group": "pre-commit",
         "args": [ "dotnet-format", "--include", "${staged}" ],
         "include": [ "**/*.cs", "**/*.vb" ]
      }
   ]
}

Temporary workaround

Adding an empty commit before Step 3 can solve the problem. git commit --allow-empty -m "first commit"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.