项目中对提交信息进行校验总结

96 阅读1分钟

对提交信息进行校验是团队开发中的常见需求,这里通过利用git hook和husky的能力实现对提交信息的校验

首选创建一个项目,然后执行如下命令

git init 

安装husky

husky官网

执行如下命令对husky进行初始化

pnpm add --save-dev husky
pnpm exec husky init

创建git hook 脚本

.husky目录下新建commit-msg文件(这个文件名就对应了相应的 git hook)

文件内容如下:

#!/bin/sh
#. "$(dirname "$0")/_/husky.sh"
node ./.husky/pre-commit.js

创建具体的校验规则文件pre-commit.js


const fs = require('fs');
const path = require('path');

const msgPath = path.join(__dirname, '../', '.git/COMMIT_EDITMSG');
const msg = fs.readFileSync(msgPath, 'utf8').trim();
const commitMsgRegex = /^Des[^;]*;PN[^;]*;Author[^;]*;Date.*/;
const target = msg.replace(/\s/g, "");
if (!commitMsgRegex.test(target)) {
    console.error('\x1b[31m', '提交信息格式错误,必须包含 "Des:", "PN:", "Author:", "Date:" 四个字段并填写对应信息。');
    process.exit(1);
}

检查 package.json文件是否正确

{
  "dependencies": {
    "husky": "^9.0.11"
  },
  "scripts": {
    "prepare": "husky",
    "test": "echo husky test"
  }
}

测试

提交不合规的提交信息

image.png

提交合规的信息

image.png