Git Commit 规范化实践 - 告别手动输入表情符号

44 阅读2分钟

写在前面

之前我一直手动在 commit 信息前加表情符号,比如 ✨ feat: xxx🐛 fix: xxx,每次都要去找对应的 emoji,有时候还会遗漏,挺麻烦的。最近发现了 commitizen + cz-git 这套方案,可以通过交互式界面自动生成规范的提交信息,分享给大家。

顺便推荐一下我在维护的开源项目 gocron - 一个 Go 写的分布式定时任务管理系统,用来替代 Linux crontab 的,支持 Web 界面、秒级精度、任务依赖等功能。欢迎 Star ⭐️

对比效果

之前手动输入:

 feat: add task dependency feature  # 每次都要复制粘贴 emoji
🐛 fix: fix status update issue

现在交互式选择:

pnpm run commit
# 选择类型、范围、填写描述,自动生成带 emoji 的规范提交

在gocron项目中使用案例

gocron 项目已经配置好了,直接使用:

cd gocron
pnpm install
pnpm run prepare

# 提交代码
git add .
pnpm run commit

在自己项目中配置

1. 安装依赖

pnpm add -D @commitlint/cli @commitlint/config-conventional commitizen cz-git husky

2. 创建配置文件

创建 commitlint.config.cjs

module.exports = {
  extends: ['@commitlint/config-conventional'],
  prompt: {
    types: [
      { value: "✨ feat",     name: "feat:     ✨ 新增功能" },
      { value: "🐛 fix",      name: "fix:      🐛 修复缺陷" },
      { value: "📝 docs",     name: "docs:     📝 文档变更" },
      { value: "💄 style",    name: "style:    💄 代码格式" },
      { value: "♻️ refactor", name: "refactor: ♻️ 代码重构" },
      { value: "⚡️ perf",     name: "perf:     ⚡️ 性能优化" },
      { value: "✅ test",     name: "test:     ✅ 添加测试" },
      { value: "📦️ build",    name: "build:    📦️ 构建变更" },
      { value: "🎡 ci",       name: "ci:       🎡 CI 配置" },
      { value: "⏪️ revert",   name: "revert:   ⏪️ 回滚" },
      { value: "🔨 chore",    name: "chore:    🔨 其他修改" }
    ],
    skipQuestions: ['breaking', 'footerPrefix', 'footer']
  }
}

3. 修改 package.json

{
  "scripts": {
    "prepare": "husky",
    "commit": "git-cz"
  },
  "config": {
    "commitizen": {
      "path": "node_modules/cz-git"
    }
  }
}

4. 初始化 husky

pnpm run prepare
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg

使用

git add .
pnpm run commit

按提示操作:

  1. 选择提交类型(自动带 emoji)
  2. 选择影响范围(可选)
  3. 填写简短描述
  4. 确认提交

提交类型说明

类型说明示例
feat新功能✨ feat(task): 添加任务依赖配置
fixBug 修复🐛 fix(api): 修复状态更新异常
docs文档📝 docs: 更新 API 文档
style代码格式💄 style: 统一代码缩进
refactor重构♻️ refactor: 重构任务调度逻辑
perf性能优化⚡️ perf: 优化查询性能
test测试✅ test: 添加单元测试
build构建📦️ build: 升级依赖
ciCI 配置🎡 ci: 添加 GitHub Actions
revert回滚⏪️ revert: 回滚某功能
chore其他🔨 chore: 更新 .gitignore

相关链接


如果觉得有用,欢迎给 gocron 点个 Star ⭐️