git - 如何检查两个分支是否为 "even"?

标签 git github git-branch

GitHub 网络界面有一个很好的功能,可以告诉我一个分支是否与 master 分支一致。

是否有与此功能等效的命令行?我使用多个存储库,我正在寻找一种快速方法来查看分支是否均匀或需要注意。

这里是 GitHub 网页界面的截图,对于那些想知道这个功能的人:

enter image description here

enter image description here

最佳答案

GitHub 术语

Branch A and branch B are even.

是 GitHub 的用语

Branch A and Branch B point to the same commit.

两个分支是否相等?

如果您只对是否这两个分支感兴趣,没有任何额外的细节(例如提交计数),脚本友好的方法是简单地测试它们提示的 SHA为了平等:

[ "$(git rev-parse <refA>)" = "$(git rev-parse <refB>)" ]

运行此命令后,$? 的值是0如果<ref1><ref2>是偶数,1否则。因为这个命令只涉及管道 Git 命令 git-rev-parse , 它可以安全地以编程方式使用。

一个分支是在另一个分支之前还是之后?

如果你想模拟 GitHub 的功能,例如打印

foo is n commits ahead of bar

等等,可以使用如下脚本:

#!/bin/sh

# git-checkeven.sh
#
# Check whether two revisions are even, and, otherwise, to what extent
# the first revision is ahead of / behind the second revision
#
# Usage: git checkeven <revA> <revB>
#
# To make a Git alias called 'checkeven' out of this script,
# put the latter on your search path, and run
#
#   git config --global alias.checkeven '!sh git-checkeven.sh'

if [ $# -ne 2 ]; then
    printf "usage: git checkeven <revA> <revB>\n\n"
    exit 2
fi

revA=$1
revB=$2

if ! git merge-base --is-ancestor "$revA" "$revB" && \
  ! git merge-base --is-ancestor "$revB" "$revA"
then
  printf "$revA and $revB have diverged\n"
  exit 1
fi

nA2B="$(git rev-list --count $revA..$revB)"
nB2A="$(git rev-list --count $revB..$revA)"

if [ "$nA2B" -eq 0 -a "$nB2A" -eq 0 ]
then
  printf "$revA is even with $revB\n"
  exit 0
elif [ "$nA2B" -gt 0 ]; then
  printf "$revA is $nA2B commits behind $revB\n"
  exit 1
else
  printf "$revA is $nB2A commits ahead of $revB\n"
  exit 1
fi

测试

假设一个玩具仓库有以下历史:

         * [develop]
        /
... -- * [main, master]
        \
         * [release]

然后,在定义一个名为 checkeven 的 Git 别名之后调用上面的脚本,你得到...

$ git checkeven main develop
main is 1 commits behind develop
$ git checkeven develop main
develop is 1 commits ahead of main
$ git checkeven master main
master is even with main
$ git checkeven develop release
develop and release have diverged

关于git - 如何检查两个分支是否为 "even"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31982954/

相关文章:

git - 如何在 visual studio 中设置输出和中间目录以依赖于当前的 git 分支?

c++ - Git 和 KDevelop

android - app-release-unsigned.apk 未签名

android - 仅在 git 中为 android 项目分支 1 或 2 个文件

Git 提交和推送

混帐 : how to organize two projects that have common code

Git 使用从 GitHub 客户端同步来分离 HEAD

Github compare 给出的结果与 GraphQL 输出不同

git - 在我的本地计算机上的两个不同位置有一个存储库的两个不同分支

git - 如何让gitk只显示本地分支?