自定义commit-msg校验规则

得益于某些制定规则的部门,最近提交代码的规范又发生了变更,导致提交错误需要解决,考虑到也不可能以后发生变更日常查文档,于是考虑使用huskygit hooks中进行拦截,整体思路还是拿到提交记录进行正则匹配。

husky

首先需要安装husky

npm i husky -D
npx pkg set scripts.prepare="husky install"
npm run prepare // npx husky install

// or直接配置package.json
{
"script": {
"prepare": "husky install"
}
}
npm run prepare
添加hooks脚本

git hooks中有很多拦截钩子,需要考虑不同阶段使用什么钩子,我这里的应用场景只有本地提交commit时进行拦截校验。

npx husky add .husky/commit-msg

这里会有一个问题,就是husky会将.git仓库中原生hooks进行覆盖。比如我之前commit-msg hook会在commit中添加ChangeId,使用husky就失效了,解决方法就是将原脚本的内容复制到husky目录下的脚本中。

校验函数

进行校验采用的当然还是js,主要还是shell已经忘的差不多了

const path = require('path')
const cwd = Process.cwd()
const fs = require('fs')

const message = fs.readFileSync(path.join(cwd, '.git/COMMIT_EDITMSG'), 'utf-8')

const reg1 = /\[[^\[\]]*\]/g
const reg2 = /\[(feat|fix|docs)\]:\[(.*)\]\[([^\[\]])+\]/g
const reg3 = /\[(docs|style|refactor|test|chore|tag|revert|perf)\]:\[[^\[\]]+\]/g

// 显示正确commit并退出
function showTooltip () {
console.error('--------------------------')
console.error('请检查commit格式')
console.error('[feat]:[单号][xxxx]')
console.error('[feat]:[][xxxx]')
console.error('[fix]:[单号][xxxx]')
console.error('[fix]:[][xxxx]')
console.error('[docs]:[单号][xxxx]')
console.error('[docs]:[xxxx]')
console.error('[style]:[xxxx]')
console.error('[refactor]:[xxxx]')
console.error('[test]:[xxxx]')
console.error('[chore]:[xxxx]')
console.error('[tag]:[xxxx]')
console.error('[revert]:[xxxx]')
console.error('[perf]:[xxxx]')
console.error('--------------------------')
process.exitCode = 1
}

// 检测含中括号信息数
const res1 = message.match(reg1)
if (!res1 || (res1.length !== 2 && res1.length !== 3)) {
showTooltip()
return
}

const res2 = reg2.test(message)
const res3 = reg3.test(message)

// 检测匹配模式
if ((!res2 || res1.length !== 3) && (!res3 || res1.length !== 2)) {
showTooltip()
}
console.log('--------------------------')
console.log('校验通过')
console.log('--------------------------')

Mac问题

Mac下需要修改hook文件的权限

# 先修改hook脚本的权限
chmod ug+x .husky/*
# 再git 提交修改的hook
文章作者: Furo Yang
文章链接: http://furoteam.cn/2023/08/04/自定义commit-msg校验规则/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 furoのBlog