Git. How to checkout revision, which goes after HEAD?

313 views Asked by At

What is the quickest way to checkout revision which is next (later in the time) to HEAD (when you are in detached head state)?

This should be something like:

git checkout HEAD~-1

but this command doesn't work. Also git log, which doesn't show next revision hash.

The only way, which I found is:

git checkout master
git log
[find revision number]
git checkout <revnumber>

but it looks very slow. Is there a one command for this?

3

There are 3 answers

0
Schleis On BEST ANSWER

No, there would not be a single git command. The revision that you are at when you are in a detached state could have multiple locations to go. It is possible that at that revision, you created multiple branches each with separate commits. So in that case what would be the next revision that you want?

You would need to let git know the branch that you want to get the next commit on. So that Git knows where to look for the next commit.

0
proski On

You need to find the children of HEAD and check out one of them. Please see Retrieve the list of child commits of an specific commit in Git and How do I find the next commit in git?

0
Benoit On

In git, there is no real efficient way to get the children of a commit. Any commit will have a pointer to its parents, not to its descendants that do not exist when the commit is created.

There is a possibility that there are children commit for which the branch reference has been deleted (so, these are commits that could be pruned at next garbage collection), or children commit that are part of the history of one or more existing branches.

However git 1.6 introduced --children in the rev-list command. It probably has to scan each commit that is “reachable from” (in git terminology, means “an ancestor of”) every single local and remote branch ref.

git rev-list will list all descendants with no depth limitation, in the format commit_id parent_1_commit_id [parent_2_commit_id [...]]. Therefore you will have to grep for the head commit ID in the second column to get the commit ids of its descendants.

Thus:

git rev-list --children HEAD | grep " $(git show --format=format:%H HEAD)"

You can make out a bash function to alias this to git children:

[alias]
    children = "!f(){ git rev-list --children \"$1\" | grep \" $(git show --format=format:\"%H\" \"$1\")\" | cut -f 1 -d ' '; }; f"

Then git children HEAD will give you the commit ids of all descendants of HEAD.