4

I have these branches:

  • main
  • feature-base (based on main)
  • feature-foo (based on feature-base)

The branch "feature-base" contains a lot of commits which are not needed any more.

I want to create a new branch "only-foo" which contains the difference between "feature-base" and "feature-foo".

I thought about this solution

git checkout feature
git diff feature-foo > ~/tmp/foo.patch
git switch main
git switch -c only-foo
patch -p0 < ~/tmp/foo.patch

But this does not include binary files.

Is there a better way to apply the difference of two branches to a third branch?

It is fine to get the changes only. It is ok if commit-messages (and other meta-data) from "feature-foo" get lost.

guettli
  • 25,042
  • 81
  • 346
  • 663

2 Answers2

3

Applying a "patch" is always going to be tricky because git lacks the context of the parts that the patch is coming from (which it has when doing cherry-picking and such).

I would do it like this. Suppose the scenario is I want to apply the result of git diff A..B onto C. I would do this:

git checkout -b temp B
git reset --soft A # put all differences between A and B in index ready to commit
git commit -m "Single commit for A..B"
git checkout C
git cherry-pick temp

That should do it.

eftshift0
  • 26,375
  • 3
  • 36
  • 60
2

First create the only-foo branch as a copy of feature-foo:

git branch only-foo feature-foo

Then use use git rebase with the --onto option and rebase it onto main:

git rebase --onto main feature-base only-foo

This makes main the new base, applying to it all commits from only-foo having feature-base as old base.

Note that you can skip creating the only-foo branch and rebase feature-foo directly if you don't need that branch anymore afterwards.

See also the section Advanced rebase application of the git tutorial for further details on rebasing.

michid
  • 10,536
  • 3
  • 32
  • 59