欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > git做commit信息时的校验

git做commit信息时的校验

2025/5/12 14:55:08 来源:https://blog.csdn.net/weixin_50448162/article/details/147813978  浏览:    关键词:git做commit信息时的校验

亲测可用!不行你来打我!!!!!

1. 文件基本信息

属性说明
文件名commit-msg必须无扩展名,如 .sh 或 .txt 会导致失效)
位置仓库的 .git/hooks/ 目录下(或全局模板目录的 hooks/ 下)
权限必须可执行(chmod +x .git/hooks/commit-msg
所有者建议与 Git 用户一致(通常不需要特别修改)

2. 在开发者的本地仓库中添加钩子

 单个仓库配置

#!/bin/bash# 允许的提交类型
COMMIT_TYPES=("feat" "fix" "docs" "style" "refactor" "test" "chore" "revert")# 读取提交信息
COMMIT_MSG=$(cat "$1")# 跳过空信息和合并提交
if [[ -z "$COMMIT_MSG" || "$COMMIT_MSG" =~ ^Merge ]]; thenexit 0
fi# 校验格式:类型(可选作用域): 描述
if ! [[ "$COMMIT_MSG" =~ ^($(IFS=\|; echo "${COMMIT_TYPES[*]}"))(:|\(.*\):).* ]]; thenecho -e "\n\033[31mERROR: Invalid commit message format!\033[0m" >&2echo -e "Allowed types: \033[34m${COMMIT_TYPES[*]}\033[0m" >&2echo -e "Example: \033[32mfeat: add new feature\033[0m" >&2exit 1
fiexit 0

全局仓库配置(所有仓库生效)

# 1. 创建全局模板目录
git config --global init.templatedir ~/.git-templates
mkdir -p ~/.git-templates/hooks# 2. 创建全局 commit-msg 钩子
cat > ~/.git-templates/hooks/commit-msg <<'EOF'
#!/bin/bash
# 这里粘贴上述脚本内容
EOF
chmod +x ~/.git-templates/hooks/commit-msg# 3. 应用到现有仓库
find ~ -type d -name ".git" 2>/dev/null | while read gitdir; docp ~/.git-templates/hooks/commit-msg "$gitdir/hooks/"
done

3. 如何生效?

# 进入仓库的 .git/hooks 目录
cd /path/to/repo/.git/hooks# 创建 commit-msg 文件(内容如上)
nano commit-msg  # 粘贴脚本内容# 赋予执行权限
chmod +x commit-msg

4. 测试效果

# 尝试提交不符合规范的信息
git commit -m "bad message" --allow-empty
# 预期输出错误并阻止提交# 提交符合规范的信息
git commit -m "feat: add new feature" --allow-empty
# 预期提交成功

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词