git-commitlint在项目中的运用

1,625 阅读1分钟

github: git-commitlint

目录

  • 背景
  • 安装commitlint
  • 安装husky
  • 安装shelljs
  • 参考资料

背景

在实际项目开发中,经常出现团队成员提交的git log书写规则不统一,很难根据git log来揣测此log的实际含义,也可能会出现不小心提交冲突文件导致测试环境、灰度环境甚至生产环境瘫痪的现象。所以,为规避种种不好的问题出现,可采用commitlint在代码提交之前做相应的git帐户验证判断、代码冲突判断以及git log规则书写是否规范等判断。

安装commitlint

  • 依赖:npm install --save-dev @commitlint/{config-conventional,cli}
  • 创建配置文件commitlint.config.js: echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js

安装husky

  • 依赖:npm install husky --save-dev
  • package.json添加husky配置:
{
  "husky": {
    "hooks": {
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  }
}

安装shelljs

  • npm install shelljs --save-dev
  • 增加 hooks/pre-commit.js文件(引入shelljs 在git commit之前做是否安装git、git帐号邮箱是否符合邮箱规则、是否存在冲突文件)
 require('shelljs/global')
 /**
  * 
  * 检验是否安装git
  * 
 */
 if (!which('git')) {
  echo('Sorry, this script requires git')
  exit(1);
 }
 
 /**
  * 
  * 检验git用户邮箱是否符合 @qq.com 规范
  * 
 */
 const VALID_EMAIL_SUFFIX = '@qq.com'
 //  获取用户git帐户邮箱
 const USER_EMAIL = exec('git config --get user.email').trim()
 if (!USER_EMAIL.endsWith(VALID_EMAIL_SUFFIX)) {
  echo('Sorry, this email does not meet the specifications')
  echo('Please configure the email --@qq.com')
  echo('git config --local user.email {email}')
  exit(1);
 }
 
 /**
  * 
  * 检测是否存在冲突文件
  * 
 */
 const CONFLICT_REG = /(^|\r|\n|\r\n)<{7,8} HEAD|={7,8}(\r|\n|\r\n|$)|>{7,8}.*(\r|\n|\r\n|$)/g
 const CHANGED_FILES = exec('git diff --cached --name-only --relative', { silent: true }).stdout.trim().split('\n')
 const EXCLUDE_FILES = ['node_modules']

 if (CHANGED_FILES) {
   const filter = CHANGED_FILES.filter(file => EXCLUDE_FILES.every(exclude => !file.includes(exclude)))
   const conflict = grep('-l', CONFLICT_REG, filter).stdout.trim()
   if (conflict) {
       echo(`${conflict}\n`)
       echo('The above file conflicts have not been processed, please submit it after processing!')
       exit(1)
   }
 }
  • commit-msg命令前添加pre-commit文件执行命令
{
 "husky": {
   "hooks": {
     "pre-commit": "node ./hooks/pre-commit.js",
     "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
   }
 }
}

参考资料