theduke
theduke

Reputation: 3195

Git diverged branches - revert changes

A new developer went crazy on a large git repository, really messed it up and pushed. All his changes can be thrown away.

My problem: Our git hoster does not allow push --force, so I have to pull first.

If I do so, I have A LOT of merges and conflicts, and there is no point in resolving them. What is the best way to just revert all the changes done by the other guy so I can push my current version?

Upvotes: 2

Views: 2403

Answers (3)

theduke
theduke

Reputation: 3195

I have found a way to do what I needed.

I am posting my solution here for others that are in the same situation. There most likely is an easier way, so please don't hesitate to post if you know one.


First, commit all changes so you have a clean working directory. Check with git status that there are no changes left.

Then, create a new temporary branch to store your changes.

git branch tmp

Now you should find the last commit you and the remote branch diverged. You will need the commit hash, something like 63da978a9a4620790b75dfbae86d658a65dc3e25.

When you found it, reset your master branch to that commit.

git reset --hard COMMIT

Now pull the changes from your remote. No conflicts should occur.

git pull origin master

Now you can revert the commits that should be discarded.

git revert COMMIT1

If you have done everything right, there is just one last step to complete the process: Merging back your tmp branch with all the changes.

git merge tmp

Again, no conflicts should have ocurred.

You now have a up to date branch that can be pushed again. Hurray!

git push origin master

Upvotes: 2

Colin Hebert
Colin Hebert

Reputation: 93197

There is a trick you can try.

git push origin :master

This effectively delete your branch named master. The nice thing is, you don't need any permission to do that (yes I know, weird).

Once that's done, you can just do

git push origin master:master

This will recreate the master branch exactly as it is on your repository.

No need to deal with any conflict/merge. THIS SHOULD NEVER BE USED (except in you case, it's an easy way out).

That trick allows to just remove every commit made by this developer (not there won't be any trace of those at all).


There is the "normal" way to do that:

  • Fetch the branch
  • Revert the faulty commits on the top of the branch
  • Push the reverts
  • Rebase your work on the branch

Upvotes: 1

KurzedMetal
KurzedMetal

Reputation: 12946

To avoid the conflicts, don't merge (by git pulling), just use git fetch.

Anyways if you can't use push --force, the only alternative is to git revert

Upvotes: 0

Related Questions