Git Lesson: Be mindful of a detached head

Git Lesson: Be mindful of a detached head

A severed head is never fun, and in git this is no different. In fact, a detached head can cause quite the headache.  In this article I will discuss what a detached head is, how it can happen, and most importantly, what you can do about it.  But before I begin, let’s rehash a bit about how git works.

A git repository is a direct acyclic graph of commits.  Here is a very simple git repository.

In the EGit history view it would look like this:

Now, let’s assume that core and ui bugs (commits E and F) were not actually bugs, but rather controversial design decisions. And the the fixes broke other parts of the application.  After a quick meeting, someone suggests a new way of addressing the problems that will make everyone happy. One problem, they’re not sure if it will actually work.   Since they are using git, they checkout the code before the controversial bugs were addressed (Commit B) and they start hacking away.  Now here’s the crux of the problem: a branch is a linear set of commits, so where do these new commits live? The truth is, head is not actually visible from any branch now.  This is a detached head.

 

In the EGit history view you can see you have no head.

The good news is that you can quickly fix this problem by creating a new branch.  In egit, this is as simple as Team -> Switch To -> New Branch. Now, all these ‘detached commits’ will live on the new branch (new_idea).

You can now see the new commits (and new branch) in the EGit history view:

What if you accidentally  switched branches while you were on a detached head.  At this point, there is no way to access the commits because they are not attached to any branch. Luckily, git remembers all the commits, even the ones that happened while your head was detached.  Simply drop the command line and issue: git reflog


You can now see the missing commits.  If you return to Eclipse and use Navigate -> Open Git Commit you can open the commit 73df399

And directly create a branch from here

Another very common way to lose your head is to checkout a remote branch. Again, if you checkout a remote branch, immediately create a new local branch for your new commits; otherwise you’ll be working with a detached head.

There is more information about detached heads here.  Remember, don’t fight your tools, just git ‘er done.