Git:防止主分支提交

编程入门 行业动态 更新时间:2024-10-25 13:23:18
本文介绍了Git:防止主分支提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 (为简单起见)我在Git-repo中有一个 master 分支和一个 dev 。 我想确保 master 分支始终有效,所以我所做的所有工作都应该位于 dev branch。

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

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

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

解决方案

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

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

    #!/ bin / sh 分支=$(git rev-parse --abbrev-ref HEAD) if [$ branch=master];那么 echo你不能直接提交给master分支 exit 1 fi

  • 使其成为可执行文件( 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.

  • Go to your repository.
  • 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

  • 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:防止主分支提交

    本文发布于:2023-11-26 18:40:13,感谢您对本站的认可!
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:分支   Git

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!