用commitlint規(guī)范團(tuán)隊(duì)的git提交信息

閱讀完本文預(yù)計(jì)需要5分鐘,讀完一定要記得實(shí)踐哦。

在一個(gè)團(tuán)隊(duì)中,每個(gè)人的git的commit信息都不一樣,五花八門,沒有一個(gè)機(jī)制很難保證規(guī)范化,如何才能規(guī)范化呢?可能你想到的是git的hook機(jī)制,去寫shell腳本去實(shí)現(xiàn)。這當(dāng)然可以,其實(shí)JavaScript有一個(gè)很好的工具可以實(shí)現(xiàn)這個(gè)模板,它就是commitlint。

接下來將會(huì)講解如何一步步的使用commitlint。

一般情況下,commitlint會(huì)用在git的hook回調(diào)中,最簡(jiǎn)單的就是和 husky一起使用。

前提條件是工程是通過git管理的,如果沒有先自己創(chuàng)建一個(gè)demo工程,用git初始化一下。

比如創(chuàng)建一個(gè)commitlint-test工程:

mkdir commitlint-test
cd commitlint-test
git init

npm 工程初始化

npm init

安裝commitlint

安裝依賴

npm install --save-dev @commitlint/{cli,config-conventional}

在工程更目錄添加配置文件commitlint.config.js

echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js

commitlint.config.js文件內(nèi)容如下:

module.exports = {
    extends: ['@commitlint/config-conventional'],
};

extends字段表示擴(kuò)展子@commitlint/config-conventional的配置。一般擴(kuò)展這個(gè)就足夠了,這是利用的commitlint的配置擴(kuò)展機(jī)制,可以繼承其他人的配置。

安裝husky

husky是一個(gè)git hook的管理工具,實(shí)現(xiàn)了大部分的git hook,有興趣的可以自行g(shù)oogle。

npm install --save-dev husky

在package.json中配置husky. hooks

// package.json
{
  "husky": {
    "hooks": {
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }  
  }
}

通過HUSKY_GIT_PARAMS傳遞參數(shù),-E|--env用于指向相關(guān)的編輯文件。

測(cè)試

如果不符合規(guī)則,將無法使用git進(jìn)行commit,比如下面的,如果想知道有什么規(guī)則,可以繼續(xù)往下看。

git commit -m "foo: this will fail"
husky > npm run -s commitmsg
?   input: foo: this will fail
?   type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test] [type-enum]
?   found 1 problems, 0 warnings
husky > commit-msg hook failed (add --no-verify to bypass)
git commit -m "chore: lint on commitmsg"
husky > npm run -s commitmsg
?   input: chore: lint on commitmsg
?   found 0 problems, 0 warnings

規(guī)則

git commit的消息這樣組成:
其中header是必須有的,body,footer可選。

header 
--空一行
body
--空一行
footer

header的規(guī)則

Commit message格式,注意冒號(hào)后面有空格

<type>: <subject>

type
用于說明 commit 的類別,只允許使用下面7個(gè)標(biāo)識(shí),也可以自己在配置文件中更改或者擴(kuò)展。
標(biāo)準(zhǔn)類型如下:
feat:新功能(feature)
fix:修補(bǔ)bug
docs:文檔(documentation)
style: 格式方面的優(yōu)化
refactor:重構(gòu)
test:測(cè)試
chore:構(gòu)建過程或輔助工具的變動(dòng)

subject
subject是 commit 的簡(jiǎn)短描述,不能超過50個(gè)字符,且結(jié)尾不加英文句號(hào)。

如果type為feat和fix,則該 commit 將肯定出現(xiàn)在 Change log 之中。

參考:
https://conventional-changelog.github.io/commitlint/#/
https://conventional-changelog.github.io/commitlint/#/reference-rules

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容