alexgolec
alexgolec

Reputation: 28222

Is there a way to remove commits from one branch and place them into another?

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?

Upvotes: 1

Views: 106

Answers (2)

Adam Dymitruk
Adam Dymitruk

Reputation: 129526

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.

Upvotes: 0

William Pursell
William Pursell

Reputation: 212198

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.

Upvotes: 1

Related Questions