What is the opposite of `git diff HEAD^`?

前端 未结 3 1335
死守一世寂寞
死守一世寂寞 2021-02-03 22:57

In git, I can specify the previous revision by saying HEAD^ or HEAD~1. What about going the other way? Suppose I\'m on revision X, and I do git c

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-03 23:34

    You can't really do precisely that. History in git is a directed acyclic graph - each commit contains references to its parents, but parents don't have references to their children.

    The problem here should become obvious when you think about a commit you created multiple branches from. Which "next commit" do you mean? With parents, you can number off (a normal merge commit has a first and second parent), but how do you do that with children? Even if you know what branch you're trying to be on (e.g. you've checked out master~4 and now you want to look at master~3) it's not well-defined - you could be in a situation like this:

    - X (HEAD) - o - o - o - Y (master)
       \                    /
        o - o - o ----------
    

    That said, in simple cases, you could do something like this:

    git checkout $(git rev-list HEAD..master | tail -n 1)
    

    Clearly that'll work fine with linear history. With merges... rev-list works from present to past in the history, following it backward. I believe it follows the first parent first, so the thing printed last will be the commit after HEAD found by following all last parents.

    Edit: That does assume that you know which branch you want to move forward toward. If you don't... well, you're pretty much stuck looking on all refs for commits which have the current HEAD as parent - probably grepping the output of git rev-parse:

    git rev-list --all --children | grep ^$(git rev-parse HEAD)
    

    Then grab the other SHA1 from the line (use awk, whatever). You'll have to manually inspect or make an arbitrary choice if there are multiple results though...

提交回复
热议问题