How can I prevent non-fastforward pushes to selected branch(es) in git?

Viewed 7466

I would like to protect my git repository so only non master branches can be overwritten. Is there a way to protect only selected branches?

7 Answers

Here is a modification of the Tanu Kaskinen script to allow for wildcarding of branch names. We use branches with names starting with "d/" to designate "development" branches. I wanted a way to allow non-fast-forward updates for these d/ branches:

   refs/heads/*,commit)
            # branch
            # git rev-list doesn't print anything on fast-forward updates

            if [[ $(git rev-list "$newrev".."$oldrev") ]]; then
                    branch=${refname##refs/heads/}
                    if [[ "$branch" =~ ^d/ ]] ; then
                      echo "Non-fast-forward update allowed on d/ branch"
                      nonfastforwardallowed="true";
                    else
                      #look for a specific config setting
                      nonfastforwardallowed=$(git config --bool  hooks.branch."$branch".allownonfastforward)
                    fi


                    if [ "$nonfastforwardallowed" != "true" ]; then
                            echo "hooks/update: Non-fast-forward updates are not allowed for branch $branch"
                            exit 1
                    fi
            fi
Related