2

I got a problem. I have done a couple of commits on master. But I made a mistake. I need to do these commits on branch_a. How can I cancel the commits on master and move them to branch_a.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Pan Ruochen
  • 1,990
  • 6
  • 23
  • 34
  • Does branch_a already exist? Are there commits on master that are not on branch_a that you do not want to move to branch_a? Does branch_a have commits that master doesn't? – Andrew Marshall Mar 12 '12 at 01:53
  • Ah, gutted; this might help http://stackoverflow.com/questions/927358/git-undo-last-commit , if I will be you I will revert those changes and then redo that on my feature branch (in your case probably branch_a) and commit the changes, hope this helps, cheers – Tats_innit Mar 12 '12 at 01:54
  • Tats_innit seems to have the right of it. You want to do a combination of `git revert` and `git cherry-pick`. – Borealid Mar 12 '12 at 01:56

3 Answers3

2

Assuming no one else has already seen your changes to master and built something on top of them:

git checkout branch_a
git cherry-pick <commit sha>   # for each commit you want on branch a
git checkout master
git reset <commit sha you want to move master back to>

If someone has already built stuff on top of your accidental master commits, then you'll want to git revert them instead of using reset.

Amber
  • 507,862
  • 82
  • 626
  • 550
2

If you just have a couple commits, then cherry picking them might be the easiest option. You can find the hashes of the commits via git log master. Then do the following.

git checkout branch_a
git cherry-pick COMMIT_HASH_1
git cherry-pick COMMIT_HASH_2
...
git checkout master
git reset --hard COMMIT_HASH_BEFORE

Where all COMMIT_HASH_# are the commits you wish to move to branch_a and COMMIT_HASH_BEFORE is the commit hash from before your erroneous commits. (Note that this will throw away any uncommitted changes in your working directory.)

Note that if you've already pushed the changes to master and other people might have worked with the branch, you'll instead want to git revert the same commits you cherry picked, otherwise you'll cause problems for others working on the branch. (Revert simply creates a new commit which undoes the previous commit.)

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
1

Best thing imo is to reset the master branch but keep your changes. Using cherry-pick will taint the repo with new commits. Assuming you have made two commits:

git checkout master
git reset --soft HEAD~2
git checkout branch_a
git commit -m "foo"

Resetting with --soft means your changes will be kept staged and it will put git in the state as it looked before you made the commits, so you only need to switch branch and re-commit your changes.

rtn
  • 127,556
  • 20
  • 111
  • 121