親測可用!不行你來打我!!!!!
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
# 預期提交成功
?