本文介绍了如何防止特定分支合并到git中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个master分支,用于存放已发布的生产代码;一个dev分支,用于存放测试服务器的代码;以及各个开发人员认为合适的各种功能分支(从master分支).

We have a master branch where the released production code lives, a dev branch where the code for the test server lives, and various feature branches (branched from master) as each developer sees fit.

随着时间的流逝,dev分支与master有所不同.另外,那里还有一些不正确的合并,使部分代码混乱.我们已经尝试过几次将(c1)重置(force-push)与(c0)相同.可以这么说,首先要有一个干净的石板.

Over the course of time the dev branch has diverged somewhat from master. In addition, there are some incorrect merges there that mess up parts of the code. Several times already we have tried to reset (force-push) dev to be the same as master. To start over with a clean slate, so to say.

不幸的是,这不会持续很长时间.迟早有人会将旧的dev合并到新的dev中,并带回所有混乱.我怀疑这甚至可能会自动发生,其中天真的git pull会默默地合并新旧分支头.

Unfortunately this does not last long. Sooner or later someone merges the old dev into the new dev, bringing back all the mess with it. I suspect this might even happen automatically, where a naive git pull silently merges the old and new branch heads.

是否可以通过服务器端的提交钩子来防止这种情况?如果合并了错误的提交,是否会拒绝接受git push?

Is it possible to prevent this with a server-side commit hook? Something that would refuse to accept the git push if the wrong commit is merged in?

推荐答案

Git挂钩.将以下POC脚本放入远程(服务器端)存储库中的.git/hooks/pre-receive上,并授予其执行权限.

It's possible with Git Hooks. Put the following POC script to .git/hooks/pre-receive on your remote (server-side) repository and give it right permission to execute.

配置要保护的分支,例如master

Configure the branch you want to protect, for example master

$ git config hooks.protected-branch.refs master

文件:.git/hooks/pre-receive

File: .git/hooks/pre-receive

#!/bin/sh

read old_value new_value ref_name

refs=$(git config hooks.protected-branch.refs)

for ref in $refs; do
    if [ "$ref_name" == "refs/heads/$ref" ]; then
        if [ "$old_value" == "0000000000000000000000000000000000000000" ]; then
            continue
        fi

        if ! git merge-base --is-ancestor "$ref_name" "$new_value"; then
            echo "$ref_name is protected branch"
            exit 1
        fi
    fi
done

当您尝试通过强制推动重置master时,您将获得类似的输出:

When you try to reset master by force-push, You will get similar output like this:

Counting objects: 12, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (8/8), done.
Writing objects: 100% (12/12), 920 bytes | 153.00 KiB/s, done.
Total 12 (delta 4), reused 0 (delta 0)
remote: refs/heads/master is protected branch
To ../demo
 ! [remote rejected]   master -> master (pre-receive hook declined)
error: failed to push some refs to '../demo

这篇关于如何防止特定分支合并到git中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 20:51