git 配置commit-msg

发布时间 2023-04-27 13:03:03作者: unfetteredman

git 配置commit-msg

# 安装husky
npm install husky -D
# 设置运行脚本并运行
npm set-script prepare "husky install"
npm run prepare

# 安装commitlint 根据操作系统选一种
# Install and configure if needed
npm install --save-dev @commitlint/{cli,config-conventional}
# For Windows:
npm install --save-dev @commitlint/config-conventional @commitlint/cli

# 添加hooks及赋权
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
chmod a+x .husky/commit-msg

# 生成commitlint.config.js
# Configure commitlint to use conventional config 
echo "module.exports = { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js

在package.json中配置husky. hooks

{
  "husky": {
    "hooks": {
      "pre-commit": "echo 准备提交",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
      "pre-push": "echo 准备推送"
    }
  }  
}

通过HUSKY_GIT_PARAMS传递参数,-E|--env用于指向相关的编辑文件。

 

一般情况下,默认的就够用了。
当然,如果需要自定义限制这些规则,不启用默认的规则,可以把配置写的更详细

module.exports = {
  extends: [
    "@commitlint/config-conventional"
  ],
  rules: {
    'type-enum': [2, 'always', [
     "build", // 编译相关的修改,例如发布版本、对项目构建或者依赖的改动
        "feat", // 新功能
        "fix", // 修补bug
        "docs", // 文档修改
        "style", // 代码格式修改, 注意不是 css 修改
        "refactor", // 重构
        "perf", // 优化相关,比如提升性能、体验
        "test", // 测试用例修改
        "revert", // 代码回滚
        "ci", // 持续集成修改
        "config", // 配置修改
        "chore", // 其他改动
     ]],
    'type-case': [0],
    'type-empty': [0],
    'scope-empty': [0],
    'scope-case': [0],
    'subject-full-stop': [0, 'never'],
    'subject-case': [0, 'never'],
    'header-max-length': [0, 'always', 72]
  }
};

 

rule配置说明::rule由name和配置数组组成,如:'name:[0, 'always', 72]',数组中第一位为level,可选0,1,2,0为disable,1为warning,2为error,第二位为应用与否,可选always|never,第三位该rule的值。
具体配置项参考其官方文档

 

正确的例子

git commit -m 'feat: 增加 xxx 功能'

scope 指 commit 的范围(哪些模块进行了修改)
subject 指 commit 的简短描述
body 指 commit 主体内容(长描述)
footer 指 commit footer 信息
type 指当前 commit 类型,一般有下面几种可选类型: