Skip to content

Commit 790bb66

Browse files
authored
Merge pull request #15 from Rasic2/dev/zhouh
docs: update git pre-commit hook for enhanced protection against dire…
2 parents f4244a9 + f60854b commit 790bb66

1 file changed

Lines changed: 29 additions & 5 deletions

File tree

docs/source/development/git.md

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -393,12 +393,36 @@ chmod +x .git/hooks/pre-commit
393393
```bash
394394
#!/bin/bash
395395

396-
protected_branches=("main" "master")
397-
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
396+
protected_branch="main"
397+
current_branch=$(git symbolic-ref HEAD 2>/dev/null | sed -e 's,.*/\(.*\),\1,')
398398

399-
if [[ " ${protected_branches[@]} " =~ " ${current_branch} " ]]; then
400-
echo "ERROR: You are not allowed to push directly to the $current_branch branch. Use a feature branch and create a Pull Request."
401-
exit 1
399+
# 如果没有当前分支(比如在 detached HEAD 状态),直接退出
400+
if [ -z "$current_branch" ]; then
401+
exit 0
402+
fi
403+
404+
# 检查是否是推送到受保护分支
405+
if [ "$current_branch" = "$protected_branch" ]; then
406+
# 获取推送的引用(分支或标签)
407+
while read local_ref local_sha remote_ref remote_sha
408+
do
409+
# 如果是标签推送,允许
410+
if [[ "$remote_ref" == refs/tags/* ]]; then
411+
continue
412+
fi
413+
414+
# 如果是删除分支操作,允许
415+
if [ "$remote_sha" = "0000000000000000000000000000000000000000" ]; then
416+
continue
417+
fi
418+
419+
# 如果是推送到受保护分支的提交,拒绝
420+
if [ "$remote_ref" = "refs/heads/$protected_branch" ]; then
421+
echo "ERROR: You are not allowed to push commits directly to the $protected_branch branch."
422+
echo "Use a feature branch and create a Pull Request."
423+
exit 1
424+
fi
425+
done
402426
fi
403427

404428
exit 0

0 commit comments

Comments
 (0)