9TrSl9IAlaLfDmffagsw
9TrSl9IAlaLfDmffagsw

Reputation: 405

Reset master to previous commit - how to push

I'm using SourceTree. So I a few commits/pushes were made (they are on remote) and I need to undo them. I tried to 'reverse' changes it didn't do what I expected (ie. didn't fix the problem I'm having). So I reset the master to a specific commit. The code works again, however I'm now six commits behind. How do I update the branch with the reset state (ie. wipe out all the stuff after the working commit I'm on)?

I know questions like this have been asked before but I still haven't been able to figure out how to solve this problem.

Thanks.

Upvotes: 2

Views: 573

Answers (2)

helmbert
helmbert

Reputation: 38014

As Ryan mentioned in his answer, doing a force push might be critical when other users are also using your repository. Alternatively, you can selectively revert the offending commits using git revert. This creates new commits that invert the changes of the original commits.

When you have reset your master to a given commit (and origin/master still pointing to the original remote branch tip), you can revert all commits between your local and remote branch using the following commands:

> git branch master-safe
> git reset --hard origin/master
> for COMMIT in $(git log --format="%H" master-safe..origin/master) ; do
    git revert --no-edit $COMMIT ; done

This will create a whole number of commits. Depending on preference, you can now push these commits (your collaborators will then be able to pull these new commits with a fast-forward merge) or use git rebase -i to squash them into a single commit, first.

Upvotes: 3

Ryan Clark
Ryan Clark

Reputation: 764

git push -f origin master

Will force push the state of your local environment to origin. This is generally discouraged because you can't usually be sure if anyone else has interacted with the code on origin. If this is a personal project, you can do this without causing any damage. If you're on a team, you should let everyone know what you're up to.

Upvotes: 2

Related Questions