Move Code Changes Between Branches With Git Patch Files
With patch files Git provides an easy-to-use way to move code changes between branches.
A patch file contains information about the changed lines in a comparable way like it’s shown when doing a git diff.
Here’s how to use it.
Move code from branch A to branch B
Move code from branch A to branch B, where branch B does not depend on branch A.
- On branch
Acreate patch file:
git format-patch -1 COMMIT_ID
- On branch
Bapply the created patch file:
git apply PATCH_FILE
- Interactively choose hunks to add:
git add -p
If branch B depends on branch A and you want to move a change to branch B, then you can do the same. But you need to remove the conflicts.
By the way: The same works for moving changes between repositories.
Closer view at format-patch
This creates a patch file for COMMIT_ID:
git format-patch -1 COMMIT_ID
For the latest commit on the current branch (= HEAD) the following works, too:
git format-patch -1 HEAD
This creates two patch files for the last two commits beginning on COMMIT_ID and including COMMIT_ID:
git format-patch -2 COMMIT_ID
This creates two patch files for the last two commits on the current branch (= HEAD):
git format-patch HEAD~2
This combines the two latest commits into one:
git format-patch -2 HEAD --stdout > last-two.patch
As before it can be used with a specific commits:
git format-patch -2 COMMIT_ID --stdout > last-two.patch
Conclusion
This post showed just a small subset of the possibilities of git patchsets. I can recommend to work with them to have a clean codebase and use it for moving code parts around.