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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.
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 Comment

Just want to note that this assumes you don't have any unpushed local commits.
0
git stash
git reset --hard HEAD^
git stash apply

2 Comments

Wouldn't git stash also stash the half-merged files?
@SteveBennett: Yeah youre right, i didn't read the part about merge conflicts still beeing there.
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 Comments

Are you saying you never use git pull?
Correct. I used to. I don't anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.