首页 > 解决方案 > 如何使用 git hook pre-merge-commit 获取原始合并分支名称

问题描述

我正在尝试使用新的 git hook pre-merge-commit 创建一个特定的脚本,但它没有参数。

是否有任何解决方法,以便我可以获取正在合并的分支的名称?

示例:在分支 myBranch 上,我调用“git merge testingBranch”,我想在我的脚本中获取那个“testingBranch”。

原因:我需要阻止将项目中的一个特定分支合并到任何其他分支。所以它会像:

if [[ "$originOfMergeBranchName" == "testingBranch" ]]
    then
        echo "You can't merge this branch to any other"
        exit 2
fi

我在思考如何获得 originOfMergeBranchName 时遇到了麻烦

先谢谢了

标签: gitshellhook

解决方案


我修改了在这里找到的脚本以确保完全匹配。它使用Git 环境变量 GIT_REFLOG_ACTION来获取合并的分支。

#!/bin/sh

if [[ $GIT_REFLOG_ACTION == *merge* ]]; then
    if [[ $GIT_REFLOG_ACTION =~ ^.*' 'test(' '.*)?$ ]]; then
        echo
        echo \# STOP THE PRESSES!
        echo \#
        echo \# You are trying to merge from test...
        echo \# Surely you don\'t mean that?
        echo \#
        echo \# Run the following command now to discard your working tree changes:
        echo \#
        echo \# git reset --merge
        echo
        exit 1
    fi
fi

推荐阅读