File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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
402426fi
403427
404428exit 0
You can’t perform that action at this time.
0 commit comments