Create and Apply Patches of a Git Repository

This post talks about how to get patch work with git.

Creat patch

The most straightforward way is redirecting the output of git diff to a file. For example:

git diff 240f42f f72f1ea > loading.patch

the above command would write down the new changes the commit f72f1ea made since the commit 240f42f to file loading.patch. Because git diff calls diff and print the difference in its own style, git diff can produce a easy-to-read patch. However, the problem is such patch files may require extra manual work to apply the changes later.

A better choice is git format-patch. git format-patch generates patches from commits and by default stores multiple patch files, each for the changes in one commit. This may be useful, while usually I like combine several commits and get a single patch file, then just pass the --stdout option to tell it output the patch to stdout and redirect the stdout to a file. Here are some examples:

git format-patch --stdout ^240f42f f72f1ea  > loading.patch
git format-patch --stdout 240f42f
git format-patch --stdout --root 240f42f
git format-patch -1 240f42f

The first one picks the same range of commits as the example of git diff, and writes the changes in the file loading.patch with commit information. The second one outputs the committed changes since commit 240f42f. The third command outputs all the changes before commit 240f42f. The last example would output only the changes made by commit 240f42f.

Apply patch

The patch files have ‘+’ and ‘-‘ symbols before every line changed. This feature is good for reading, while it is prohibitively troublesome to copy the changes from the patches.

One tool to apply the patches in a git repository is git apply, for instance:

git apply loading.patch

This command not only goes through all the changed file doing the modification, but also creates new files if necessary. Strength and drawback of this approach is as the following:
✓ it is compatiable with patches generated by normal diff command or git diff.
✘ you need to commit the changes by yourself.

Another tool is git am.

git am loading.patch

the above command can apply the patch as commits to your current git repository. The strength and drawback of this approach is as the oppsite of git apply.

Credits