33

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?

Xeoncross
  • 4,842

3 Answers3

59

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
mipadi
  • 4,518
5

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).

Chris Johnsen
  • 42,029
2

To add to previous answers:

While you're still on a detached HEAD, you can add a tag:

git tag <some-tag>

This will add a tag to the commit, which will make it visible in gitk and other tools.

data
  • 131