1

I made a mistake and accidentally was committing to master for a while, and now that I've realized my mistake, I want to move those commit off of the master and back into my own staging branch.

Is this possible, to do with git or am I going to have to manually move files around?

alexgolec
  • 26,898
  • 33
  • 107
  • 159
  • possible duplicate of [How can I move a set of commits from master to a separate branch?](http://stackoverflow.com/questions/1178553/how-can-i-move-a-set-of-commits-from-master-to-a-separate-branch) – mmmmmm Jul 10 '12 at 14:07

2 Answers2

1

If your mistakes are such that master currently looks like:

A->B->C->D

and you just want to move C and D to a new branch, it's pretty easy:

$ git checkout master      # move to D
$ git branch new-branch    # create new branch at D
$ git reset B-sha1         # reset master to B
$ git checkout new-branch  # continue working on new-branch

Depending on what changes are introduced by C and D, this may not work cleanly. For example, if C introduces a new file, git may not let you do the checkout of new-branch for fear of overwriting the file. (When master is checked out at B, git thinks the file is untracked.) You could add a git clean -xdf after the reset, or do reset --hard depending on the circumstances.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • So what this is doing is moving things to a different branch, and development continues there? Does this allow me to salvage the remote master as well? – alexgolec Jul 10 '12 at 14:44
  • @Alex If you have already pushed to a remote, you have more work to do. If you know that no one else has pulled from that remote, you can do an update-ref there, but if you cannot guarantee that you will need to add some `revert` commits. If you a – William Pursell Jul 10 '12 at 14:49
0

Assuming you made 5 commits to master by mistake, move the commits:

git checkout master
git branch temp
git rebase --onto yourbranch temp~5 temp

Update the branches:

git push . temp:yourbranch
git push . master~5:master -f

Update your remote master:

git push origin master -f

Tell your colleagues what you did so they can adjust their master according to your correction.

Adam Dymitruk
  • 124,556
  • 26
  • 146
  • 141