3

Let's say we have a branching structure like:

develop   -> --- a --- b --- c
                  \           \
feature 1 ->       \           --- d --- e
                    \    
feature 2 ->         --- f --- g

After doing work on feature 1, I decide it really should of been branched off as a sub-task of feature 2.

Is there a way for feature 1 to 'undo' branching off of develop, and branch off of feature 2 instead, while keeping its commits?

Example:

develop   -> --- a --- b --- c    
                  \    
feature 1 ->       \         --- d --- e
                    \       /
feature 2 ->         f --- g
dpaulus
  • 422
  • 6
  • 16
  • 1
    in this case a rebase won't work. You could do this: ```git checkout g; git cherry-pick e~2..e``` – eftshift0 Apr 06 '17 at 18:10
  • 2
    An idea might be to construct a `feature_1b` branch from `feature2`, cherrypick the commits `d` and `e`. Remove `feature1` and rename `feature1b` to `feature1`. – Willem Van Onsem Apr 06 '17 at 18:12

2 Answers2

7

The simplest solution would be to use rebase with --onto flag, as described in the Git book. The command:

git rebase --onto feature2 develop feature1

Will rebase commits from feature1 that are not found on develop on top of feature2.

1615903
  • 32,635
  • 12
  • 70
  • 99
0

Normally you would look at git rebase for this sort of thing, but it's not going to work because a rebase from feature1 onto feature2 would include commits b and c, which you don't want.

Willem's suggestion to use cherry-pick is probably the way to go.

Create a new branch:

git checkout -b feature1b feature1

Cherry pick the commits of interest (here I am saying "the last two commits of feature1", but but you could specify the range of commits using actual commit ids etc):

git cherry-pick feature1~2..feature1

At this point, branch feature1b matches your desired history. You can perform some optional cleanup, depending on your needs:

Delete the old branch:

git branch -D feature1

Rename the new branch:

git branch -m feature1
larsks
  • 277,717
  • 41
  • 399
  • 399
  • `git rebase --onto feature2 develop feature1` will do it in one step, but I admit this is particularly confusing. :-) – torek Apr 06 '17 at 21:27