How can I snip the tip off of a branch and put it somewhere else?

I was on a branch, development, and created a new branch, feature1. I coded feature 1, was happy, and decided to start work on feature 2. So I create a new branch feature2 and make one commit. Oh no! Now my tree looks like this:

dev <- . <- . <- feature1 <- feature2

But feature1 and feature2 should both be branching off of dev, like this:

dev <- . <- . <- feature1
  \--- feature2

How can I achieve this result? I've been trying various forms of git rebase all night and can't get any joy.

3 answers

  • answered 2018-12-05 20:06 0x5453

    One option:

    git checkout feature2
    git rebase -i dev
    # Delete all commits between 'dev' and feature2

  • answered 2018-12-05 20:09 Minn

    This can be done by first creating the new branch:

    git checkout -b feature2 dev

    Followed by a cherry-pick:

    git cherry-pick feature1

    Then back to the old branch and remove the commit from there:

    git checkout feature1
    git reset @^ --hard

  • answered 2018-12-05 20:13 alfunx

    Assuming the branches are named as shown, the rebase command should look as follows:

    git rebase feature1 feature2 --onto dev

    One syntax for git rebase is:

    git rebase <upstream> <branch> --onto <newbase>

    If <branch> was specified, Git first does git checkout <branch>. Afterwards, it calculates the base commit between <upstream> and the currently checked-out branch. In our case, feature1 itself is the base commit, since its an ancestor of feature2. Next, Git will take all commits of the currently checked-out branch, up until that base commit, and apply them on <newbase>.