Git Commit 规范
1. 基本原则
| 原则 | 说明 |
|---|---|
| 原子性 | 每个 commit 只做一件事,避免混杂多个无关改动 |
| 独立性 | 每个 commit 可以独立测试、撤销或回滚 |
| 有意义的提交信息 | 让代码审查者和未来的自己能够快速理解意图 |
2. Commit Message 格式
2.1 格式结构
<type>(<scope>): <subject>
<body>
<footer>
2.2 Type 类型
| Type | 说明 | 示例 |
|---|---|---|
feat | 新功能 | feat(auth): add OAuth2 login support |
fix | Bug 修复 | fix(api): handle null response in /users |
docs | 仅文档变更 | docs: update README deployment section |
style | 不影响代码逻辑的格式调整 | style: format code with prettier |
refactor | 重构(既非修复也非新功能) | refactor(db): extract connection pool |
perf | 性能优化 | perf: lazy load images in dashboard |
test | 新增或修改测试 | test: add unit tests for validator |
chore | 构建流程、工具、依赖更新 | chore: upgrade to Node 20 LTS |
ci | CI/CD 配置变更 | ci: add GitHub Actions cache |
build | 构建系统或外部依赖变更 | build: migrate from webpack to vite |
revert | 回滚之前的提交 | revert: revert abc1234 |
2.3 Scope 作用域(可选)
表示影响的具体模块或范围:
feat(auth):—认证模块fix(ui):— 用户界面fix(api/users):— API 中的用户模块
2.4 Subject 主题
- 使用动词开头,用第一人称过去式或现在时
- 首字母小写(大多数项目约定)
- 不超过 50 个字符
- 不以句号结尾
- 清晰表达 ” 做了什么 “
2.5 Body 正文(可选)
- 解释 what 和 why,而非 how
- 每行不超过 72 个字符
- 使用 未来式 而非过去式(“add feature” 而非 “added feature”)
2.6 Footer 脚注(可选)
用于关联 Issue 或关闭 Bug:
Closes #123
Fixes #456
Refs #789
3. 示例
✅ 好的 Commit
feat(billing): add Stripe payment integration
- Integrate Stripe Checkout for one-time payments
- Store payment intent IDs in database
- Send confirmation email on successful payment
Closes #234
fix(auth): prevent session hijacking on token refresh
Previously, refresh tokens were not rotated, making them vulnerable
to replay attacks. This change implements token rotation per RFC 6819.
Fixes #891
❌ 不好的 Commit
| 写法 | 问题 |
|---|---|
fix bug | 过于模糊 |
update | 没有说明更新了什么 |
WIP | 未完成的工作 |
asdfasdf | 乱码 |
fix stuff | 同上,模糊不清 |
4. Commit 规范检查
4.1 CommitLint(推荐)
安装并配置 commitlint 强制校验格式:
npm install --save-dev @commitlint/config-conventional @commitlint/cli// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'subject-case': [2, 'never', ['sentence-case', 'start-case', 'pad-space']],
'type-enum': [
2,
'always',
['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'ci', 'build', 'revert'],
],
},
};4.2 Git Hooks
使用 Husky 在 commit 时自动触发检查:
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'5. 常见问题
5.1 提交错了分支怎么办?
# 撤销最近一次 commit(保留修改)
git reset --soft HEAD~1
# 完全撤销(不保留修改)
git reset --hard HEAD~15.2 如何修改已 push 的 commit message?
# 修改最后一次 commit
git commit --amend
# 如果已经 push,需要 force push(慎用!)
git push --force-with-lease5.3 Squash 多个小提交
git rebase -i HEAD~3
# 将第二个之后的 pick 改为 squash 或 s6. 参考资料
- Conventional Commits v1.0.0
- Git Commit Messages — thoughtbot
- Angular Commit Message Format