Git: Prevent commits in master branch

亡梦爱人 提交于 2019-11-26 10:10:51

问题


(For simplicity) I have a master branch and a dev in my Git-repo. I want to ensure the master branch is always working, so all work I do should be in the dev branch.

However, when I merge my changes in with a --no-ff merge, I tend to stay in the master branch, and just continue working in it (because I forget to checkout my dev branch).

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

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


回答1:


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:

    #!/bin/sh
    
    branch="$(git rev-parse --abbrev-ref HEAD)"
    
    if [ "$branch" = "master" ]; then
      echo "You can't commit directly to master branch"
      exit 1
    fi
    
  3. Make it executable (not required on Windows):

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

To disable fast-forward 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




回答2:


It may make sense to install it globally via

git config --global core.hooksPath ~/githooks

and moving that pre-commit file into that directory



来源:https://stackoverflow.com/questions/40462111/git-prevent-commits-in-master-branch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!