Skip to content

在 .NET 项目中使用 husky 完成 pre-commit 操作

Published: at 18:00

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

安装

在代码仓库的根目录中,执行

Terminal window
dotnet new tool-manifest
dotnet tool install Husky

作用是基于 dotnet tool 的机制,安装 Husky 这个工具

执行 husky 命令

Terminal window
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 restoredotnet husky install

延伸

可以配合 csharpier,对提交的代码做自动格式化。 不过更建议配置 csharpier 在保存代码的时候,自动做格式化,这样能具体看到代码都格式化成什么样子了。

Pre-commit Hook | CSharpier

参考:mapperly/.husky at main · riok/mapperly

问题补充

添加了上述的 husky 配置之后,因为这里 task-runner 中配置使用了 bash 命令,在 Visual Studio 中提交代码时,默认是使用 cmd 来执行 git 命令的。

此时可能无法正确执行 bash,需要将 git 安装目录中的 bin 目录,通常是 C:\Program Files\Git\bin 添加到环境变量,而且是第一个(确保在 %SystemRoot%\system32 之前)

验证方式,在 C 盘根目录运行 cmd 命令行(不是 powershell, 也不是其它 bash 命令行),执行 where bash

Terminal window
c:\>where bash
C:\Program Files\Git\bin\bash.exe

git bin 目录下的 bash 应该在第一个

参考文献

Autoformatting with Husky.NET | Anthony Steele

Format and Automate .NET Project with Husky.Net Git hooks | CodeNx


原文链接: https://blog.jgrass.cc/posts/husky-in-net/

本作品采用 「署名 4.0 国际」 许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。