【问题标题】:Git hook to get prior branch name获取先前分支名称的 Git 钩子
【发布时间】:2016-09-29 16:53:53
【问题描述】:

我正在处理 .git/hooks/post-checkout 并且在获取/导出分支名称或获取之前的分支名称时遇到问题。 切换到s3分支时,我想重启服务器。

我不知道如何在 bash 中获取 env var,所以我尝试使用 git 来获取先前的分支,但我得到的最接近的是 git checkout -/git checkout @{-1},虽然我不确定如何在不调用结帐的情况下检索先前的分支名称。

我应该使用 Git 环境变量而不是 shell 吗?

当前文件只是在每次结帐时重新启动服务器

#!/bin/bash

touch tmp/restart.txt
echo " *** restarting puma-dev"

current_branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')
if [ "$current_branch" = "s3" ]
then
  echo " *** please don't upload any files"
  echo
fi

【问题讨论】:

    标签: git bash git-branch githooks


    【解决方案1】:

    你应该可以使用这一行来获取之前的分支名称:

    git rev-parse --abbrev-ref @{-1}

    并获取当前分支名称:

    git rev-parse --abbrev-ref HEAD

    【讨论】:

      【解决方案2】:

      Git 将先前和当前的引用名称传递给 post-checkout 挂钩,因此您应该能够执行以下操作:

      #!/bin/sh
      
      oldref="$1"
      newref="$2"
      branch_update="$3"
      
      [ "$branch_update" = '1' ] || exit  # exit if branch didn't change
      
      [ "$oldref" = 'refs/heads/s3' ] && oldref_was_s3=1
      [ "$newref" = 'refs/heads/s3' ] && newref_is_s3=1
      
      if [ -z "$oldref_was_s3" -a -n "$newref_is_s3" ]; then
          echo " *** please don't upload any files"
      fi
      

      完全未经测试,但应该很接近。

      【讨论】:

        【解决方案3】:

        部分感谢 Chris,我无法解释或使用他的方法,但发现这些信息很有帮助,也感谢 Keif Kraken,我确实使用了他的方法。

        切换到特定分支或从特定分支 (s3) 更改时重启服务器

        .git/hooks/post-checkout 脚本

        #!/bin/bash
        oldref=$(git rev-parse --abbrev-ref @{-1})
        newref=$(git rev-parse --abbrev-ref head)
        
        if [[ ( "$oldref" = "s3" || "$newref" = "s3" ) && "$oldref" != "$newref" ]]
        then
          touch tmp/restart.txt
          echo " *** restarting puma-dev"
          echo " *** please don't upload any files"
        fi
        

        【讨论】:

        • 仅供参考,我在脚本中有一个愚蠢的语法错误。当我应该使用-a 进行逻辑与时,我尝试使用&&。我认为我的脚本现在应该可以工作了,它避免了不必要地运行git
        猜你喜欢
        • 2013-09-10
        • 2018-10-27
        • 2023-03-09
        • 2017-08-11
        • 1970-01-01
        • 1970-01-01
        • 2011-09-08
        • 2011-12-25
        相关资源
        最近更新 更多