Generating Patches

The git format-patch command generates a patch in the form of an email message. It creates one piece of email for each commit you specify. You can specify the commits using any technique discussed in Identifying Commits.

Common use cases include:

  • A specified number of commits, such as -2

  • A commit range, such as master~4..master~2

  • A single commit, often the name of a branch, such as origin/master

While the Git diff machinery lies at the heart of the git format-patch command, it differs from git diff in two key ways:

  • Whereas git diff generates one patch with the combined differences of all the selected commits, git format-patch generates one email message for each selected commit.

  • git diff doesn’t generate email headers. In addition to the actual diff content, git format-patch generates an email message complete with headers that list the commit author, the commit date, and the commit log message associated with the change.

Tip

git format-patch and git log should seem very similar. As an interesting experiment, compare the output of the following two commands: git format-patch -1 and git log -p -1 --pretty=email.

Let’s start with a fairly simple example. Suppose you have a repository with just one file in it named file. Furthermore, the content of that file is a series of single capitalized letters, A through D. Each letter was introduced into the file, one line at a time, and committed using a log message corresponding to that letter:

$ git init
$ echo A > file
$ git add ...

Get Version Control with Git now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.