Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all symbolic names from a Git commit hash?

If a Git commit hash has multiple tags associated with it and/or is the head of multiple branches, is there a good way to list all of them?

I've looked through the options to git name-rev, git describe, and git symbolic-ref but haven't found any options that seem to do what I want. Frustratingly, git name-rev has a --tags option to list only tags but no apparent mechanism to list only branches (and git name-rev always seems to prefer tags over branches for me anyway).

$ git checkout -b branch1
$ git checkout -b branch2
$ git tag tag1
$ git tag tag2
$ git name-rev HEAD
HEAD tags/tag1
$ git describe --all HEAD
HEAD tags/tag1
$ git symbolic-ref HEAD
refs/heads/branch2

To map a commit hash to all of its symbolic names, will I need to run git tag --list and git branch --all --list and then run git rev-parse on all of the results?

like image 362
jamesdlin Avatar asked Jun 21 '20 21:06

jamesdlin


2 Answers

It should be possible to achieve what you want thanks to the git for-each-ref command:

git for-each-ref --points-at=HEAD

Complete example session:

$ git init
$ touch a
$ git add a
$ git commit -m a
[master (root-commit) eb3222d] a
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 a
$ git checkout -b branch1
Switched to a new branch 'branch1'
$ git checkout -b branch2
Switched to a new branch 'branch2'
$ git tag tag1
$ git tag tag2
$ git tag -a tag3 -m "annotated tag"
$ git for-each-ref --points-at=HEAD
eb3222db1821633a54ccd0a6434e883c4cb71b98 commit refs/heads/branch1
eb3222db1821633a54ccd0a6434e883c4cb71b98 commit refs/heads/branch2
eb3222db1821633a54ccd0a6434e883c4cb71b98 commit refs/heads/master
eb3222db1821633a54ccd0a6434e883c4cb71b98 commit refs/tags/tag1
eb3222db1821633a54ccd0a6434e883c4cb71b98 commit refs/tags/tag2
0dbba96f519c2ad1b470f97171230004addff896 tag    refs/tags/tag3
like image 81
ErikMD Avatar answered Sep 26 '22 19:09

ErikMD


I realized that normally git log shows me all of the names that I'm looking for. Looking at git log's formatting options, I alternatively could use:

$ git log --format='%d -1 HEAD
 (HEAD -> branch2, tag: tag2, tag: tag1, branch1)

The formatting of the output from ErikMD's git for-each-ref suggestion probably is easier to deal with though, so that's likely what I'll end up using.

like image 36
jamesdlin Avatar answered Sep 26 '22 19:09

jamesdlin