需要在推送之前验证本地和远程分支

时间:2017-10-26 11:49:37

标签: git githooks

我正在尝试使用GIT中的Pre-push hook创建一个检查点,我正在检查本地分支和远程分支名称是否相同。

仅当本地和远程分支相同时才允许推送。我在预推样本钩子文件中尝试这样的东西,但它无法正常工作。请建议。

while read local_ref local_sha remote_ref remote_sha
do
if [ "$local_ref" != "$remote_ref" ]
then
        echo " Please check Remote and local branch names";
        exit 1

else
        exit 0
fi
done

更新:我的本地分支是" git push命令" Mybranch 和远程分支是 refs / for / Mybranch

所以即使我的分支名称是相同的,它给我错误,我如何只从远程排除/ refs / for中提取分支名称?

Git push命令:

git push origin Mybranch:refs/for/Mybranch

1 个答案:

答案 0 :(得分:0)

一般情况下,你不应该假设refs/heads/refs/for/,因为你的钩子将用于标记推送(refs/tags/)和其他推送(例如,refs / notes /,也许refs / stash等等。

请注意,您(或任何人)可以运行,例如git push there refs/heads/master:refs/for/something refs/tags/v1.2:refs/tags/v1.2 refs/remotes/origin/master:refs/heads/master同时请求推送三个内容,这就是为什么您必须在预推钩中循环读取所有请求。< / p>

您在评论中建议您使用:

remote_ref >> remote.txt
remote_ref1 = cat remote.txt | cut -d'/' -f3
rm remote.txt

有一些语法错误。

检查前缀是否明智,如果它符合您的期望并希望处理,请删除前缀。不要只提取第三个单词,因为如果您使用名为feature/tall的分支,或者正在使用除前两个组件之外的其他结构的引用(远程跟踪分支工作此例如,虽然通常你不会推它们。)

在sh / bash脚本语言中,您可以编写,例如:

case $local_ref in
refs/heads/*)
    local_type=branch
    local_short=${local_ref#refs/heads/}
    ;;
*)
    local_type=unknown
    ;;
esac

case $remote_ref in
refs/heads/*)
    remote_type=branch
    remote_short=${remote_ref#refs/heads/}
    ;;
refs/for/*)
    remote_type=gerrit
    remote_short=${remote_ref#refs/for/}
    ;;
*)
    remote_type=unknown
    ;;
esac

现在您已经解码了引用类型并找到了已知案例的简短版本,您可以编写每个案例的逻辑,然后根据需要进行扩展:

case $local_type,$remote_type in
branch,branch|branch,gerrit)
    # push from branch to branch, or from branch to gerrit:
    # require that the shortened names match exactly (for now)
    if [ $local_short != $remote_short ]; then
        echo "push to $remote_type requires paired names" 1>&2
        echo "but you are pushing from $local_short to $remote_short" 1>&2
        exit 1
    fi
    ;;
*)
    # echo "unknown reference type - allowing" 1>&2 # uncomment for debug
    ;;
esac

所有这些都将进入主while read ...循环。如果你到了循环的末尾, all 你正在推送的引用已被验证(因为没有被echo和退出代码拒绝)。

相关问题