Search code examples
gitversion-controlmerge

Retrieve lost HEAD branch in git


I have a really simple Git project, with just a Master branch and no origins.

Somewhere along the line I accidentally created a detached HEAD in my project, and then after making a bunch of commits on that detached HEAD, tried to merge it back into my Master branch. I was doing this in SourceTree, and at first the merge seemed to work (the graph showed master going into head, and there were merge conflicts which I fixed), but then I double clicked on Master to switch to that branch and then suddenly my HEAD disappeared. I can't find it anywhere in SourceTree under All Branches, and git branch and git log on the command line only show my Master branch too.

Is there anyway to get back my commits from my lost detached HEAD?


Solution

  • I can't find it anywhere in SourceTree

    Go back to the command-line interface and do a git reflog.
    You should be able to find back the SHA1 of your HEAD in that log.

    Note that you wouldn't have needed to "merge" your detached HEAD branch back to master.

    You simply could have reset master to your current detached HEAD commit.
    See "How to fix a Git detached head?"

    git checkout master
    

    In pure SourceTree fashion (as in this thread)

    http://edwon.tv/wordpress/wp-content/uploads/2012/09/Screen-Shot-2012-10-15-at-4.15.22-PM.png

    You could also have checked out an existing branch, then used right-click on the latest commit and selected Reset <branch> to this commit to move the branch pointer to where you want it to be.

    When HEAD is displayed, it means that you're on a detached HEAD, which means you have no branch checked out and any commits won't move any branches when they're made. If you checkout a detached HEAD in SourceTree, it will warn you fairly obviously, so maybe this was done on the command line beforehand and you saw the after effects in SourceTree.

    Alternative:

    create a branch from my "HEAD" branch (which isn't really a branch at all) using the new branch command. At that point head is gone.
    Then I was able to merge that branch with master and delete the unwanted branch I had created from HEAD.