git detached head: how I restore texts (sometimes)

Pavol Kutaj
Oct 28, 2020

--

abstract

The concern is documenting an accidental discovery of the DETACHED HEAD state

1. enter detached HEAD

  • note that HEAD is the term from data structure terminology for graph-types like lists or DAGs
  • it denotes the beginning point where the traverse can begin (TAIL being the end)
  • in git: HEAD === active branch — only 1 branch can be active, pointing to the latest commit
  • in powershell, from the main folder of the git project get the name of the active branch
gc ./.git/HEAD
ref: refs/heads/master
  • if you however checkout a particular commit with the its <sha> you'll enter a state of DETACHED HEAT

The detached HEAD state is useful for revisiting old states, and sometimes for short-term work that you are not sure you will keep. Other than that you probably want to avoid it. — https://stackoverflow.com/a/2467564/11082684

  • if you checkout only <sha> you will create a DETACHED HEAD
git checkout <sha>

2. rules

  • you can’t merge detached HEAD
  • this is just a peek into the past, but it is very transient
  • once you checkout back to master, the detached HEAD dissapears again

3. usecase

  • in my markdown notes, sometimes I commit en-masse
  • in some of those commits there are files mistakenly re-pasted, edited
  • need to check the initial commit of the affected file
  • this is the case for DETACHED HEAD
  • get the file history with
git log --pretty=format:\"%C(auto)%h%d%Creset %C(cyan)(%ci)%Creset %C(green)%cn <%ce>%Creset %s\" --name-status --date=short --all --full-history -- foo.txt
  • checkout a detached head
git checkout <sha>
  • open foo.txt to se if that is what you were looking for

4. sources

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com