Git状态上游和下游

时间:2014-12-31 05:52:56

标签: git git-branch git-status

我可以运行这些命令并获得预期的输出

$ 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 个答案:

答案 0 :(得分:3)

内置没有这样的东西,跟踪仅存储在另一个方向:“X轨道Y”,而不是“Y跟踪......”,这更复杂,因为“......”部分可以扩展到多个项目。 (另外,我认为Y首先成为一个远程跟踪分支更为典型,在这种情况下,你不可能在Y上 - 尽管一个命令试图找到“什么跟踪Y”当然可以采取参数,所以你可以说“告诉我任何跟踪origin/master}的分支。

也就是说,构建这样的事情当然是可能的。算法看起来像这样,用Python-esque伪代码:

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 --getbranch.branch.remote的{​​{1}},而branch.branch.merge的详细信息则更为复杂:如果analyzeremote,则.中的任何内容都很简单,但如果它是实际的遥控器,tracked中的任何内容都必须通过相应的tracked传递行找到适当的远程跟踪分支。