How can I get a previous branch/commit using Git plumbing commands or status files?
Edit: The question is - how can I get this information (the previous branch or commit) without performing an actual checkout? This is needed for a tool which works on top of Git, not for a regular Git scenario.
By taking a look in the code:
if (!strcmp(arg, "-"))
arg = "@{-1}";
The way to access the previously checked out branches is documented in revisions doc on @{-n}
Now, to resolve the branch name behind @{-n}
, the solution is git check-ref-format --branch
:
With the
--branch
option, it expands the “previous branch syntax”@{-n}
. For example,@{-1}
is a way to refer the last branch you were on. This option should be used by porcelains to accept this syntax anywhere a branch name is expected, so they can act as if you typed the branch name.
$ git check-ref-format --branch @{-1}
my_branch
$ git check-ref-format --branch @{-2}
master
There is also the git rev-parse --symbolic-full-name
solution:
$ git rev-parse --symbolic-full-name @{-1}
refs/heads/my_branch
$ git rev-parse --symbolic-full-name @{-2}
refs/heads/master