Git Hooks 与提交规范自动化
规范靠人自觉,通常三周就废了。钩子(hooks)是把规范变成机器检查的最省事办法:提交前自动跑,不合格就拦住。
一、Git 原生钩子
.git/hooks/ 下有 pre-commit.sample 之类的一堆样例,去掉后缀就能用。常用的四个:
| 钩子 | 时机 | 典型用途 |
|---|---|---|
pre-commit | git commit 前 | 格式化、lint、跑单测 |
commit-msg | 编辑完提交信息后 | 校验提交信息格式 |
pre-push | git push 前 | 跑更重的测试 |
post-checkout | 切分支后 | 自动装依赖 |
问题很明显:.git/hooks 不进版本库,团队没法共享。所以有了工具层。
二、Husky(JS 生态最常用)
npm i -D husky lint-staged
npx husky init
.husky/pre-commit:
npx lint-staged
package.json:
{
"lint-staged": {
"*.{ts,tsx,js}": ["eslint --fix", "prettier --write"],
"*.{css,md,json}": ["prettier --write"]
}
}
lint-staged 只处理本次暂存的文件,所以钩子很快。
提交信息校验,.husky/commit-msg:
npx --no -- commitlint --edit "$1"
配 commitlint.config.cjs 强制 Conventional Commits:
module.exports = { extends: ['@commitlint/config-conventional'] };
三、Lefthook(跨语言,配置更清晰)
# lefthook.yml
pre-commit:
parallel: true
commands:
lint:
glob: "*.{ts,js}"
run: npx eslint --fix {staged_files} && git add {staged_files}
fmt:
glob: "*.{css,md}"
run: npx prettier --write {staged_files} && git add {staged_files}
commit-msg:
commands:
msg:
run: npx commitlint --edit {1}
Go、Python、Rust 项目也都能用,不依赖 npm。
四、提交信息的典型规范
<type>(<scope>): <subject>
<body>
<footer>
type 常用的几个:feat、fix、docs、style、refactor、perf、test、chore、build、ci。
好处不是好看,是能自动生成 CHANGELOG、自动判断版本号该升哪一位。
五、绕开钩子
git commit --no-verify -m "wip" # 跳过 pre-commit 与 commit-msg
git push --no-verify # 跳过 pre-push
紧急情况能用,但别养成习惯。CI 里应该再跑一遍同样的检查,钩子只是提前反馈,不能当唯一防线。
六、钩子该做什么、不该做什么
该做:格式化、lint 快速项、提交信息校验、敏感文件检查(别把 .env 提交上去)。
不该做:完整构建、集成测试、拉网络依赖。这些放 CI。
判断标准很简单:钩子超过 10 秒,人就会开始用 --no-verify,那就等于没有。