返回
规避commitlint拦截不规范commit的备用方案:本地正则表达式拦截器
前端
2023-09-28 02:13:03
前言
在现代软件开发中,代码规范和质量控制是至关重要的。commitlint是一个流行的工具,可以帮助开发者强制执行提交消息的规范,从而提高代码的质量和可维护性。
然而,commitlint只能拦截符合通用规范的提交消息,例如<type>(<scope>): <subject>
。当使用的提交消息规范与通用规范有差异时,就很难通过设定commitlint规则集进行拦截。
本文提供了一种备用方案:通过在commitlint.config.js文件中使Commitlint使用正则表达式,可以本地拦截不规范的commit。
正则表达式本地拦截器
要使Commitlint使用正则表达式进行本地拦截,需要在commitlint.config.js文件中添加以下代码:
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'body-leading-blank': [1, 'always'],
'footer-leading-blank': [1, 'always'],
'header-max-length': [2, 'always', 72],
'subject-case': [2, 'never', ['sentence-case', 'start-case', 'pascal-case']],
'subject-empty': [2, 'never'],
'subject-full-stop': [2, 'never', '.'],
'type-case': [2, 'always', 'lower-case'],
'type-empty': [2, 'never'],
'type-enum': [
2,
'always',
['build', 'ci', 'chore', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test']
]
},
plugins: [
{
rules: {
'custom-rule': (parsed, when) => {
// 正则表达式
const regex = /^((feat|fix|docs|style|refactor|perf|test|build|chore|ci|revert)\((.+)\): (.*)|((.+):(.*)))$/;
// 测试提交消息是否符合正则表达式
const result = regex.test(parsed.raw);
// 如果不符合正则表达式,则返回错误消息
if (!result) {
return when('提交消息不符合规范');
}
}
}
}
]
};
上面的代码中,我们定义了一个名为custom-rule的规则,该规则使用正则表达式来测试提交消息是否符合规范。如果提交消息不符合正则表达式,则返回错误消息。
使用正则表达式本地拦截器
要使用正则表达式本地拦截器,需要在终端中运行以下命令:
npx commitlint --edit
这将打开commitlint.config.js文件,可以按照上面的代码添加custom-rule规则。
添加完成后,保存commitlint.config.js文件,即可使用正则表达式本地拦截不规范的commit。
结论
通过在commitlint.config.js文件中使Commitlint使用正则表达式,可以本地拦截不规范的commit。这是一种简单有效的方法,可以提高代码的质量和可维护性。