閱讀完本文預(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灭忠。
接下來將會講解如何一步步的使用commitlint膳算。
一般情況下,commitlint會用在git的hook回調(diào)中弛作,最簡單的就是和 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)的編輯文件娱俺。
測試
如果不符合規(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格式验庙,注意冒號后面有空格
<type>: <subject>
type
用于說明 commit 的類別顶吮,只允許使用下面7個(gè)標(biāo)識,也可以自己在配置文件中更改或者擴(kuò)展粪薛。
標(biāo)準(zhǔn)類型如下:
feat:新功能(feature)
fix:修補(bǔ)bug
docs:文檔(documentation)
style: 格式方面的優(yōu)化
refactor:重構(gòu)
test:測試
chore:構(gòu)建過程或輔助工具的變動(dòng)
subject
subject是 commit 的簡短描述悴了,不能超過50個(gè)字符,且結(jié)尾不加英文句號违寿。
如果type為feat和fix湃交,則該 commit 將肯定出現(xiàn)在 Change log 之中。
參考:
https://conventional-changelog.github.io/commitlint/#/
https://conventional-changelog.github.io/commitlint/#/reference-rules