21

In my local git tree I pull commits from the "master" branch in the repository, but all development is done in a different branch, and pushed in a different branch too.

I would like to avoid mistakes and prevent accidental commits in my local "master" branch, and allow only pull requests (then I'd rebase the developement branch to the updated master). Is this possible? How?

Micha
  • 5,117
  • 8
  • 34
  • 47
Jellby
  • 2,360
  • 3
  • 27
  • 56

1 Answers1

32

You can use a pre-commit hook.

For example, place the following script as .git/hooks/pre-commit:

#!/bin/bash
if test $(git rev-parse --abbrev-ref HEAD) = "master" ; then 
  echo "Cannot commit on master"
  exit 1
fi

And set it as executable

chmod +x .git/hooks/pre-commit
asmeurer
  • 86,894
  • 26
  • 169
  • 240
brice
  • 24,329
  • 7
  • 79
  • 95
  • 1
    Thanks, that seems to be what I needed. Just to be sure, that wouldn't interfere with "git pull", right? I ask because I cannot test it until there's some update in the server. – Jellby Jun 25 '13 at 10:02
  • 1
    No. it should be fine, it will only affect trying to commit to master. – brice Jun 25 '13 at 10:13
  • 1
    @Jellby: in order to test : `git clone /my/local/project project-test; cd project-test` Then use `project-test` with `project` as remote, and test your hook with `testBracnh` instead of `master` – LeGEC Jun 25 '13 at 12:24
  • it is not clear, whether `test` should be substituted with something? or it is a part of the script? – Yevhen Dubinin Nov 21 '16 at 23:25
  • No, test is the unix `test` command and should be left as is. – brice Dec 07 '16 at 09:48