Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use git hook pre-commit to stop commits to master

Tags:

git

bash

githooks

I want to stop myself accidently commiting something to the master branch unless I am sure. So I tried this script to determine which branch I am on but there is a problem. When I create a new branch git name-rev returns master even though I am on the other branch

$ git branch
  ignore
  master
* set_support
$ git name-rev --name-only HEAD
master

This is my script.

#!/bin/sh
# Check to see if we are on master branch. Stop accidental commits
if [ "`git name-rev --name-only HEAD`" == "master" ]
then
   if [ -f i_want_to_commit_to_master ]
   then
      rm i_want_to_commit_to_master
      exit 0
   else
      echo "Cannot commit to master branch Adrian"
      echo "Remember to create file 'touch i_want_to_commit_to_master' to commit to master"
   fi
   exit 1
fi
exit 0

For Mark: I rebuilt git against latest stable tag and same results. It only works after a commit is made to the new branch.

$ mkdir gittest
$ cd gittest
$ git init
Initialized empty Git repository in /home/adrian/gittest/.git/
$ touch file1
$ git add file1
$ git commit
[master (root-commit) 7c56424] New file
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file1
$ git branch
* master
$ git checkout -b new_branch
Switched to a new branch 'new_branch'
$ git name-rev --name-only HEAD
master
$ git --version
git version 1.7.7.1
$ git branch
  master
* new_branch
$ touch file2
$ git add file2
$ git commit
[new_branch 1e038fb] new file
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file2
$ git name-rev --name-only HEAD
new_branch
like image 838
Adrian Cornish Avatar asked Oct 27 '11 23:10

Adrian Cornish


2 Answers

This command is used to find a friendly name of a commit. What is happening is that HEAD is resolving to the sha1 of the commit first and then a name is determined. I'm guessing it is arbitrarily picking master for the name as it comes up first in what git log --decorate would come across.

I would just parse the output of git branch in your test:

"`git branch | grep \* | cut -f2 -d' '` == "master"

or a more direct way would be:

$(git symbolic-ref HEAD 2>/dev/null) == "refs/heads/master"
like image 109
Adam Dymitruk Avatar answered Sep 25 '22 03:09

Adam Dymitruk


As an alternative you could use git rev-parse as suggested in this answer. So the if expression would be:

"$(git rev-parse --abbrev-ref HEAD)" == "master"
like image 38
Diego Avatar answered Sep 23 '22 03:09

Diego