Reputation: 18177
I need to create a patch file for the last N commits and apply them as separate commits to another branch. For N=3 I assume I have to do this:
git diff HEAD~3 HEAD~2 >> diff1
git diff HEAD~2 HEAD~1 >> diff2
git diff HEAD~1 HEAD >> diff3
and then apply them on another branch respectively:
git apply diff1
(push)
git apply diff2
(push)
git apply diff3
Is there any shorter way to do this?
Upvotes: 10
Views: 9712
Reputation: 478
This can be done with git format-patch and git am, respectively. From your example, try:
git format-patch HEAD~3
This will generate files 0001-commit-foo.patch
, 0002-commit-bar.patch
, 0003-commit-baz.patch
. Then you can copy them to another repo and use git am
to apply them:
git am *.patch
This will preserve the commits as you made them in the previous tree including commit messages, SHAs, and timestamps.
Upvotes: 18
Reputation: 124804
You've mentioned in a comment that you need the patches, because the branches are on different projects. That's not a problem. You can add a remote for the other project, and you can cherry-pick from it, even if they don't share a common history. Cherry-picking doesn't concern ancestry, it's just about replaying changes, just as you would with patches.
If for some reason cherry picking is really not an option for you (though I really doubt), you can use loops in Bash, for example:
for ((i = 3, d = 1; i > 0; i--, d++)); do ((j = i - 1)); git diff HEAD~$i HEAD~$j > diff$d; done
You can write a similar loop for the git apply
commands.
Upvotes: 1
Reputation: 871
Try git cherry-pick
commits to another branch (no need to create temporary patches). This questions answers how to cherry-pick multiple commits at a time: How to cherry-pick multiple commits
Upvotes: 1