How to move commits to another branch?

浪子不回头ぞ 提交于 2019-12-03 05:42:36

(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.

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).

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!