How to move commits to another branch?

2019-03-17 14:58发布

问题:

I'd like to move my last few commits from master into a branch of their own.

The tree on my PC looks like that:

   W (some branch)
  /       
X1--X2--X3--X4--Y--Z1--Z2 (master)

I'd like it to look like:

   W (some branch)
  /       
X1--X2--X3--X4 (master)
             \
              Y--Z1--Z2 (my new branch)

However, the tree at GitHub looks like:

   W (some branch)
  /       
X1--X2--X3--X4--Y (master)

That's what I saw as a solution for moving the last commits to another branch:

git checkout master
git branch my_new_branch
git reset <commit_id>

My question is: would I be able to successfully push to GitHub after moving the commits into a new branch and if so would it require to do something else than these three commands?

回答1:

(I assume <commit_id> is the object name of X4...)

Those commands will indeed end you up with what you want locally. (You might want to use git reset --hard to keep the working tree and index the same as the commit you're resetting to, but as usual, be very careful that git status is clean before you use that command.)

If you afterwards try to push master to GitHub, it will tell you that everything's already up to date, because the master on GitHub is one commit ahead. You can force the push, so that master is reset on GitHub, but that's rewriting public history, so you should only do that if (a) you're the only who'll have fetched master from GitHub or (b) you can let your collaborators know what do so that they don't accidentally merge Y back in. If that's OK, you can do:

 git push --force origin master

... and then master on GitHub will be the same as your local version.



回答2:

It should work but you will need:

  • to push -f origin master (force the push, which will spell trouble if anyone else has already clone your repo)
  • to push then your new branch (which will then find the X4 sha1 on top of which said new branch will be set).


回答3:

Nobody has mentioned that you can simply cherry pick the commit into another branch. This way your commit message will still be there for you.

Just copy the revision id of your commit you want to move. git log --oneline

Than create a new branch on top of the former commit and change to it: git checkout -b "$newBranchName" HEAD~$n (HEAD~$n stands for the n-th commit) or git checkout -b "$newBranchName" $formerRevsion

Now you just have to cherry pick the wanted commit: git cherry-pick $revision

The old commit will be still in the other branch but you can fix that with rebase. Move back to your old branch and use rebase: git rebase -i HEAD~$n

Just delete the commit line of the cherry picked commit and your branch will be rebased with out it. You have to use git push -f because the revisions of all rebased commits have changed.