2

I was working in a version branch V4.15.0, after I did some minor changes which should have gone to the master branch, I commited and pushed.

What would be the best way to revert this mistake? Is there a way I can move a commit from V4.15.0 to master, without having to delete the commit?

flavio.donze
  • 7,432
  • 9
  • 58
  • 91

2 Answers2

3

First we need to fix the V4.15.0 branch. There are two possible methods.

git revert is the easiest way. When given a single commit id, revert will create its reverse as a new commit in the history.

git checkout V4.15.0
git revert HEAD

If you do not want the history to show your mistake, you'll have to use push --force to reset the history. Please note it is usually a bad practice to rewrite history in non user branches and some repository manager never allows --force on them for that reason. But it might be acceptable in your case, verify with your workflow policies.

# checkout the original V4.15.0 branch
git checkout commit_before_mistake_V4.15.0
# we are now detached from HEAD, so checkout a new branch
git checkout -b fixed_branch
# force push, this rewrites history
git push fixed_branch:V4.15.0 --force

Now we have to move the commit to the master branch.

Fortunately, using any of the above two methods will not delete the erroneous commit. Remember its id and you can use git cherry-pick id to add that commit to any other branch.

git checkout master
git cherry-pick id
Martin
  • 3,960
  • 7
  • 43
  • 43
  • 1
    It's worth mentioning that rewriting history might be dangerous and is discouraged. See [this SO post](http://stackoverflow.com/a/1491022/4494577) – jannis Apr 11 '16 at 13:37
  • 1
    Yes, I added a notice regarding this. Thanks. – Martin Apr 11 '16 at 13:43
2

You will need to do two things. First, revert the commits on the branch where you don't want the commits. Second, cherry-pick the commits that you want to the correct branch.

Happy cherry-picking!

Sheamus
  • 6,506
  • 3
  • 35
  • 61