Search code examples
gitgit-rebasegit-reset

Git - changing the branch tip to include commits from another branch


I have a git workflow scenario question and have provided the "current" and "desired" branch structures, but I don't know the correct commands to get to the desired state.

Current:

a -- b                --> Branch1 (there are no commits after b)
     \
      \
       c -- d -- e    --> Branch2

I want to rebase or reset head (not merge, as I want a straight line history in log) such that Branch 1 looks like this:

Desired:

a -- b -- c -- d -- e --> Branch1
     \
      \
       c -- d -- e    --> Branch2 (this branch may be removed)

I realise that the head of Branch2 must now be the head of Branch1, but don't know if the following commands will ensure changes c and d will also become part of Branch1 or if the new commit history will look like a -- b -- e:

git checkout Branch1 
git reset Branch2 

Thank you for your time!


Solution

  • Since Branch1 has no commits after b, you can simply fast-forward it to Branch2:

    git checkout Branch1
    git merge --ff-only Branch2
    

    --ff-only forces a fast-forward and forbids a merge commit. See man git-merge#ff.

    After the fast-forward, your tree will look like this:

    a -- b -- c -- d -- e --> Branch1, Branch2
    

    Branch2 can safely be removed. This whole operation is strictly equivalent to removing Branch1 and renaming Branch2 to Branch1. Remember, for git a branch is simply an alias/pointer to a commit.