Reputation: 25054
I need a command which returns the full reference name of my currently checked out revision. Or as close to this as possible. Big plus if git-only (for cross-platform purposes).
By "full reference name" I mean e.g. refs/tags/my-tag
, refs/heads/my-branch
.
Examples:
git checkout master
magic command
# => /refs/heads/master
git checkout v1.0.0
magic command
# => /refs/tags/v1.0.0
git checkout 86742545e8152a8fbf31eafa55eb573042f61f5d
magic command
# =>
Few points of reference:
.git/HEAD
shows the hash in both cases.git show-ref
shows all references and the corresponding commit hashesgit symbolic-ref HEAD
works for branches and with the -q
option it doesn't fail if you're not on a branchgit describe --tags --exact-match
kind of works for tags, but you'd need to prefix it with refs/tags
and get rid of stderrRelated:
All I could find seemed too complicated for what I'm looking for.
Upvotes: 3
Views: 1434
Reputation: 487795
You probably want git describe
, perhaps with some flags and perhaps with some post-processing. See details below.
I'm not entirely sure what actual problem you are trying to solve:
The hash ID is the permanent name for this commit. So just git rev-parse HEAD
and you have it.
The current branch name is what git symbolic-ref HEAD
gets. It produces an error if there is no current branch name, which is the case whenever you use git checkout
to switch to a detached HEAD. That includes:
--detach
with a branch name, andNote that a branch name stores one commit hash ID, except for the somewhat special case of being on an "unborn branch", in which case, the branch name doesn't exist, even though it is the current branch name. This somewhat obnoxious state is necessary because a branch name must contain the hash ID of an existing commit, and in a new, totally-empty repository, there is no existing commit, yet you're started out on branch master
.
If the problem you are trying to solve is: "Tell me what command the user typed in to get into the HEAD
state I'm in now, whether that is detached or attached", Git does not save that for you. The closest you get are entries in the HEAD
reflog. This reflog is not required to exist. One other place to look is in history saved by the shell (command line interpreter): if that history exists, it probably contains the exact command the user entered, even if that command is an alias.
If the problem you are trying to solve is: "Provide a name useful to / readable by humans, that will (always | currently) identify this exact commit", there is no right answer, but the closest you can come is to make your own new tag for the current commit hash ID. The second-closest you can come, which is pretty useful, is to use the output of git describe
(which has lots of flags to tweak its output). Note that using a branch name will only identify the same commit until the branch name moves on to identify some other commit, which happens regularly.
Upvotes: 2