Git – No Branch

30 / Nov / 2012 by Hitesh Bhatia 0 comments

Recently one of my colleagues went nuts over Git, he was trying to do a git commit through his IDE, and he encountered this “detached HEAD” warning. But he ultimately did that, and when he switched to master branch, there was no other branch and his commits were not on master branch either. This is where he thougt of redoing all his work.

But I told him about ‘reflog’ command, which basically keeps track of ‘HEAD’. Looking at the output (listed below) ‘git reflog’ command made it clear that he did a checkout of old commit, Kept committing on ‘no branch’ state, and when he checked out master back.
[shell]
d41214e HEAD@{0}: checkout: moving from 7691216fc5b4491e35ceeec18e6c91c314ae4b95 to master
7691216 HEAD@{1}: commit: Changes to product history
7f04320 HEAD@{2}: commit: Implemented product history
1aec670 HEAD@{3}: checkout: moving from master to 1aec670
[/shell]
There was no other branch. But he remembered his commit messages which were also shown in the output of ‘git reflog’ command their respective hash codes. Now we had two ways to remedy this situation

1) We could cherry-pick both of his commits to branch master.
[shell]
git cherry-pick 7f04320
git cherry-pick 7691216
[/shell]
This approach is only useful when the number of commits are less, as one has to repeat this for each commit.

2) Create a branch from last commit and merge it to master.
[shell]
git branch product 7691216
git checkout master
git merge product
[/shell]
But this also has a drawback, when replicating this scenario, I found out that “Git is not able to do a very complex merge” in this case. I went back to month old code with checkout, and tried the same thing. But git refused to a merge.

We used first option and our work was back in master branch, but precaution is always better than cure. Now to make sure this kind of situation never comes up, always do a checkout with the branch name.
[shell]
git checkout product 1aec670
[/shell]

This would have altogether saved us from ‘detached State’ scenario. And also while replicating this scenario from command line, I found out that Git also gives a warning stating that “Warning: you are leaving 2 commits behind, not connected to”. So listening to Git would also have saved us the trouble.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *