Git Commit校验

  • 2019 年 11 月 3 日
  • 笔记

环境要求:

  • nodejs
  • git

一、初始化nodejs项目:

在我们iOS项目的根目录下执行下面命令:这条命令会在项目根目录生成package.json配置文件。

npm init -y

二、然后安装husky,commitlint相关依赖:

npm install --save-dev @commitlint/config-conventional @commitlint/cli husky

三、在项目根目录新建commitlint.config.js配置文件,并加入下面的代码:

这下面是我们自己写的commit规则,只允许type为以下三个名称才能提交成功:taskstorybug。这里三个分别代表:完成某个任务、完成某个需求、修复某个bug。当然你也可以根据你们项目添加自己的type

commitlint GitHub链接

commitlint rules配置规则

const types = [    'task',    'story',    'bug'  ];    typeEnum={    rules:{      'type-enum': [2, 'always', types]    },    value:() => types  }    module.exports = {    extends: [      "@commitlint/config-conventional"    ],      rules: {          'body-leading-blank': [1, 'always'],          'footer-leading-blank': [1, 'always'],          'header-max-length': [2, 'always', 72],          'scope-case': [2, 'always', 'sentence-case'],          'subject-case': [2,'always','sentence-case'],          'subject-empty': [2, 'never'],          'subject-full-stop': [2, 'never', '.'],          'type-case': [2, 'always', 'lower-case'],          'type-empty': [2, 'never'],          'type-enum': typeEnum.rules['type-enum']      }  };

四、在项目根目录新建parser-preset.js配置文件,并加入下面的代码:

module.exports = {    parserOpts: {        headerPattern: /^(task|story|bug)((S+))?: d+-(?!-)[S]+$/,        headerCorrespondence: ['type', 'scope']    }  };  在package.json中加入下面的代码:    {    "husky": {      "hooks": {        "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"      }    }  }

完成

到这里就已经配置完成了。你可以试着提交一次代码验证是否成功。 以后提交的格式只能为以下三种:

task: xxx    //完成某个任务  story: xxx  //完成某个需求  bug: xxx   //修复某个bug

其它任何格式都将无法提交成功。这样做的好处就是以后多人开发中,commit message清晰明了。