3

I just did something dumb. In my fooclient project, I just did:

git remote add official https://github.com/fooserver
git pull official master

In other words, I pulled a completely different codebase (the server, instead of the client) into my working directory. Not surprisingly, there weren't many merge conflicts (the file names are all completely different, after all). Also not surprisingly, Git completely failed to warn me that the repos didn't have a single common ancestor.

In this particular situation, I'm able to recover by doing this:

cp file-i-worked-on.js ~
git reset --hard HEAD # to discard broken merge conflicts
git checkout a12345 # where a12345 is the latest head of fooclient that I had checked out
cp ~/file-i-worked-on.js .

But what would be the more general strategy?

4 Answers 4

4

This will reset you to the last state master was in:

git reset --hard HEAD@{1}

This is possible because of the reflog. Running git reflog will show you the reflog, and allow you to verify you're resetting to the correct state.

2
  • Ah - this sounds like the right answer. So HEAD@{...} lets you track changes to what is pointed to by HEAD. And hence, your command translates to "You know what HEAD pointed to just before we messed things up? Let's go back there..." - sounds like a pretty useful tool. Commented Mar 12, 2012 at 3:08
  • @SteveBennett Yup! It's very useful because it makes it far easier to undo an accidental command than trying to backtrace what you did. Sadly it's not a very well known feature of Git. Commented Mar 12, 2012 at 3:10
0

After removing the unwanted remote (git remote rm ...), just git reset --hard to the spot you want your current branch to be on.

git reset --hard origin/master

If you were on master before, this resets your master to be the same spot that your origin remote's master is it. That's it!

1
  • Just want to note that this assumes you don't have any unpushed local commits. Commented Mar 12, 2012 at 1:14
0
git stash
git reset --hard HEAD^
git stash apply
2
  • Wouldn't git stash also stash the half-merged files? Commented Mar 12, 2012 at 1:14
  • @SteveBennett: Yeah youre right, i didn't read the part about merge conflicts still beeing there. Commented Mar 12, 2012 at 1:15
0

From now on

git fetch

Inspect what you got in gitk or git log or anything else. Now merge or rebase what you got to where you want it to go.

2
  • 2
    Are you saying you never use git pull? Commented Mar 12, 2012 at 3:05
  • Correct. I used to. I don't anymore. Commented Mar 12, 2012 at 22:34

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