git branch delete – HOOK

I have ready many articles about protecting remote branches…

I however would like to capture in a git hook the following LOCAL repo command:

git branch -d abranchthatshouldnotbedeleted

I would like to hook that command and analyze it against an branch list file of “protected branches” that I made and do a simple check to allow or deny the delete.

Certain branches of mine are now locked in a stated where they are managed now and must be protected.

  • How to discover a file is changed in GIT during a push
  • Git server hooks
  • Git post-receive hook clone successful, but reporting 'not a git repository'?
  • How to configure Git post commit hook
  • TortoiseGit hook scripts can not prevent start-commit
  • git windows post pull
  • Git Post-Update Hook - Can I handle “master” and “branches”?
  • Phabricator hook and Bitbucket
  • 2 Solutions collect form web for “git branch delete – HOOK”

    Since GitHub doesn’t allow pre-receive hook (only post-receive ones), I would recommend pushing to an intermediate local repo, protected by Gitolite (an authorization layer, through ssh or http access to your git repo).

    Gitolite can help code all kind of access rules, including protecting a branch against deletion.

    If the push is allowed, then a post-commit hook can push that automatically to GitHub.

    Git does not (currently) have a hook that you can use to do what you want. See git help hooks for a list of available hooks.

    You may want to consider a different approach. For example, you could wrap git in a wrapper script or shell function that does its own parsing to prevent you from deleting the branch:

    git() {
        [ "${1}" != branch ] ||
        { [ "$2" != -d ] && [ "$2" != -D ]; } ||
        case $3 in
            abranchthatshouldnotbedeleted) false;;
            *) true;;
        esac ||
        { printf %s\\n "ERROR: branch $3 must not be deleted" >&2; exit 1; }
        command git "$@"
    }
    

    The above shell function is quite primitive and doesn’t handle invocations like git --git-dir=/foo.git branch -d abranchthatshouldnotbedeleted, but you get the point. Perhaps you can use git rev-parse --parseopt to make it more robust.

    Git Baby is a git and github fan, let's start git clone.