Git状态上游和下游

3
我可以运行这些命令并获得预期的输出。
$ git branch --track test
$ git checkout test
$ touch hello.txt
$ git add hello.txt
$ git commit -m hello.txt
$ git status
On branch test
Your branch is ahead of 'master' by 1 commit.

然而,这就是我的问题所在。
$ git checkout master
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

我想知道自己是否领先于 origin/master,但我也想知道自己是否落后于 test。我想要一个命令来给我这样的结果:

On branch master
Your branch is up-to-date with 'origin/master'.
Your branch is behind 'test' by 1 commit, and can be fast-forwarded.
1个回答

3

没有内置的方法来实现这个功能,跟踪信息只能以"X tracks Y"的形式存储,而不是"Y被...跟踪",后者更加复杂,因为"..."部分可能会扩展到多个项。(此外,我认为Y通常是一个远程跟踪分支,在这种情况下,您永远无法在Y上—尽管尝试查找"跟踪Y的内容"的命令可以接受参数,因此您可以说"告诉我任何跟踪origin/master的分支)。

话虽如此,构建这样的东西当然是可能的。算法看起来像这样,Python风格的伪代码:

table = {}
for branch in local_branches:
    try:
        remote, tracked = get_what_branch_tracks(branch)
    except ValueError:
        continue # local branch "branch" not tracking anything
    try:
        br2 = analyze(branch, remote, tracked)
    except ValueError:
        warn('upstream for %s is gone' % branch)
        continue
    # at this point br2 is, e.g., origin/master or a local branch that "branch" tracks
    table.setdefault(br2, []).append(branch)

# now table[] is a table of branches that are tracked, with
# each table[key] being the branches that track branch "key"

现在,对于任何在table中的有趣分支,你只需计算可以在各个分支对中找到的修订版本数量,就像git status一样,这在shell中只需要:

# to compute "git status" for branch X that tracks Y:
nahead=$(git rev-list --count Y..X) # we're ahead $nahead commits
nbehind=$(git rev-list --count X..Y) # and behind $nbehind

如果你落后了但还没有领先,你可以快进。 get_what_branch_tracks的细节很简单,只需要执行一些git config --get命令,其中包括branch.branch.remotebranch.branch.merge。而对于analyze来说,细节更加复杂:如果remote.,那么tracked中的任何内容都是简单的;但如果它是一个实际的远程分支,则必须通过相应的fetch行来查找适当的远程跟踪分支。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接