【问题标题】:Git: how to check out the currently pushed branch in the pre-push hook?Git:如何在 pre-push 钩子中检查当前推送的分支?
【发布时间】:2013-12-01 11:02:39
【问题描述】:

在我的项目中,我有一个 pre-push git 挂钩,可以在每次推送时运行单元测试。

但是当我尝试从一个分支推送更改而留在另一个分支时,单元测试将针对活动分支运行,而不是针对当前推送的分支。

例如,如果我尝试从我的 new_feature 分支推送更改,而我的工作目录反映了开发分支的结构,则 pre-push 挂钩将为开发分支运行单元测试,而不是为 new_feature 运行。

摆脱这种情况的基本想法是在 pre-push 钩子中检查当前推送的分支。但我不知道如何获取有关当前在钩子内推送的分支的信息:此信息不包含在钩子参数中。

【问题讨论】:

    标签: git githooks


    【解决方案1】:

    来自githooksmanual

    Information about what is to be pushed is provided on the hook's standard input
    with lines of the form:
    
       <local ref> SP <local sha1> SP <remote ref> SP <remote sha1> LF
    
    For instance, if the command git push origin master:foreign were run the hook would
    receive a line like the following:
    
       refs/heads/master 67890 refs/heads/foreign 12345
    
    although the full, 40-character SHA-1s would be supplied.
    

    其中 正是您正在推动的分支。有了它,您可以在该工作树中签出和测试。

    这是一个示例钩子脚本:

    #!/bin/sh
    
    z40=0000000000000000000000000000000000000000
    
    IFS=' '
    while read local_ref local_sha remote_ref remote_sha
    do
        current_sha1=$(git rev-parse HEAD)
        current_branch=$(git rev-parse --abbrev-ref HEAD)
        if [ "$local_sha" != $z40 ] && [ "$local_sha" != "$current_sha1" ]; then
            git checkout $local_sha
    
            # do unit testing...
    
            git checkout $current_branch
        fi
    done
    
    exit 0
    

    【讨论】:

      【解决方案2】:

      pre-push hook(由git 1.8.2, April 2013引入)已由commit ec55559this sample引入:

      此挂钩由“git push”调用,可用于防止发生推送。
      使用两个参数调用挂钩,提供目标远程的名称和位置,如果未使用命名远程,则两个值将相同。

      钩子的标准中提供了有关要推送的内容的信息 输入表格的行:

      <local ref> SP <local sha1> SP <remote ref> SP <remote sha1> LF
      

      例如,如果命令 +git push origin master:foreign+ 运行,钩子将收到如下行:

      refs/heads/master 67890 refs/heads/foreign 12345
      

      尽管会提供完整的 40 个字符的 SHA1。

      • 如果外部引用尚不存在,&lt;remote SHA1&gt; 将为 40 0
      • 如果要删除引用,&lt;local ref&gt; 将提供为(delete)&lt;local SHA1&gt; 将为 40 0
      • 如果本地提交指定的名称不是可以扩展的名称(例如 HEAD~ 或 SHA1),则它将按照最初给出的方式提供。

      因此,请检查本地 ref 是否包含正确分支的名称,即“当前推送的分支”,前提是您在 git push 命令中提供相同的名称(即不要单独使用 git push)。

      【讨论】:

        猜你喜欢
        • 2018-11-02
        • 2014-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-16
        • 1970-01-01
        相关资源
        最近更新 更多