简体   繁体   中英

In git, how do I remove a commit from a branch but keep that commit in a separate branch?

I have a DEV branch with a history looking like this (with each list item being a separate commit):

  • feature 5
  • feature 4
  • feature 3
  • feature 2
  • feature 1

Suppose I want to "delete" feature 3 from this branch, but I don't want to lose the code in this feature so I want to put it in it's own separate branch.

Basically, from the dev branch above, I want to end up with two branches looking like this:

DEV BRANCH :

  • feature 5
  • feature 4
  • feature 2
  • feature 1

NEW BRANCH :

  • feature 3
  • feature 2
  • feature 1

Any ideas how I can achieve this in git?

Create a new branch from feature3 . Then reset feature3 from the dev branch. However, if you have pushed these commits you will need to use revert

First create newbranch from feature3

git checkout dev
git branch newbranch feature3
git reset --hard feature3

Now if you haven't pushed to remote

git reset --hard feature3

Or if you have pushed

git revert feature3

Also, if you want to add specific commits to newbranch , like feature7 you can use

git checkout newbranch
git cherry-pick feature7
#create NEW
git branch NEW commit3

#rewrite DEV
git rebase -i commit2 DEV

#in the editor remove the line "pick commit3", save and exit.

To create a new branch till feature3 :

git checkout <feature3_commit_id>
git checkout -b new_branch

To remove feature3 from dev branch

git checkout dev_branch
git rebase --onto <feature2_commit_id> <feature3_commit_id> <feature5_commit_id>

Just FYI, you can use git log --oneline to find commit ids.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM