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
fixBug 修复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
ciCI/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”)

用于关联 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~1

5.2 如何修改已 push 的 commit message?

# 修改最后一次 commit
git commit --amend
 
# 如果已经 push,需要 force push(慎用!)
git push --force-with-lease

5.3 Squash 多个小提交

git rebase -i HEAD~3
# 将第二个之后的 pick 改为 squash 或 s

6. 参考资料