【问题标题】:git prepush hook: get branches pushed togit prepush hook:将分支推送到
【发布时间】:2016-09-26 19:24:54
【问题描述】:

如何在预推送挂钩的上下文中获取被推送到的分支列表?我知道如何获取当前分支,但它可能与被推送到的一个/多个分支不同。

我曾想过解析命令,但我担心我可能会忘记某些情况。像git pushgit push origin master 都会推送到 master 等。

【问题讨论】:

    标签: git push githooks


    【解决方案1】:
    while read oldrev newrev refname 
    do
         if [[ "$newrev" != "0000000000000000000000000000000000000000" ]] ; then
              branch=${refname#refs/heads/} 
         fi
    done
    

    【讨论】:

    • 关闭,但不太正确:请参阅 git hooks 文档的 pre-push hook 部分中的 refs/heads/master 67890 refs/heads/foreign 12345 示例:kernel.org/pub/software/scm/git/docs/githooks.html
    • 看起来$(echo ${refname#refs/heads/} | awk '{print $1;}')' 会成功
    • @Guig: 更简单:while read refname localhash foreignref foreignhash; do ... 但是您还应该检查refname(我将其重命名为localref)实际上也以refs/heads/开头,否则推送标签v1.2将尝试对可能不存在的 branch v1.2 执行某些操作。
    • 我已经修改了过滤掉标签的答案
    • 这仍然不对,这里的主要问题是您将其构建为一个 pre-receive 或 post-receive 钩子,它读取具有 三个 值的行。预推送挂钩的输入由具有 四个 值的行组成。这四个值依次是本地引用名称、本地哈希 ID、远程(外部)引用名称和远程哈希。考虑到 sh read 的工作方式,您将在 $refname 中获得最后两个,在 $oldrev 中获得本地引用名称,在 $newrev 中获得要推送的本地哈希。
    【解决方案2】:

    这是一个可能的循环,尽管我不清楚您想对远程分支或标记名称和/或本地 ref 做什么:

    #! /bin/sh
    
    NULLSHA=0000000000000000000000000000000000000000 # 40 0's
    
    say() {
        echo "$@" 1>&2
    }
    
    while read localref localhash foreignref foreignhash; do
        case $foreignref in
        refs/heads/*)
            reftype=branch
            shortref=${foreignref#refs/heads/};;
        refs/tags/*)
            reftype=tag
            shortref=${foreignref#refs/tags/};;
        *)  reftype=unknown-ref-type
            shortref=$foreignref;;
        esac
        say "pushing to $reftype $shortref"
        case $localhash,$foreignhash in
        $NULLSHA,*) say "(push with intent to delete)";;
        *,$NULLSHA) say "(push with intent to create)";;
        *) say "(push with intent to update from $foreignhash to $localhash)"
           # for branch updates only, let's see if it's a fast-forward
           if [ $reftype = branch ]; then
               if git merge-base --is-ancestor $foreignhash $localhash; then
                   say "(this is a fast-forward)"
               else
                   say "(this can only work if forced)"
               fi
           fi;;
        esac
    done
    

    (注意:这没有经过很好的测试)。

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 2020-02-16
      • 1970-01-01
      • 2022-01-23
      • 2011-09-10
      • 2013-10-09
      • 2016-07-08
      • 2019-07-29
      • 2016-10-25
      相关资源
      最近更新 更多