Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

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 checkout X^. How do I go back?

Something like git checkout X+?

like image 893
Paul Biggar Avatar asked Aug 24 '10 13:08

Paul Biggar


2 Answers

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...

like image 192
Cascabel Avatar answered Oct 04 '22 09:10

Cascabel


I don't think this is possible, since a Git commit only stores its parent commit, but not its children.

Imagine a commit would store its children. What would happen if you would create several branches off this commit, so multiple commits have this commit as parent? What would then be "HEAD+"? This is ambiguous and wrong.

Speaking in what I know from data structures: Git stores history as a single-linked list, whereas you operation would need a doubly-linked list.

like image 21
fat-lobyte Avatar answered Oct 04 '22 09:10

fat-lobyte