如何防止特定分支在 git 中合并?

Vil*_*lx- 9 git githooks

我们有一个master发布的生产代码所在的dev分支,一个测试服务器代码所在的分支,以及master每个开发人员认为合适的各种功能分支(从 分支)。

随着时间的推移,该dev分支与master. 此外,还有一些不正确的合并会弄乱部分代码。我们已经多次尝试将 (force-push) 重置dev为与master. 可以这么说,从头开始。

不幸的是,这不会持续很长时间。迟早会有人把旧dev的和新的合并起来dev,把所有的烂摊子都带回来。我怀疑这甚至可能会自动发生,一个天真的人git pull默默地合并新旧分支头。

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

Gas*_*sol 8

Git Hooks是可能的。将以下 POC 脚本.git/hooks/pre-receive放在您的远程(服务器端)存储库中,并授予其正确的执行权限。

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

$ git config hooks.protected-branch.refs master
Run Code Online (Sandbox Code Playgroud)

文件:.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
Run Code Online (Sandbox Code Playgroud)

当您尝试master通过 force-push重置时,您将获得类似的输出:

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
Run Code Online (Sandbox Code Playgroud)