Husky 是一个用于 Git 仓库的工具,主要用于管理 Git 钩子(hooks)。它可以帮助开发者在特定的 Git 操作(如提交、推送等)之前或之后执行自定义的脚本或命令,从而提高代码质量和团队协作效率。
主要用在前端项目中,可以通过 Husky.Net,将 Husky 的功能,引入到 .NET 项目中。
alirezanet/Husky.Net: Git hooks made easy with Husky.Net internal task runner! 🐶 It brings the dev-dependency concept to the .NET world!
Welcome | Husky.Net
安装
在代码仓库的根目录中,执行
dotnet new tool-manifest
dotnet tool install Husky
作用是基于 dotnet tool 的机制,安装 Husky 这个工具
执行 husky 命令
dotnet husky install
作用是执行 husky 工具的 install 命令,会生成 .husky 目录
准备
在 .husky 目录下,新建 pre-commit
文件,内容如下
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"dotnet husky run
并在 task-runner.json 中定义自己的任务
{"$schema": "https://alirezanet.github.io/Husky.Net/schema.json","tasks": [{"name": "check-large-files","group": "pre-commit","command": "bash","args": [".husky/check-large-file.sh"]}]
}
作用就是在 git 提交之前,执行 dotnet husky run
,最终就会执行到 task-runner.json
中定义的任务。
我这里定义的任务就是运行 check-large-file.sh 这个脚本(文件也放在了 .husky 文件夹中)。这里命令的执行,是基于项目根目录中的。
check-large-file.sh 的具体内容,参见 git 禁止大文件提交到仓库中 | 晒太阳的猫 中 pre-commit
文件的内容
执行
这样,则之后进行 git commit 时,就会执行到这段自定义的脚本,检查提交的文件大小是否合规。
如果出现错误,执行效果如下:
团队协作
将上述操作生成的 .config
和 .husky
中的内容,提交到代码仓库中。
并在一个 csproj 项目中(通常是入口的那个 csproj),添加如下内容
Automate installation for other contributors | Husky.Net
<Target Name="husky" BeforeTargets="Restore;CollectPackageReferences" Condition="'$(HUSKY)' != 0"><Exec Command="dotnet tool restore" StandardOutputImportance="Low" StandardErrorImportance="High"/><Exec Command="dotnet husky install" StandardOutputImportance="Low" StandardErrorImportance="High"WorkingDirectory="../../" /> <!--Update this to the relative path to your project root dir -->
</Target>
也可以通过 dotnet husky attach <path-to-project-file>
自动添加。
这样,其他团队成员在打开项目之后,就会自动执行 dotnet tool restore
和 dotnet husky install
延伸
可以配合 csharpier,对提交的代码做自动格式化。
不过更建议配置 csharpier 在保存代码的时候,自动做格式化,这样能具体看到代码都格式化成什么样子了。
Pre-commit Hook | CSharpier
参考:mapperly/.husky at main · riok/mapperly
参考文献
Autoformatting with Husky.NET | Anthony Steele
Format and Automate .NET Project with Husky.Net Git hooks | CodeNx