Last Updated: February 25, 2016
·
4.947K
· hannesg

git: revision magic like a boss

Every git revision is internally indentified using a sha1 checksum like "55d42a2333bf709d7c2b36df8d15b66b3ddb60d1". However, these identifiers are very unhandy for human beings and therefore git provides a ton of shortcuts so you don't have to type these checksums. Many of these shortcuts are well known like HEAD^ or HEAD~2. But few people know how git resolves these shortcuts.

Sadly it's not obvious that all these shortcuts are very well documented in the help page for the tool git rev-parse which is accessible throught:

$> git help rev-parse

or online: http://git-scm.com/docs/git-rev-parse

This tool is internally used by many git tools like git checkout, git diff and git log to find out which checksum to use. Therefore, every shortcut that works with git rev-parse works with these tools as well:

$> git rev-parse HEAD^
55d42a2333bf709d7c2b36df8d15b66b3ddb60d1
$> git checkout master
# checks out 55d42a2333bf709d7c2b36df8d15b66b3ddb60d1

With this new knowledge the shortcuts from above become clear:

  • HEAD^ is the revision before the current
  • HEAD~2 is the same as HEAD^^ and the revision before HEAD^

There are even better shortcuts shown in the documentation:

  • master^{tag} is the last tagged revision in the branch "master".
  • master^{/foo} is the last revision in the branch "master" which commit message matches the regexp "foo".
  • master@{yesterday} is the revision in the branch "master" that was current yesterday.
    Instead of yesterday you can use relative times like "5 minutes ago" or "last year". This is really nice with git diff:

    $> git diff master@{last week}..master
    # diff between now and last week
  • master@{2012-04-01 0:00:00} is the last revision in the branch "master" made before the first of april 2012.

  • @{-1} is the last revision in previously checked-out branch.

A now: off to the git console and do revision magic!