上游和下游的 Git 状态

标签 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,但我也想知道我是否领先于origin/mastertest 后面。我正在寻找一个命令来给我这样的东西:

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.

最佳答案

没有内置这样的东西,跟踪只存储在另一个方向:“X tracks Y”,而不是“Y is tracked by ...”,这比“...”部分更复杂可以扩展到多个项目。 (另外,我认为 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 s,属于 branch.<em>branch</em>.remotebranch.<em>branch</em>.merge , 而详细信息为 analyze更复杂:如果 remote.然后 tracked 中的任何内容很简单,但如果它是一个真正的 Remote ,则 tracked 中的任何内容必须通过对应的fetch行来找到合适的远程跟踪分支。

关于上游和下游的 Git 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27716781/

相关文章:

java - Git 存储库的内部版本号 Maven 插件

git - 如何强制 git-status 使用哈希检查差异?

git - 当 git 只显示包含未跟踪文件的目录而不是文件本身时,这意味着什么?

git - 在版本控制中忽略文件夹元文件

git - 什么时候需要 git-rebase?

git - 如何在本地和远程删除 Git 分支?

git - 如何恢复添加到 git 但被 checkout 覆盖的文件

git - 如何从 git status 获取相对于当前目录的路径?

git - 503错误推送到远程

git - 从本地分支推送到不同的远程分支