自定义hook脚本,拦截Git的commit命令

发布于:2025-02-10 ⋅ 阅读:(23) ⋅ 点赞:(0)

        默认系统已经安装了git,且运行环境在windows下: ~/.git 通常指的是用户主目录下的.git目录。

1、创建 ~/.gitconfig 文件

[user]
 	name = userName # 配置git username
 	email = userName@mail.com.cn # 配置 git 邮箱
[core]
	autocrlf = false
	hooksPath = ~/.git/hooks # 指定自定义脚本位置
[credential]
	helper = store
[http]
	sslVerify = true
	sslBackend = schannel

2、创建 ~/.git/hooks/commit-msg

#!/bin/sh

# Created by Husky v4.3.8 (https://github.com/typicode/husky#readme)
#   At: 2024/8/8 下午8:51:41
#   From: undefined (undefined)
echo "---------开始执行检查脚本----------"
# 获取提交信息文件的路径
commit_msg_file=$1

# 读取提交信息
commit_msg=$(cat "$commit_msg_file")

# 打印提交信息(可选)
echo "Commit message: $commit_msg"

keywords="feat:|fix:|perf:|impr:|ci:|docs:|style:|refactor:|test:|chore:|jvm:|pom:|apm:|conf:|typo:|wip:"
# 定义关键词列表
EXCLUDED_KEYWORDS=("【" "】" "[]" "【】")

# 在这里可以添加您需要的逻辑来处理提交信息
# 例如,检查提交信息是否符合某种格式
if ! echo "$commit_msg" | grep -qE "^($keywords)" ; then
  echo "Error: Commit message must start with one of the following keywords:[ 'feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'revert', 'build', 'impr','ci','jvm','pom','apm','conf','typo', 'wip']"
  exit 1
fi

# 检查提交信息长度是否超过50字符
if [ ${#commit_msg} -gt 50 ]; then
    echo "Error: Commit message length exceeds 50 characters."
    exit 1
fi

# 遍历关键词列表,检查提交信息中是否不包含任何关键词
for keyword in "${EXCLUDED_KEYWORDS[@]}"; do
    if echo "$commit_msg" | grep -qE "$keyword"; then
        echo "Error: Commit message contains an excluded keyword '$keyword'."
        exit 1
    fi
done

exit 0

3、测试脚本

默认你已经掌握了git命令的使用,且已有本地git 仓库

npm install

git add .

git commit "your message"


网站公告

今日签到

点亮在社区的每一天
去签到