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
# 预期提交成功