前端之路:用 Angular 規範來約束團隊 git 提交

CommitMsg

git 提交規範node

背景

團隊協做開發,git 做爲一個開源的分佈式版本控制系統,儼然成爲當下最受歡的項目代碼版本管理工具, 便是團隊,就要有必定的規矩,規範,這樣才能更好的發揮團隊效率。熟悉 git 的小夥伴都知道,每次提交代碼, 都要寫 Commit message(提交說明),不然就不容許提交,至於提交的信息 git 並無進行約束,以致於, 提交上來的說明是五花八門,由此社區出現了多種寫法規範,其中 Angular 規範 是目前最爲普遍的寫法,比較合理和系統化。 本文就來說一講兩種使用 Angular 規範的方法。git

法一,基於項目經過 hooks 觸發(我司團隊用的此方法)

這種方法的好處是,任何人只要想往本項目提交 commit,就必須按照規範,不然不讓提交。github

  1. 安裝所需依賴,npm i --save-dev husky chalk
  2. 在項目的根目錄新建一個文件夾 .github (名字隨意),這個文件夾專門用來存放 github 相關的東西;
  3. 在上一步的文件夾中新建 node 腳本文件 verifyCommitMsg (名字隨意);
  4. 在上一步的腳本文件中寫入如下代碼:
#!/bin/env node

const chalk = require('chalk');
const msgPath = process.env.HUSKY_GIT_PARAMS;
if (!msgPath) {
  console.error(chalk.red(`process.env.HUSKY_GIT_PARAMS can't be ${msgPath},please check`));
  process.exit(1);
}
console.log('HUSKY_GIT_PARAMS: ', msgPath);
const msg = require('fs')
  .readFileSync(msgPath, 'utf-8')
  .trim();
console.log(msg);

const commitRE = /^(revert: )?(feat|fix|docs|style|refactor|perf|test|workflow|ci|chore|types)(\(.+\))?: .{1,50}/;

if (!commitRE.test(msg) && !/merge/ig.test(msg)) {
  console.log();
  console.error(
    `  ${chalk.bgRed.white(' ERROR ')} ${chalk.red(`invalid commit message format.`)}\n\n` +
      chalk.red(
        `  Proper commit message format is required for automated changelog generation. Examples:\n\n`
      ) +
      `    ${chalk.green(`feat(compiler): add 'comments' option`)}\n` +
      `    ${chalk.green(`fix(v-model): handle events on blur (close #28)`)}\n\n` +
      chalk.red(`  See .github/COMMIT_CONVENTION.md for more details.\n`)
    // chalk.red(`  You can also use ${chalk.cyan(`npm run commit`)} to interactively generate a commit message.\n`)
  );
  process.exit(1);
}
複製代碼
  1. package.json 增長/修改 hooks,以下:
...
"husky": {
  "hooks": {
    "commit-msg": "node .github/verifyCommitMsg"
  }
},
...
複製代碼

這樣就作到了每次提交都會檢查 commit 信息了,當不符合規範時,會給出提示。 例如:npm

method1

法二,基於 npm 依賴插件

這種方法的好處是,提交比較人性化。json

  1. 全局安裝依賴,npm i -g commitizen
  2. 初始化適配器,commitizen init cz-conventional-changelog --save-dev --save-exact
  3. git cz 命令 代替 git commit

例如:分佈式

method2

===🧐🧐 文中不足,歡迎指正 🤪🤪===svg

相關文章
相關標籤/搜索