10

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?

PMBjornerud
  • 829
  • 1
  • 8
  • 17
B Faley
  • 17,120
  • 43
  • 133
  • 223

3 Answers3

17

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.

nasamuffin
  • 458
  • 3
  • 10
  • If anyone struggle with "fatal: could not open '*.patch' for reading: Invalid argument" error message from msysgit, here is why: https://groups.google.com/forum/#!topic/msysgit/1IT785Jf4Zo – Ilya Jun 23 '17 at 20:52
1

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

Community
  • 1
  • 1
TomaszGuzialek
  • 861
  • 1
  • 8
  • 15
1

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.

janos
  • 120,954
  • 29
  • 226
  • 236