
Git Hooks:使用 Pre-commit 和 Pre-push 自动化代码质量检查
Git hooks 在 Git 工作流的关键节点自动运行脚本。
Hook 类型
pre-commit 每次提交前(运行 lint/测试)
prepare-commit-msg 修改提交消息模板
commit-msg 验证提交消息格式
pre-push 推送前(运行集成测试)
post-merge 合并后(安装依赖)
pre-rebase 变基前
手动设置 Hook
# 创建 pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
npm run lint
if [ $? -ne 0 ]; then
echo "Lint failed. Commit aborted."
exit 1
fi
EOF
chmod +x .git/hooks/pre-commit
Husky - 现代 Hook 管理
# 安装 Husky
npm install -D husky
npx husky init
# init 命令会创建 .husky/ 目录
# .husky/pre-commit
#!/bin/sh
npx lint-staged
# .husky/commit-msg
#!/bin/sh
npx --no -- commitlint --edit $1
# .husky/pre-push
#!/bin/sh
npm test
lint-staged - 在暂存文件上运行 Linter
// package.json
{
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{js,jsx}": "eslint --fix",
"*.{css,scss}": "prettier --write",
"*.{md,json}": "prettier --write"
}
}
commitlint - 约定式提交
npm install -D @commitlint/cli @commitlint/config-conventional
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [2, 'always', [
'feat', 'fix', 'docs', 'style',
'refactor', 'test', 'chore', 'revert'
]],
'subject-max-length': [2, 'always', 72],
}
};
Post-merge Hook
# .husky/post-merge
#!/bin/sh
# 如果 package.json 发生变化则重新安装
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
if echo "$changed_files" | grep -q "package.json"; then
echo "package.json changed, reinstalling dependencies..."
npm install
fi
绕过 Hooks
# 在需要时跳过 hooks(谨慎使用)
git commit --no-verify -m "WIP: skip hooks"
git push --no-verify
团队级配置
// package.json
{
"scripts": {
"prepare": "husky"
}
}
prepare 脚本会在 npm install 后自动运行,确保所有团队成员都设置了 hooks。
Git hooks 在代码到达仓库之前强制执行代码质量检查。