Rasmus Bækgaard Rasmus Bækgaard - 10 months ago 50
Git Question

Git: Prevent commits in master branch

(For simplicity) I have a

branch and a
in my Git-repo.
I want to ensure the
branch is always working, so all work I do should be in the

However, when I merge my changes in with a
merge, I tend to stay in the
branch, and just continue working in it (because I forget to checkout my

Can I put up a rule for the
branch, which states I can't do commits, and fast-forward merges, but only
merges from another branch?

This must work for private hosted repositories (ergo not GitHub and BitBucket).

qzb qzb
Answer Source

Yes, it is possible. You must create pre-commit hook which rejects commits to master branch. Git doesn't call pre-commit hook when you call merge command, so this hook will be rejecting only regular commits.

  1. Go to your repository.
  2. Create file .git/hooks/pre-commit with following content:

    branch="$(git rev-parse --abbrev-ref HEAD)"
    if [ "$branch" == "master" ]; then
      echo "You can't commit directly to master branch"
      exit 1
  3. Make it executable:

    $ chmod +x .git/hooks/pre-commit

To disable fast-forwad merges you must also add following option to your .git/config file:

[branch "master"]
    mergeoptions = --no-ff

If you want also protect master branch on your remote, check this answer: How to restrict access to master branch on git