Git patches

Git patches are a useful way of transferring commits between developers, or even between repositories. There are two ways of creating a patch in Git:

  1. git diff; and
  2. git format-patch.

There are also two ways for applying a patch in Git:

  1. git apply; and
  2. git am.

The steps for applying a patch in Git are straightforward enough:

  1. Create a patch file;
  2. Send the patch file to another developer (optional); and
  3. Apply the patch file, resolving any conflicts.

git diff is a way of displaying the difference between two commits. The output can be written to a file and is the standard way to create a patch.

git format-patch is similar to diff but includes additional commit information such as the name, email and commit date. It is often used when applying full-scale patches that have been received via email.

git apply takes patch files created by either diff or format-patch and applies the changes, but does not commit them. They become unstaged changes, waiting to be committed.

git am, like format-patch, also deals with patches sent via email. am can parse either a mailbox or patch file, using the information it gathers to not only apply the changes of a patch, but create individual commits for every change it encounters.

Example

The below snippet does the trick for me whenever I need to move commits between branches or repositories. I prefer format-patch and git am due to the way they apply commits.

$ git format-patch --stdout SHA..SHA > diff.patch
$ git am diff.patch

The flag --stdout instructs format-patch to place all commits in a single patch, which is sent through to the file diff.patch.