I'm working on a local branch foo that has a rich and useful history. I make a bunch of changes and commit them. A git status
says:
On branch foo
Your branch is ahead of 'origin/foo' by 1 commit.
(use "git push" to publish your local commits)
So I go ahead and type git push
.
Which seems work just fine. A quick git status
reveals:
On branch foo
Your branch is up to date with 'origin/foo'.
nothing to commit, working tree clean
I switch to my local main main branch (called feature1), git checkout feature1
. No problem. I then git pull
to add all my co-workers' changes.
And now I want to switch back to foo to merge the feature1 changes I just pulled into foo.
EDIT (I missed this both when typing AND when posting! It's the key!!!)
git checkout origin\foo
And lo-and-behold! I get this message, which I've never seen:
Note: checking out 'origin/foo'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b <new-branch-name>
HEAD is now at f5a29b1083 cosmetic changes for code review
Now the result of git status
is
EDIT (correction):
HEAD detached at origin/foo
nothing to commit, working tree clean
So my questions are multiple:
1) What did I do wrong? This is something that I've been doing over and over for a long time, yet nothing like this has happened before.
2) How can I ensure that this doesn't happen again?
3) how to I fix this without losing my work and (more importantly) without polluting everyone's history when I merge foo into feature1 in the future?
git checkout foo
if a local branchfoo
does not exist but there is one (and only one) remote tracking branchfoo
(origin/foo
in this case). But it should also create the local branchfoo
in this case. You can end up in a "detached HEAD" state if you checkout anything but a branch (a commit hash, a tag, a relative reference likeHEAD~1
etc). However, I cannot tell why your local branch suddenly disappeared. It is possible that your repo became corrupt somehow. Rungit fsck
to find out.git for-each-ref '**/foo'
and include the results?git pull
aftergit checkout feature1
?git fsck
revealed a number of dangling blobs, commits and trees. Too many to even display.