Skip to content

Instantly share code, notes, and snippets.

@tw3
Last active April 6, 2020 18:53
Show Gist options
  • Save tw3/e48e549dd84f3c236dbbb62a43b58e45 to your computer and use it in GitHub Desktop.
Save tw3/e48e549dd84f3c236dbbb62a43b58e45 to your computer and use it in GitHub Desktop.
Git pre-commit and pre-push hooks to avoid committing to master or release branches

Git pre-commit and pre-push hook

It will check if current branch is master or a release branch and, if so, prevents a commit or push

To install

  1. Enable git templates

    git config --global init.templatedir '~/.git-templates'
    
  2. Create a directory to hold the global hooks:

    mkdir -p ~/.git-templates/hooks
    
  3. Copy the pre-commit and pre-push hooks below to ~/.git-templates/hooks

  4. Make them executable

    chmod a+x ~/.git-templates/hooks/pre-commit
    chmod a+x ~/.git-templates/hooks/pre-push
    
  5. Re-initialize git in your cloned projects to enable these scripts there:

    cd <your-git-clone-folder>
    git init
    

After this you should see an error if you try to commit to the master or a releaseXXX branch:

$ git commit -m "test commit to master branch"
You can't commit directly to master branch
#!/usr/bin/env bash
branch="$(git rev-parse --abbrev-ref HEAD)"
if [[ "$branch" = "master" ]]; then
echo "You can't commit directly to master branch"
exit 1
fi
if [[ "$branch" =~ ^release* ]]; then
echo "You can't commit directly to a release branch"
exit 1
fi
#!/usr/bin/env bash
branch="$(git rev-parse --abbrev-ref HEAD)"
if [[ "$branch" = "master" ]]; then
echo "You can't push directly to master branch"
exit 1
fi
if [[ "$branch" =~ ^release* ]]; then
echo "You can't push directly to a release branch"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment