2

Normally, I can list local branches with git branch, and remote branches with git branch -r. However, these commands don't work with detached HEAD - I get fatal: HEAD does not point to a branch (presumably because git branch tries to determine current branch so that it can mark it with an asterisk).

What's the best way of getting branch information when I'm in detached HEAD? Note that I'd like to get output in the same format, including coloring.

Jan Warchoł
  • 1,063
  • 1
  • 9
  • 22
  • 2
    `git branch` works just fine for me in detached head state. I did `git log`, picked a SHA1 from a few commits back, and checked that out to reach detached head state. `git branch` still works for me, colors and all. – tripleee Nov 15 '17 at 12:02
  • 2
    Same for me. It prints `* (no branch)` as current branch. I use a fairly old version of git (`1.7.1`). Which version on which platform do you use? – gucce Nov 15 '17 at 13:30
  • @gucce Ooh, this is very interesting! Now I see that sometimes it works and sometimes throws an error. I'll try narrowing it down. I'm using git 2.14.2 on Linux Mint. – Jan Warchoł Nov 15 '17 at 21:22

1 Answers1

0

This should work more consistently with Git 2.29 (Q4 2020): "git status"(man) has trouble showing where it came from by interpreting reflog entries that record certain events, e.g. "checkout @{u}", and gives a hard/fatal error.

Even though it inherently is impossible to give a correct answer because the reflog entries lose some information (e.g. "@{u}" does not record what branch the user was on hence which branch 'the upstream' needs to be computed, and even if the record were available, the relationship between branches may have changed), at least hide the error to allow "status" show its output.

That also influences git branch.

See commit f24c30e, commit ec06b05, commit a4f66a7 (01 Sep 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit 0df670b, 09 Sep 2020)

wt-status: tolerate dangling marks

Signed-off-by: Jonathan Tan

When a user checks out the upstream branch of HEAD, the upstream branch not being a local branch, and then runs "git status"(man) , like this:

git clone $URL client
cd client
git checkout @{u}
git status  

no status is printed, but instead an error message:

fatal: HEAD does not point to a branch  

(This error message when running "git branch"(man) persists even after checking out other things - it only stops after checking out a branch.)

This is because "git status"(man) reads the reflog when determining the "HEAD detached" message, and thus attempts to DWIM "@{u}", but that doesn't work because HEAD no longer points to a branch.

Therefore, when calculating the status of a worktree, tolerate dangling marks. This is done by adding an additional parameter to dwim_ref() and repo_dwim_ref().

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250