Search code examples
gitpatchcherry-pick

Create patch from two commits not in sequence not at the head


I have a repo with a single branch and 10 commits. I want to create a patch for all the commits affecting two of the files in the repo, say for example commits #3, 4, and 7, ie not the head, not in sequence, and not labeled. I've kept the scope of commits small so they don't affect unrelated files.

How should I do this?

I've looked at lots of examples online including cherry-pick, squash, and checking out a specific commit in a temp branch, but none of these appear to be close to my scenario, and my head is spinning at all the possibilities.


Solution

  • Make a temporary branch

    git checkout -b tmpb  #3^
    

    Cherry-pick commits #3, 4 and 7 into the branch

    git cherry-pick #3
    git cherry-pick #4
    git cherry-pick #7
    

    Squash them into a single commit

    git rebase -i #3^
    

    Use git format-patch to create a patch

    git format-patch master
    

    Note, that #3, #4 and #7 in commands should be replaced with respective SHA1