要在 Git 提交前运行代码检查工具并在测试失败时阻止提交,可通过配置 Git 钩子(Hooks) 实现,核心是使用 pre-commit 钩子。以下是详细配置步骤:

🔧 一、核心方法:配置 pre-commit 钩子
手动创建钩子脚本(原生方式)

创建或修改 pre-commit 文件

进入 Git 仓库的 .git/hooks/ 目录:

      cd .git/hooks/

复制示例文件并重命名:

      cp pre-commit.sample pre-commit

编辑 pre-commit 文件,添加检查脚本[citation:1][citation:7]:

      #!/bin/sh
 # 运行代码检查工具(示例:ESLint)
 eslint . --ext .js,.jsx
 # 检查返回值,失败则阻止提交
 if [ $? -ne 0 ]; then
     echo "❌ 代码检查失败!请修复问题后再提交。"
     exit 1
 fi

设置可执行权限

  chmod +x .git/hooks/pre-commit

验证工具安装

确保项目中已安装检查工具(如 ESLint)[citation:1]:
npm install eslint --save-dev

使用 pre-commit 框架(推荐)

安装框架

  pip install pre-commit

创建配置文件

在项目根目录创建 .pre-commit-config.yaml,定义检查规则[citation:3][citation:6][citation:8]:
repos:
repo: https://github.com/pre-commit/pre-commit-hooks

   rev: v4.4.0
   hooks:

id: trailing-whitespace # 删除行尾空格

id: end-of-file-fixer # 确保文件以换行符结束

repo: https://github.com/psf/black

   rev: 23.7.0
   hooks:

id: black # Python 代码格式化

repo: https://github.com/PyCQA/flake8

   rev: 6.1.0
   hooks:

id: flake8 # Python 代码规范检查

安装钩子

  pre-commit install

测试运行

  pre-commit run --all-files  # 手动触发检查

使用 Husky + lint-staged(Node.js 项目)

安装依赖

  npm install husky lint-staged --save-dev

初始化 Husky

  npx husky init

配置 lint-staged

在 package.json 中定义[citation:4][citation:5]:
“lint-staged”: {
.{js,jsx}": “eslint --fix”,
"
.{css,scss}”: “stylelint --fix”

添加钩子脚本

编辑 .husky/pre-commit:
#!/bin/sh
npx lint-staged

⚙️ 二、扩展功能:集成其他检查
单元测试

在 pre-commit 脚本中添加测试命令[citation:1]:
# 运行单元测试
npm test
if [ $? -ne 0 ]; then
echo “❌ 单元测试失败!”
exit 1
fi

提交信息规范检查

使用 commit-msg 钩子 + Commitlint[citation:4][citation:5]:
# 安装工具
npm install @commitlint/cli @commitlint/config-conventional --save-dev

配置 .husky/commit-msg

npx commitlint --edit $1

⚠️ 三、注意事项
钩子同步问题

.git/hooks/ 中的钩子不会自动同步到仓库。

解决方案:

使用 pre-commit 或 Husky 等框架,配置文件可纳入版本控制[citation:3][citation:6]。

手动钩子脚本需通过其他方式共享(如脚本模板)。
跳过检查(紧急情况)

添加 --no-verify 参数跳过钩子[citation:3]:
git commit -m “紧急修复” --no-verify

性能优化

仅检查暂存区文件:使用 git diff --staged 而非全量扫描[citation:2]。

对大型项目,用 lint-staged 仅检查修改的文件[citation:5]。

💎 总结
简单场景:手动编写 pre-commit 脚本(适合少量检查)。

多语言/复杂规则:用 pre-commit 框架(支持丰富插件)[citation:3][citation:8]。

前端项目:选 Husky + lint-staged(高效且易维护)[citation:4][citation:5]。

配置后,每次 git commit 会自动触发检查,失败时阻止提交并输出错误,确保代码质量[citation:1][citation:7]。

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐