likes
comments
collection
share

利用husky和commitlint进行git的敏感词拦截提交

作者站长头像
站长
· 阅读数 31

最近接到一个需求,由于公司的安全级别提升了,一些敏感词不能出现在git的提交信息中,比如"完成5G通讯功能","5G"就是敏感词,或者"室温超导研究","室温超导"就是敏感词,等等。为了防止新老同事将一些敏感词写在commit message提交信息中,造成gitlab和磁盘污染,要在提交代码的时候做一次message的检测,如果检测到含敏感词就不让提交。如以下: 利用husky和commitlint进行git的敏感词拦截提交

研究了一阵子,发现commitlint的plugins功能可以实现这个需求,演示如下。

首先创建一个项目,这里用vite演示

npm create vite
...

然后初始化git仓库,这一步很重要

git init

在package.json中添加以下脚本

"prepare": "husky install"

安装husky和commitlint

yarn add husky commitlint @commitlint/cli @commitlint/config-conventional -D

将commitlint集成到husky中

npx husky add .husky/commit-msg "npx --no-install commitlint -e $HUSKY_GIT_PARAMS"

新建.commitlintrc.cjs文件

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

新建一个敏感词文件forbidanWords.cjs,以后就是用这个文件来统一维护敏感词

const keyword = ['敏感词']

module.exports = {
    keyword,
}

修改一下.commitlintrc.cjs

const { keyword } = require('./forbidanWords.cjs')

module.exports = {
    extends: ['@commitlint/config-conventional'],
    rules: {
        'forbidan-keyword': [2, 'always'],
    },
    plugins: [
        {
            rules: {
                'forbidan-keyword': ({ subject }) => {
                    const reg = new RegExp(`(${keyword.join('|')})`, 'g')
                    return [!reg.test(subject), `含有敏感词--${subject?.match(reg)?.join('')}`]
                },
            },
        },
    ],
}

这样就完成了敏感词的拦截配置了,让我们来测试一下:

git add .
git commit -m "敏感词"

利用husky和commitlint进行git的敏感词拦截提交

报错显示我们没有按照规范提交。我们再按照规范的去提交一下:

git add .
git commit -m "feat(all): 敏感词"

利用husky和commitlint进行git的敏感词拦截提交 自此,敏感词的提交拦截需求就完成了。

转载自:https://juejin.cn/post/7208711636494975031
评论
请登录