What is the best way to git patch a subrange of a branch?

In Subversion, it is easy to merge a range of changesets/diffs from a branch using “svn merge -r a:b mybranch”. But in git, I found it is only possible to cherry-pick a single commit from a branch to apply that patch to my current working branch. So I am wondering if there is a fast way to apply all the commits in one swoop between two tags in a bugfix branch to my current master branch?

The easiest way to perform the action that you are looking for is with git rebase. Here’s a recipe. Assume that tag A is the commit on top of which the patch series that you want to select is based and that tag B is the commit of the final patch in the series. Also, assume that br is the name of the current branch and the branch where the new patch series should be applied.

# Checkout a new temporary branch at the current location
git checkout -b tmp

# Move the br branch to the head of the new patchset
git branch -f br B

# Rebase the patchset onto tmp, the old location of br
git rebase --onto tmp A br

The easiest way I’ve found to do this is:

git cherry-pick starthash..endhash

Note that the two dots have no spaces separating them from the hash labels. Also, this will not cherry-pick starthash, but rather everything after starthash up to and including endhash. To include starthash do git cherry-pick starthash^..endhash.

As far as I know, you can’t git merge this way. Merge is intended to join two branches which have a history in common, not for picking up several commits or patch series. I feel like cherry-picking is fundamentally what you’re asking for.

You can use git cherry (not cherry-pick!) to find out which commits should be inserted into your branch, then git cherry-pick them. You can also explicitly ask git cherry-pick to record the origin of those commits in case you’re cherry-picking from a public branch. This is probably the best way to deal with this problem. (Another could have been to export them via git format-patch and then importing them with git-am/git-apply, but that would likely be slower, plus it won’t record the origin of the commits.)

EDIT: “Public” (branch) should be understood as something not subject to history editing. Of course, you can do this when developing closed-source software without the code being public.

Leave a Comment