Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git hook to prevent creating new branches from specific branches

Tags:

git

githooks

I'm starting to play around with git hooks, and I'd like to create one to prevent a developer from creating a new branch when on a specific branch. The current process in our company is meant to look like this:

git checkout master
git fetch
git reset --hard origin/master
git checkout -b [branch name]
do awesome things.

However, occasionally when moving quickly, some developers end up starting this new branch from a staging repo. Which causes grief.

So, I'd like to create a hook to interrupt when a developer starts to create a new branch, check what branch they're on, and either exit 1 if the branch is not master (or just generally stop the action if the branch name is staging), or allow it otherwise.

Edit:

As I search more on this, I realize I want a pre-checkout hook, which doesn't appear to exist. Unless someone has a better idea, I'll proceed to print a very large warning in a post-checkout hook if the above scenario comes to pass.

like image 902
hookedonwinter Avatar asked Nov 23 '11 00:11

hookedonwinter


People also ask

How do I restrict a branch name in git?

You can set up a CI rule to reject incorrectly named branches. If you protect the main branch and require that check to be green, then people won't be able to merge them. You can force users to use a forking model to prevent them from polluting the main repository with invalidly named branches.


1 Answers

For the client side you can create a post-checkout hook that uses the git branch --merged to see branches merged in the current branch. If the branch you want to prevent from branching is merged in the current branch then you throw the error.

Code in bach would look like this:

#!/bin/sh

getBranchName()
{
    echo $(git rev-parse --abbrev-ref HEAD)
}

getMergedBranches()
{
    echo $(git branch --merged)
}

if [ "$(getBranchName)" != "dev" ]; then
    if [[ $(getMergedBranches) == *"dev"* ]]; then
        echo "Don't create branches from the dev branch!"
        exit 1
    fi
fi
like image 117
jmurgic Avatar answered Oct 04 '22 11:10

jmurgic