Git:防止主分支提交 [英] Git: Prevent commits in master branch

查看:144
本文介绍了Git:防止主分支提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(为简单起见)我在Git-repo中有一个 master 分支和一个 dev
我想确保 master 分支始终有效,所以我所做的所有工作都应该位于 dev branch。



然而,当我使用 - no-ff 合并我的更改时,我倾向于留在 master 分支中,并继续在其中工作(因为我忘了签出我的 dev 分支)。



我可以为 master 分支建立一条规则,其中规定我不能提交,并且快-forward合并,但只有 - no-ff 从另一个分支合并?



这必须适用于私人托管(不是GitHub和BitBucket)。

解决方案

是的,这是可能的。您必须创建拒绝提交到主分支的预提交挂钩。当您调用 merge 命令时,Git不会调用预提交钩子,因此该钩子将仅拒绝常规提交。


  1. 转至您的存储库。使用以下内容创建文件 .git / hooks / pre-commit

  2. $ b

     #!/ bin / sh 

    分支=$(git rev-parse --abbrev-ref HEAD)

    if [$ branch=master];那么
    echo你不能直接提交给master分支
    exit 1
    fi



  3.   
  4. 使其成为可执行文件( Windows 不要求):

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

要禁用 fast-forwad 合并,您还必须将以下选项添加到 .git / config 文件中:

  [branchmaster] 
mergeoptions = --no-ff

如果您还想保护远程的主分支,请选中此答案:如何限制访问git上的master分支


(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).

解决方案

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-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

这篇关于Git:防止主分支提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆