I started working on some files I had in a git submodule under another project. However, since it was a git submodule it never checked out "master" and instead just checked out the head and placed all the files in the folder in "no branch".

Now that I've made some changes by accident to these files I just realized that I was working in a "no branch", submodule of my project.

How do I get those files into a branch (like master) so I can rescue them?

link|improve this question

70% accept rate
feedback

2 Answers

up vote 4 down vote accepted

You can use git reflog to find the "lost" commits:

$ cd submodule_dir
$ git reflog          # Find the commit
$ git checkout master
$ git cherry-pick $SHA_OF_MISSING_CMMIT
link|improve this answer
Yep, this worked great! except I did a git merge $COMMIT_SHA once I was in the other branch. – Xeoncross Mar 5 '10 at 1:18
feedback

The “no branch” state is called a detached HEAD. It is called this because the HEAD ref is not attached to any branch, instead it is pointing directly at a commit. To attach HEAD to a branch that points to the current HEAD commit, use git checkout -b branchname.

You can safely update an existing branch to include the commits at HEAD with this sequence:

git branch temp
git checkout branchname
git merge temp
git branch -d temp

Or, equivalently, using the reflog notation HEAD@{1} to avoid having to make the temporary branch:

git checkout branchname
git merge HEAD@{1}

Using the temporary branch would be a good idea if you were not going to do the merge immediately.

If you want to forcibly overwrite an existing branch to point to the commit at HEAD you can use git branch -f branchname && git checkout branchname. If the commit at HEAD is not based on the current tip of branchname this will result in a non-fast-forward change to branchname which you usually want to avoid (it is viewed as rewriting history).

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.