Contents

git commit时如何自动添加前缀

功能说明

该钩子可用于在git commit时自动给message添加前缀

使用说明

1 创建commit-msg钩子:

控制台输入:

1
2

npx husky add commit-msg

2 在.husky/下创建hooks/commit-msg.js,并写入以下内容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function getFileContent(filePath) {
  try {
    var buffer = fs.readFileSync(filePath);
    var hasToString = buffer && typeof buffer.toString === 'function';

    return hasToString && buffer.toString();
  } catch (err) {
    if (err && err.code !== 'ENOENT' && err.code !== 'ENAMETOOLONG') {
      throw err;
    }
  }
}
require('dotenv').config({ path: '.env' });
const path = require('path');
const fs = require('fs');
const dotenv = require('dotenv');
const commitMsgPath = process.argv[2];
const gitMsgPath = path.resolve(__dirname, '../../', commitMsgPath);
const prefix = process.env.prefix;
const commitMsg = prefix + getFileContent(gitMsgPath);
let ret = 0;
console.log('this is the commiting message:@@ ', commitMsg);
if (commitMsg.match(/^--(story|bug)=[0-9]+/)) {
  console.log('提交符合规范!@@');
  fs.writeFileSync(gitMsgPath, commitMsg);
} else {
  ret = 1;
  console.log(`提交不符合规范!`);
}
process.exit(ret);

3 将以下内容覆盖到.husky/commit-msg

1
2
3
4
#!/bin/sh

commitFiles=$(git diff --name-only --cached)
sudo node  ./.husky/hooks/commit-msg.js $1 $commitFiles

4 在根目录创建.env文件,并写入以下内容

1
prefix="--story=xxx 你想要添加的前缀"

5 挂载钩子

1
npx husky install