Branch off Master but include changes from another unmerged branch

Viewed 833

I have a feature branch that has not yet been merged. I need to create a new branch from Master but I want it to also include the changes from my as of yet unmerged feature branch.

I do not want to branch off my feature branch, how can I do this?

master 
     ~ branch A (not yet merged)
     ~ branch B (new branch which includes changes from branch A)

I was thinking I should perhaps branch from master and then rebase my new branch against branch A?

When I eventually merge branch B after branch A, the changes should only show the branch B changes as branch A has already been merged - is this correct?

1 Answers

There is no special preparation required. You can either

# master is checked out
git checkout -b B
git merge A

or

# A is checked out
git checkout -b B
git merge master

In both cases, your new branch B ends up "branched off master" and with new changes from A. After A is merged back to master, a diff between master and B will no longer show contents of A as different, as these commits are now in the history of both branches. A later merge of B will only include/add those commits which happened for that new feature.

Full example, starting with an empty directory:

# 1st commit
git init
echo "foo" >> foo
git add -A
git commit -m "foo"

# Branch A
git checkout -b A
echo A >> A
git add -A
git commit -m "A"

# Branch B on top of A
git checkout -b B
echo B >> B
git add -A
git commit -m "B"

# More development on master
git checkout master
echo bar >> bar
git add -A
git commit -m "bar"

# First, B "contains" both A and B changes
git diff B

# But after merging A...
git merge A

# ...Diff B now only shows "remaining" changes
git diff B
Related