Is it possible to force `git checkout` to treat the ref as a commit hash?

Viewed 113

This is a somewhat academic / esoteric question, because I know it's not a good idea to name a branch after a commit hash. However, I'm curious.

It seems that if I name a branch after a hash X, and then do git checkout X, git will prefer the branch name. Fortunately, it will warn about it.

$ git checkout f878084412c04542e297cb5c52b0fb6f6a2b2870
warning: refname 'f878084412c04542e297cb5c52b0fb6f6a2b2870' is ambiguous.
Git normally never creates a ref that ends with 40 hex characters
because it will be ignored when you just specify 40-hex. These refs
may be created by mistake. For example,

  git switch -c $br $(git rev-parse ...)

where "$br" is somehow empty and a 40-hex ref is created. Please
examine these refs and maybe delete them. Turn this message off by
running "git config advice.objectNameWarning false"
Switched to branch 'f878084412c04542e297cb5c52b0fb6f6a2b2870'

Is it possible to force git checkout <arg> to treat the <arg> as a commit hash instead?

1 Answers

The short answer is no: if the name exactly matches some refs/heads/* name, git checkout will treat it as that branch name.

There's a simple workaround: drop the last digit. You now have an "ambiguous" 39-character-long hash ID. Suppose $H expands to these 39 characters: the possible hash IDs are then ${H}0, ${H}1, ..., ${H}f, for a total of 16 possible hash IDs. It's extremely unlikely that there is more than one match, and Git will then treat the shortened hash ID as a hash ID, rather than as the branch name.

(There's a second simple workaround, which is to rename the branch name, of course. :-) )

Related