GIT-FORMAT-PATCH(1)

๐Ÿ’Œ GIT-FORMAT-PATCH(1) โ€” prepare patches for e-mail submission ๐Ÿ’Œ

okay so this is git-format-patch(1) from the Git Manual, and it's lowkey iconic because it turns your commits into cute little UNIX-mailbox-shaped patch messages that you can send by e-mail or feed to git am. ๐ŸŽ€โœจ

โœจ NAME โœจ

git-format-patch โ€” Prepare patches for e-mail submission ๐Ÿ’–

๐ŸŒธ SYNOPSIS ๐ŸŒธ

git format-patch [-k] [(-o|--output-directory) <dir> | --stdout]
                   [--no-thread | --thread[=<style>]]
                   [(--attach|--inline)[=<boundary>] | --no-attach]
                   [-s | --signoff]
                   [--signature=<signature> | --no-signature]
                   [--signature-file=<file>]
                   [-n | --numbered | -N | --no-numbered]
                   [--start-number <n>] [--numbered-files]
                   [--in-reply-to=<message-id>] [--suffix=.<sfx>]
                   [--ignore-if-in-upstream] [--always]
                   [--cover-from-description=<mode>]
                   [--rfc[=<rfc>]] [--subject-prefix=<subject-prefix>]
                   [(--reroll-count|-v) <n>]
                   [--to=<email>] [--cc=<email>]
                   [--[no-]cover-letter] [--quiet]
                   [--commit-list-format=<format-spec>]
                   [--[no-]encode-email-headers]
                   [--no-notes | --notes[=<ref>]]
                   [--interdiff=<previous>]
                   [--range-diff=<previous> [--creation-factor=<percent>]]
                   [--filename-max-length=<n>]
                   [--progress]
                   [<common-diff-options>]
                   [ <since> | <revision-range> ]

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

So the whole vibe is: take each non-merge commit and prep its "patch" in one "message" per commit, formatted to look like a UNIX mailbox. ๐Ÿ“ฌ The output of this command is super convenient for e-mail submission, or for use with git am.

A "message" generated by this command has three parts, bestie:

  • A brief metadata header that begins with From <commit> with a fixed Mon Sep 17 00:00:00 2001 datestamp to help programs like file(1) recognize that the file is an output from this command, plus fields that record the author identity, the author date, and the title of the change (taken from the first paragraph of the commit log message).
  • The second and subsequent paragraphs of the commit log message.
  • The "patch", which is the diff -p --stat output (see git-diff(1)) between the commit and its parent.

The log message and the patch are separated by a line that is a three-dash line. ๐Ÿ’…

There are two ways to specify which commits to operate on:

  1. A single commit, <since>, specifies that the commits leading to the tip of the current branch that are not in the history that leads to the <since> to be output.
  2. Generic <revision-range> expression (see SPECIFYING REVISIONS section in gitrevisions(7)) means the commits in the specified range.

The first rule takes precedence in the case of a single <commit>. To apply the second rule, i.e., format everything since the beginning of history up until <commit>, use the --root option: git format-patch --root <commit>. If you want to format only <commit> itself, you can do this with git format-patch -1 <commit>. ๐Ÿซถ

By default, each output file is numbered sequentially from 1, and uses the first line of the commit message (massaged for pathname safety) as the filename. With the --numbered-files option, the output file names will only be numbers, without the first line of the commit appended. The names of the output files are printed to standard output, unless the --stdout option is specified.

If -o is specified, output files are created in <dir>. Otherwise they are created in the current working directory. The default path can be set with the format.outputDirectory configuration option. The -o option takes precedence over format.outputDirectory. To store patches in the current working directory even when format.outputDirectory points elsewhere, use -o .. All directory components will be created. ๐Ÿ—‚๏ธ

By default, the subject of a single patch is "[PATCH] " followed by the concatenation of lines from the commit message up to the first blank line (see the DISCUSSION section of git-commit(1)).

When multiple patches are output, the subject prefix will instead be "[PATCH n/m] ". To force 1/1 to be added for a single patch, use -n. To omit patch numbers from the subject, use -N. ๐Ÿ”ฅ

If given --thread, git-format-patch will generate In-Reply-To and References headers to make the second and subsequent patch mails appear as replies to the first mail; this also generates a Message-ID header to reference. ๐Ÿงต

๐Ÿ’… OPTIONS ๐Ÿ’…

  • -p, --no-stat โ€” Generate plain patches without any diffstats.
  • -U<n>, --unified=<n> โ€” Generate diffs with <n> lines of context. The number of context lines defaults to diff.context or 3 if the configuration variable is unset. (-U without <n> is silently accepted as a synonym for -p due to a historical accident. ๐Ÿ˜ญ)
  • --output=<file> โ€” Output to a specific file instead of stdout.
  • --output-indicator-new=<char> โ€” Specify the character used to indicate new lines in the generated patch. Normally it's +.
  • --output-indicator-old=<char> โ€” Specify the character used to indicate old lines in the generated patch. Normally it's -.
  • --output-indicator-context=<char> โ€” Specify the character used to indicate context lines in the generated patch. Normally it's ' ' (a space).
  • --indent-heuristic โ€” Enable the heuristic that shifts diff hunk boundaries to make patches easier to read. This is the default. โœจ
  • --no-indent-heuristic โ€” Disable the indent heuristic.
  • --minimal โ€” Spend extra time to make sure the smallest possible diff is produced. โณ
  • --patience โ€” Generate a diff using the "patience diff" algorithm.
  • --histogram โ€” Generate a diff using the "histogram diff" algorithm.
  • --anchored=<text> โ€” Generate a diff using the "anchored diff" algorithm.

This option may be specified more than once.

If a line exists in both the source and destination, exists only once, and starts with <text>, this algorithm attempts to prevent it from appearing as a deletion or addition in the output. It uses the "patience diff" algorithm internally. ๐Ÿช

  • --diff-algorithm=(patience|minimal|histogram|myers) โ€” Choose a diff algorithm. The variants are as follows:
    • default, myers โ€” The basic greedy diff algorithm. Currently, this is the default.
    • minimal โ€” Spend extra time to make sure the smallest possible diff is produced.
    • patience โ€” Use "patience diff" algorithm when generating patches.
    • histogram โ€” This algorithm extends the patience algorithm to "support low-occurrence common elements".

For instance, if you configured the diff.algorithm variable to a non-default value and want to use the default one, then you have to use --diff-algorithm=default option. ๐Ÿ’ก

  • --stat[=<width>[,<name-width>[,<count>]]] โ€” Generate a diffstat. By default, as much space as necessary will be used for the filename part, and the rest for the graph part. Maximum width defaults to terminal width, or 80 columns if not connected to a terminal, and can be overridden by <width>. The width of the filename part can be limited by giving another width <name-width> after a comma or by setting diff.statNameWidth=<name-width>. The width of the graph part can be limited by using --stat-graph-width=<graph-width> or by setting diff.statGraphWidth=<graph-width>. Using --stat or --stat-graph-width affects all commands generating a stat graph, while setting diff.statNameWidth or diff.statGraphWidth does not affect git format-patch. By giving a third parameter <count>, you can limit the output to the first <count> lines, followed by ... if there are more.

These parameters can also be set individually with --stat-width=<width>, --stat-name-width=<name-width> and --stat-count=<count>. ๐Ÿ“Š

  • --compact-summary โ€” Output a condensed summary of extended header information such as file creations or deletions ("new" or "gone", optionally +l if itโ€™s a symlink) and mode changes (+x or -x for adding or removing executable bit respectively) in diffstat. The information is put between the filename part and the graph part. Implies --stat. ๐Ÿง
  • --numstat โ€” Similar to --stat, but shows number of added and deleted lines in decimal notation and pathname without abbreviation, to make it more machine friendly. For binary files, outputs two - instead of saying 0 0.
  • --shortstat โ€” Output only the last line of the --stat format containing total number of modified files, as well as number of added and deleted lines.
  • -X [<param>,...], --dirstat[=<param>,...] โ€” Output the distribution of relative amount of changes for each sub-directory. The behavior of --dirstat can be customized by passing it a comma separated list of parameters. The defaults are controlled by the diff.dirstat configuration variable (see git-config(1)). The following parameters are available:
    • changes โ€” Compute the dirstat numbers by counting the lines that have been removed from the source, or added to the destination. This ignores the amount of pure code movements within a file. In other words, rearranging lines in a file is not counted as much as other changes. This is the default behavior when no parameter is given.
    • lines โ€” Compute the dirstat numbers by doing the regular line-based diff analysis, and summing the removed/added line counts. (For binary files, count 64-byte chunks instead, since binary files have no natural concept of lines). This is a more expensive --dirstat behavior than the changes behavior, but it does count rearranged lines within a file as much as other changes. The resulting output is consistent with what you get from the other --*stat options.
    • files โ€” Compute the dirstat numbers by counting the number of files changed. Each changed file counts equally in the dirstat analysis. This is the computationally cheapest --dirstat behavior, since it does not have to look at the file contents at all.
    • cumulative โ€” Count changes in a child directory for the parent directory as well. Note that when using cumulative, the sum of the percentages reported may exceed 100%. The default (non-cumulative) behavior can be specified with the noncumulative parameter.
    • <limit> โ€” An integer parameter specifies a cut-off percent (3% by default). Directories contributing less than this percentage of the changes are not shown in the output. ๐ŸŒˆ

Example: this next bit counts changed files while straight-up ignoring directories that have less than 10% of the total amount of changed files, and it accumulates child directory counts up into the parent directories: --dirstat=files,10,cumulative. ๐ŸŽ€

  • --cumulative โ€” literally just a synonym for --dirstat=cumulative, bestie. same energy, shorter name ๐Ÿ’…
  • --dirstat-by-file[=<param>,...] โ€” synonym for --dirstat=files,<param>,..., iykyk.
  • --summary โ€” drops a condensed summary of extended header info โ€” creations, renames, mode changes, all the little receipts ๐Ÿงพ
  • --no-renames โ€” turns rename detection off, even when your config file is out here saying it should be on by default. your config said slay, this flag said no ๐Ÿ’€
  • --rename-empty, --no-rename-empty โ€” controls whether empty blobs get used as a rename source. that's it, that's the whole vibe check.
  • --full-index โ€” instead of just the first handful of characters, it shows the full pre- and post-image blob object names on the index line when it's generating patch format output. no more squinting at abbreviated nonsense ๐Ÿ‘‘
  • --binary โ€” on top of --full-index, it outputs a binary diff that can actually be applied with git-apply. iconic for when text diffs just aren't giving.
  • --abbrev[=<n>] โ€” instead of showing the whole full 40-byte hexadecimal object name in diff-raw format output and diff-tree header lines, it shows the shortest prefix that's at least <n> hexdigits long and still uniquely refers to the object. small caveat though: in diff-patch output format, --full-index takes higher precedence โ€” so if --full-index is specified, full blob names get shown regardless of --abbrev. you can also set a non-default number of digits with --abbrev=<n>. โœจ
  • -B[<n>][/<m>], --break-rewrites[=[<n>][/<m>]] โ€” breaks complete rewrite changes into pairs of delete and create. two whole purposes, ok:
    • it affects the way a change that amounts to a total rewrite of a file gets treated โ€” not as a series of deletion and insertion mixed together with a very few lines that happen to match textually as the context, but as a single deletion of everything old followed by a single insertion of everything new. the number <m> controls this aspect of the -B option (defaults to 60%). -B/70% specifies that less than 30% of the original should remain in the result for Git to consider it a total rewrite (i.e. otherwise the resulting patch will be a series of deletion and insertion mixed together with context lines). ๐Ÿซถ
    • when used with -M, a totally-rewritten file is also considered as the source of a rename (usually -M only considers a file that disappeared as the source of a rename), and the number <n> controls this aspect of the -B option (defaults to 50%). -B20% specifies that a change with addition and deletion compared to 20% or more of the file's size are eligible for being picked up as a possible source of a rename to another file. ๐Ÿ”ฅ
  • -M[<n>], --find-renames[=<n>] โ€” detects renames. if <n> is specified, it's a threshold on the similarity index (i.e. amount of addition/deletions compared to the file's size). for example, -M90% means Git should consider a delete/add pair to be a rename if more than 90% of the file hasn't changed. without a % sign, the number gets read as a fraction, with a decimal point before it โ€” i.e., -M5 becomes 0.5, and is thus the same as -M50%. similarly, -M05 is the same as -M5%. to limit detection to exact renames, use -M100%. the default similarity index is 50%. ๐Ÿ’–
  • -C[<n>], --find-copies[=<n>] โ€” detects copies as well as renames. also peep --find-copies-harder. if <n> is specified, it means exactly the same thing as it does for -M<n>. ๐Ÿฆ‹
  • --find-copies-harder โ€” ok so for performance reasons, by default the -C option only finds copies if the original file of the copy was modified in the same changeset. this flag makes the command inspect unmodified files as candidates for the source of the copy. heads up though: this is a very expensive operation for large projects, so use it with caution, fr fr ๐Ÿ˜ญ giving more than one -C option has the same effect.
  • -D, --irreversible-delete โ€” omits the preimage for deletes, i.e. it prints only the header but not the diff between the preimage and /dev/null. the resulting patch is not meant to be applied with patch or git apply โ€” this is solely for people who just want to concentrate on reviewing the text after the change. plus the output obviously lacks enough information to apply such a patch in reverse, even manually, hence the name of the option. ๐Ÿ’€

When used together with -B, it also omits the preimage in the deletion part of a delete/create pair.

  • -l<num> โ€” the -M and -C options involve some preliminary steps that can detect subsets of renames/copies cheaply, followed by an exhaustive fallback portion that compares all remaining unpaired destinations to all relevant sources. (For renames, only remaining unpaired sources are relevant; for copies, all original sources are relevant.) For N sources and destinations, this exhaustive check is O(N^2). this option prevents that exhaustive portion of rename/copy detection from running if the number of source/destination files involved exceeds the specified number. it defaults to diff.renameLimit. note that a value of 0 is treated as unlimited. โญ
  • -O<orderfile> โ€” controls the order in which files appear in the output. this overrides the diff.orderFile configuration variable (see git-config(1)). to cancel diff.orderFile, use -O/dev/null. ๐ŸŽ€

The output order is determined by the order of glob patterns in <orderfile>. all files with pathnames that match the first pattern are output first, all files with pathnames that match the second pattern (but not the first) are output next, and so on. all files with pathnames that do not match any pattern are output last, as if there was an implicit match-all pattern at the end of the file. if multiple pathnames have the same rank (they match the same pattern but no earlier patterns), their output order relative to each other is the normal order.

<orderfile> is parsed like this:

  • Blank lines are ignored, so they can be used as separators for readability.
  • Lines starting with a hash ("#") are ignored, so they can be used for comments. add a backslash ("\") to the beginning of the pattern if it starts with a hash.
  • Each other line contains a single pattern.

Patterns have the same syntax and semantics as patterns used for fnmatch(3) without the FNM_PATHNAME flag, except a pathname also matches a pattern if removing any number of the final pathname components matches the pattern. for example, the pattern "foo*bar" matches "fooasdfbar" and "foo/bar/baz/asdf" but not "foobarx". ๐Ÿ’…

  • --skip-to=<file>, --rotate-to=<file> โ€” discards the files before the named <file> from the output (i.e. skip to), or moves them to the end of the output (i.e. rotate to). these options were invented primarily for the use of the git difftool command, and may not be very useful otherwise. ๐Ÿ™ˆ
  • --relative[=<path>], --no-relative โ€” when run from a subdirectory of the project, it can be told to exclude changes outside the directory and show pathnames relative to it with this option. when you're not in a subdirectory (e.g. in a bare repository), you can name which subdirectory to make the output relative to by giving a <path> as an argument. --no-relative can be used to countermand both the diff.relative config option and a previous --relative. ๐ŸŒธ
  • -a, --text โ€” treats all files as text. no cap.
  • --ignore-cr-at-eol โ€” ignores the carriage-return at the end of line when doing a comparison. bye bye \r ๐Ÿฆ‹
  • --ignore-space-at-eol โ€” ignores changes in whitespace at EOL.
  • -b, --ignore-space-change โ€” ignores changes in the amount of whitespace. this ignores whitespace at line end, and considers all other sequences of one or more whitespace characters to be equivalent. โœจ
  • -w, --ignore-all-space โ€” ignores whitespace when comparing lines. this ignores differences even if one line has whitespace where the other line has none. it's giving zero tolerance for spaces ๐Ÿ’€
  • --ignore-blank-lines โ€” ignores changes whose lines are all blank.
  • -I<regex>, --ignore-matching-lines=<regex> โ€” ignores changes whose all lines match <regex>. this option may be specified more than once. ๐Ÿ”ฅ
  • --inter-hunk-context=<number> โ€” shows the context between diff hunks, up to the specified <number> of lines, thereby fusing hunks that are close to each other. defaults to diff.interHunkContext or 0 if the config option is unset. ๐Ÿซถ
  • -W, --function-context โ€” shows the whole function as context lines for each change. the function names are determined in the same way as git diff works out patch hunk headers (see "Defining a custom hunk-header" in gitattributes(5)). main character energy honestly ๐Ÿ‘‘
  • --ext-diff โ€” allows an external diff helper to be executed. if you set an external diff driver with gitattributes(5), you need to use this option with git-log(1) and friends. ๐Ÿ‘ฏ
  • --no-ext-diff โ€” disallows external diff drivers. periodt.
  • --textconv, --no-textconv โ€” allows (or disallows) external text conversion filters to be run when comparing binary files. see gitattributes(5) for details. important though: because textconv filters are typically a one-way conversion, the resulting diff is suitable for human consumption, but cannot be applied. for this reason, textconv filters are enabled by default only for git-diff(1) and git-log(1), but not for git-format-patch(1) or diff plumbing commands. ๐Ÿ’–
  • --ignore-submodules[=(none|untracked|dirty|all)] โ€” ignores changes to submodules in the diff generation. all is the default. using none will consider the submodule modified when it either contains untracked or modified files or its HEAD differs from the commit recorded in the superproject, and can be used to override any settings of the ignore option in git-config(1) or gitmodules(5). when untracked is used, submodules are not considered dirty when they only contain untracked content (but they are still scanned for modified content). using dirty ignores all changes to the work tree of submodules โ€” only changes to the commits stored in the superproject are shown (this was the behavior until 1.7.0). using all hides all changes to submodules. ๐Ÿงš
  • --src-prefix=<prefix> โ€” shows the given source <prefix> instead of "a/".
  • --dst-prefix=<prefix> โ€” shows the given destination <prefix> instead of "b/".
  • --no-prefix โ€” do not show any source or destination prefix. none. zero. nada. ๐Ÿ’…
  • --default-prefix โ€” uses the default source and destination prefixes ("a/" and "b/"). this overrides configuration variables such as format.noprefix, diff.srcPrefix, diff.dstPrefix, and diff.mnemonicPrefix (see git-config(1)). ๐ŸŒˆ
  • --line-prefix=<prefix> โ€” slaps an extra <prefix> at the front of every single line of output. every one. no escaping it ๐Ÿ’…
  • --ita-invisible-in-index โ€” okay so by default, entries you added with git add -N show up as an existing empty file in git diff and as a new file in git diff --cached. this flag flips that: the entry looks like a new file in git diff and like it doesn't exist at all in git diff --cached. you can undo it with --ita-visible-in-index. heads up though bestie โ€” both of these options are experimental and could get removed in future ๐Ÿ˜ญ so don't get too attached.
  • --max-depth=<depth> โ€” for each pathspec you hand it on the command line, it descends at most <depth> levels of directories. a value of -1 means no limit at all, go wild. can't be combined with wildcards in the pathspec, sorry ๐Ÿซถ. say you've got a tree containing foo/bar/baz โ€” here's what each set of options matches:
    • --max-depth=0 -- foo: foo
    • --max-depth=1 -- foo: foo/bar
    • --max-depth=1 -- foo/bar: foo/bar/baz
    • --max-depth=1 -- foo foo/bar: foo/bar/baz
    • --max-depth=2 -- foo: foo/bar/baz

if you give no pathspec at all, the depth gets measured as if you'd specified all the top-level entries. and note that's different from measuring from the root โ€” because --max-depth=0 would still return foo. that's the whole point: you can still limit depth while asking for just a subset of the top-level entries โœจ

also note: this option is only supported for diffs between tree objects. not against the index, not against the working tree. periodt.

For the full tea on these common options, see also gitdiffcore(7) ๐Ÿ“

  • -<n> โ€” prepare patches from the topmost <n> commits. simple as that.
  • -o <dir>, --output-directory=<dir> โ€” stash the resulting files in <dir> instead of the current working directory.
  • -n, --numbered โ€” name the output in [PATCH n/m] format, even when there's only a single patch.
  • -N, --no-numbered โ€” name the output in [PATCH] format instead.
  • --start-number <n> โ€” start numbering the patches at <n> instead of 1.
  • --numbered-files โ€” output file names become a plain number sequence, without the default first line of the commit tacked on.
  • -k, --keep-subject โ€” don't strip or add [PATCH] on the first line of the commit log message. leave it exactly as it is ๐Ÿ‘‘
  • -s, --signoff โ€” adds a Signed-off-by trailer to the commit message, using your own committer identity. check the signoff option in git-commit(1) for the full rundown.
  • --stdout โ€” prints all commits to standard output in mbox format instead of making a file for each one. convenient fr fr.
  • --attach[=<boundary>] โ€” creates a multipart/mixed attachment where the first part is the commit message and the patch itself lives in the second part, with Content-Disposition: attachment. cute little package ๐ŸŽ€
  • --no-attach โ€” disables creating an attachment, and overrides whatever the configuration setting says. your config doesn't get a vote here.
  • --inline[=<boundary>] โ€” same multipart/mixed attachment deal, first part = commit message, patch in the second part, but this time with Content-Disposition: inline.
  • --thread[=<style>], --no-thread โ€” controls whether In-Reply-To and References headers get added, so the second and subsequent mails show up as replies to the first. it also controls generation of the Message-ID header that's being referenced.

the optional <style> can be either shallow or deep. shallow threading makes every mail a reply to the head of the series โ€” and the head gets chosen from the cover letter, the --in-reply-to, and the first patch mail, in that order. deep threading makes every mail a reply to the previous one. chain time ๐Ÿ”ฅ

the default is --no-thread, unless the format.thread configuration is set. and --thread with no argument is equivalent to --thread=shallow.

โš ๏ธ beware bestie: the default for git send-email is to thread emails itself. so if you want git format-patch to handle the threading, make sure threading is disabled for git send-email. don't let them both do it, that's giving chaos ๐Ÿ’€
  • --in-reply-to=<message-id> โ€” makes the first mail (or all the mails, if you're using --no-thread) appear as a reply to the given <message-id>. this is how you drop a new patch series without shredding existing threads ๐Ÿงต
  • --ignore-if-in-upstream โ€” skips any patch that matches a commit in <until>..<since>. it examines all patches reachable from <since> but not from <until>, compares them against the patches you're generating, and straight-up ignores any that match. no duplicates, no cap ๐Ÿ™ˆ
  • --always โ€” includes patches for commits that don't introduce any change, which are omitted by default. sometimes nothing happened and that's still valid ๐Ÿ’œ
  • --cover-from-description=<mode> โ€” controls which parts of the cover letter get automatically filled in from the branch's description.

<mode> can be any of these:

  • message, default โ€” the cover letter subject gets populated with placeholder text, and the body gets populated with the branch's description. this is the default mode when neither a configuration nor a command line option is specified.
  • subject โ€” the first paragraph of the branch description populates the cover letter subject, and the remainder of the description fills the body of the cover letter.
  • auto โ€” if the first paragraph of the branch description is greater than 100 bytes, the mode becomes message; otherwise subject gets used. it decides for you, main character energy โœจ
  • none โ€” both the cover letter subject and body get populated with placeholder text. nothing from your description, we're starting fresh.
  • --description-file=<file> โ€” uses the contents of <file> instead of the branch's description when generating the cover letter.
  • --subject-prefix=<subject-prefix> โ€” uses [<subject-prefix>] instead of the standard [PATCH] prefix in the subject line. great for naming a patch series, and it can be combined with the --numbered option ๐Ÿ’…

the config variable format.subjectPrefix can also set a subject prefix for a given repository, applied to all patches. this is often useful on mailing lists that receive patches for several repositories โ€” it disambiguates the patches (with a value of e.g. "PATCH my-project"). chefs kiss ๐Ÿ‘‘

  • --filename-max-length=<n> โ€” instead of the standard 64 bytes, chomps the generated output filenames at around <n> bytes (a too-short value gets silently raised to a reasonable length, don't worry). defaults to the value of the format.filenameMaxLength configuration variable, or 64 if that's not configured.
  • --rfc[=<rfc>] โ€” prepends the string <rfc> (defaults to "RFC") to the subject prefix. since the subject prefix defaults to "PATCH", you'll get "RFC PATCH" by default ๐ŸŒˆ

RFC stands for "Request For Comments" โ€” use this when you're sending an experimental patch for discussion rather than for application. "--rfc=WIP" is also a genuinely useful way to signal that a patch isn't complete yet ("WIP" = "Work In Progress"). and if the receiving community's convention for a particular extra string is to have it after the subject prefix, you can prefix the <rfc> string with a dash ("-") to signal that the rest of the <rfc> string should be appended to the subject prefix instead โ€” e.g., --rfc='-(WIP)' results in "PATCH (WIP)". iykyk ๐Ÿฆ‹

  • -v <n>, --reroll-count=<n> โ€” marks the series as the <n>-th iteration of the topic. output filenames get v<n> prepended to them, and the subject prefix ("PATCH" by default, but configurable via --subject-prefix) gets v<n> appended. e.g. --reroll-count=4 may produce a v4-0001-add-makefile.patch file that has "Subject: [PATCH v4 1/20] Add makefile" in it. and <n> doesn't have to be an integer (e.g. --reroll-count=4.4, or --reroll-count=4rev2 are allowed) โ€” but the downside of such a reroll-count is that the range-diff/interdiff with the previous version won't state exactly which version the new iteration is being compared against ๐Ÿ˜ฌ
  • --to=<email> โ€” adds a To: header to the email headers. this is in addition to any configured headers, and you can use it multiple times. the negated form --no-to discards all To: headers added so far (from config or command line). bye felicia ๐Ÿ‘‹
  • --cc=<email> โ€” adds a Cc: header to the email headers. also in addition to any configured headers, also usable multiple times. the negated form --no-cc discards all Cc: headers added so far (from config or command line).
  • --from, --from=<ident> โ€” uses <ident> in the From: header of each email. for a commit email, if the author ident of the commit isn't textually identical to the provided <ident>, it places a From: header in the body of the message with the original author. if no <ident> is given, or the option isn't passed at all, it uses the ident of the current committer.
ngl this option is only useful if you're actually sending the emails and want to identify yourself as the sender while retaining the original author (git am will correctly pick up the in-body header, don't stress). also note git send-email already handles this transformation for you โ€” so don't use this option if you're feeding the result to git send-email. ๐Ÿซถ
  • --force-in-body-from, --no-force-in-body-from โ€” with the e-mail sender specified via the --from option, an in-body "From:" identifying the commit's real author is added at the top of the commit log message by default if the sender differs from the author. with this option, the in-body "From:" gets added even when the sender and the author have the same name and address โ€” which helps if the mailing list software mangles the sender's identity ๐Ÿ˜ญ defaults to the value of the format.forceInBodyFrom configuration variable.
  • --add-header=<header> โ€” adds an arbitrary header to the email headers. in addition to any configured headers, and usable multiple times. for example, --add-header="Organization: git-foo". the negated form --no-add-header discards all headers added so far from config or command line โ€” that's To:, Cc:, and custom ones. scorched earth, love that ๐Ÿ’…
  • --cover-letter, --no-cover-letter โ€” in addition to the patches, generates a cover letter file containing the branch description, commit list and the overall diffstat. you can fill in a description in the file before sending it out โœจ
  • --commit-list-format=<format-spec> โ€” this one controls how the commit list of your patch series gets formatted, and it's lowkey a whole vibe. Accepted values for format-spec are shortlog, modern, or a format-string prefixed with log:. Like, for example, log: %s (%an). The modern option is literally the same as log:%w(72)[%(count)/%(total)] %s. Fun fact: you can drop the log: prefix entirely if your format-string has a % in it (we're expecting it to be part of %<placeholder>). Defaults to the format.commitListFormat configuration variable if that's set, or else shortlog. Heads up though: using this option from the command-line implies --cover-letter unless you also pass --no-cover-letter. ๐Ÿ’…
  • --encode-email-headers, --no-encode-email-headers โ€” this encodes email headers that have non-ASCII characters using "Q-encoding" (as described in RFC 2047) instead of just outputting the headers verbatim. Defaults to whatever format.encodeEmailHeaders configuration variable says. โœจ
  • --interdiff=<previous> โ€” reviewer aid mode, activated ๐Ÿซถ. This inserts an interdiff into the cover letter, or as commentary of the lone patch of a 1-patch series, showing the differences between the previous version of the patch series and the series you're currently formatting. <previous> is a single revision naming the tip of the previous series which shares a common base with the series being formatted โ€” for example git format-patch --cover-letter --interdiff=feature/v1 -3 feature/v2.
  • --range-diff=<previous> โ€” also a reviewer aid, but make it range-diff. Inserts a range-diff (see git-range-diff(1)) into the cover letter, or as commentary of the lone patch of a 1-patch series, showing the differences between the previous version of the patch series and the series currently being formatted. <previous> can be a single revision naming the tip of the previous series if it shares a common base with the series being formatted (for example git format-patch --cover-letter --range-diff=feature/v1 -3 feature/v2), or a revision range if the two versions of the series are disjoint (for example git format-patch --cover-letter --range-diff=feature/v1~3..feature/v1 -3 feature/v2). ๐ŸŒˆ
Note that diff options passed to the command affect how the primary product of format-patch is generated, and they are not passed to the underlying range-diff machinery used to generate the cover-letter material (this may change in the future). So don't come for it if your diff flags don't show up over there, bestie. ๐Ÿ™ˆ
  • --creation-factor=<percent> โ€” used with --range-diff (so like, they're a package deal ๐Ÿ’–), this tweaks the heuristic which matches up commits between the previous and current series of patches by adjusting the creation/deletion cost fudge factor. See git-range-diff(1) for the deets.

Defaults to 999 (the git-range-diff(1) uses 60), because the whole use case is showing comparison with an older iteration of the same topic and the tool should find more correspondence between the two sets of patches. Slay, different defaults for different contexts.

  • --notes[=<ref>], --no-notes โ€” appends the notes (see git-notes(1)) for the commit after the three-dash line. โœจ

The expected use case of this is to write supporting explanation for the commit that does not belong to the commit log message proper, and include it with the patch submission. While one can simply write these explanations after format-patch has run but before sending, keeping them as Git notes allows them to be maintained between versions of the patch series (but see the discussion of the notes.rewrite configuration options in git-notes(1) to use this workflow). Big brain behavior ngl.

The default is --no-notes, unless the format.notes configuration is set.

  • --signature=<signature>, --no-signature โ€” adds a signature to each message produced. Per RFC 3676 the signature is separated from the body by a line with -- on it. If the signature option is omitted the signature defaults to the Git version number. ๐ŸŽ€
  • --signature-file=<file> โ€” works just like --signature except the signature is read from a file. Same energy, different source.
  • --suffix=.<sfx> โ€” instead of using .patch as the suffix for generated filenames, use the specified suffix. A common alternative is --suffix=.txt. Leaving this empty will remove the .patch suffix entirely. โœจ
Note that the leading character does not have to be a dot; for example, you can use --suffix=-patch to get 0001-description-of-my-change-patch. iykyk ๐Ÿฆ‹
  • -q, --quiet โ€” do not print the names of the generated files to standard output. Silence is golden, periodt. ๐Ÿ’…
  • --no-binary โ€” do not output contents of changes in binary files, instead display a notice that those files changed. Patches generated using this option cannot be applied properly, but they are still useful for code review. So like, they're for looking at, not for applying โ€” don't get it twisted. ๐Ÿ‘‘
  • --zero-commit โ€” outputs an all-zero hash in each patch's From header instead of the hash of the commit. Zero thoughts, head empty, hash empty. ๐Ÿ’€
  • --no-base, --base[=<commit>] โ€” record the base tree information to identify the state the patch series applies to. See the BASE TREE INFORMATION section below for details. If <commit> is auto, a base commit is automatically chosen. The --no-base option overrides a format.useAutoBase configuration. ๐Ÿงš
  • --root โ€” treats the revision argument as a <revision-range>, even if it is just a single commit (that would normally be treated as a <since>). Note that root commits included in the specified range are always formatted as creation patches, independently of this flag. ๐Ÿ“
  • --progress โ€” show progress reports on stderr as patches are generated. For when you need to know things are, in fact, happening.

๐ŸŒธ CONFIGURATION ๐ŸŒธ

Okay so you can specify extra mail header lines to be added to each message, defaults for the subject prefix and file suffix, number patches when outputting more than one patch, add To: or Cc: headers, configure attachments, change the patch output directory, and sign off patches โ€” all with configuration variables. It's giving customization era. ๐Ÿ’–

[format]
        headers = "Organization: git-foo\n"
        subjectPrefix = CHANGE
        suffix = .txt
        numbered = auto
        to = <email>
        cc = <email>
        attach [ = mime-boundary-string ]
        signOff = true
        outputDirectory = <directory>
        coverLetter = auto
        commitListFormat = shortlog
        coverFromDescription = auto

๐Ÿ’œ DISCUSSION ๐Ÿ’œ

The patch produced by git format-patch is in UNIX mailbox format, with a fixed "magic" time stamp to indicate that the file is output from format-patch rather than a real mailbox, like so:

From 8f72bad1baf19a53459661343e21d6491c3908d3 Mon Sep 17 00:00:00 2001
From: Tony Luck <tony.luck@intel.com>
Date: Tue, 13 Jul 2010 11:42:54 -0700
Subject: [PATCH] =?UTF-8?q?[IA64]=20Put=20ia64=20config=20files=20on=20the=20?=
 =?UTF-8?q?Uwe=20Kleine-K=C3=B6nig=20diet?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

arch/arm config files were slimmed down using a python script
(See commit c2330e286f68f1c408b4aa6515ba49d57f05beae comment)

Do the same for ia64 so we can have sleek & trim looking
...

Typically it will be placed in a MUA's drafts folder, edited to add timely commentary that should not go in the changelog after the three dashes, and then sent as a message whose body, in our example, starts with "arch/arm config files were...". On the receiving end, readers can save interesting patches in a UNIX mailbox and apply them with git-am(1). ๐ŸŒˆ

When a patch is part of an ongoing discussion, the patch generated by git format-patch can be tweaked to take advantage of the git am --scissors feature. After your response to the discussion comes a line that consists solely of -- >8 -- (scissors and perforation โœ‚๏ธ), followed by the patch with unnecessary header fields removed:

...
> So we should do such-and-such.

Makes sense to me.  How about this patch?

-- >8 --
Subject: [IA64] Put ia64 config files on the Uwe Kleine-Kรถnig diet

arch/arm config files were slimmed down using a python script
...

When sending a patch this way, most often you are sending your own patch, so in addition to the From $SHA1 $magic_timestamp marker you should omit From: and Date: lines from the patch file. The patch title is likely to be different from the subject of the discussion the patch is in response to, so it is likely that you would want to keep the Subject: line, like the example above. iykyk ๐Ÿซถ

๐Ÿ” Checking for patch corruption ๐Ÿ”

Many mailers, if not set up properly, will corrupt whitespace. Gross. Here are two common types of corruption:

  • Empty context lines that do not have any whitespace.
  • Non-empty context lines that have one extra whitespace at the beginning.

One way to test if your MUA is set up correctly is:

  • Send the patch to yourself, exactly the way you would, except with To: and Cc: lines that do not contain the list and maintainer address.
  • Save that patch to a file in UNIX mailbox format. Call it a.patch, say.
  • Apply it:
$ git fetch <project> master:test-apply
$ git switch test-apply
$ git restore --source=HEAD --staged --worktree :/
$ git am a.patch

If it does not apply correctly, there can be various reasons. Let's break it down:

  • The patch itself does not apply cleanly. That is bad but does not have much to do with your MUA. You might want to rebase the patch with git-rebase(1) before regenerating it in this case.
  • The MUA corrupted your patch; "am" would complain that the patch does not apply. Look in the .git/rebase-apply/ subdirectory and see what patch file contains and check for the common corruption patterns mentioned above. ๐Ÿ•ต๏ธ
  • While at it, check the info and final-commit files as well. If what is in final-commit is not exactly what you would want to see in the commit log message, it is very likely that the receiver would end up hand editing the log message when applying your patch. Things like "Hi, this is my first patch.\n" in the patch e-mail should come after the three-dash line that signals the end of the commit message. Noted, bestie โ€” keep the small talk out of the changelog. ๐Ÿ’€

๐Ÿ’Œ MUA-SPECIFIC HINTS ๐Ÿ’Œ

okay bestie, these are the mailer-specific survival notes for sending patches inline without letting your email app absolutely destroy them ๐Ÿ’…

๐ŸŒˆ GMail ๐ŸŒˆ

GMail literally has no way to turn off line wrapping in the web interface, so it will mangle any emails you send ๐Ÿ˜ญ You can however use git send-email and send your patches through the GMail SMTP server, or use any IMAP email client to connect to the google IMAP server and forward the emails through that.

For hints on using git send-email to send your patches through the GMail SMTP server, see the EXAMPLE section of git-send-email(1).

For hints on submission using the IMAP interface, see the EXAMPLE section of git-imap-send(1).

๐ŸŒฉ๏ธ Thunderbird ๐ŸŒฉ๏ธ

By default, Thunderbird will both wrap emails as well as flag them as being format=flowed, both of which will make the resulting email unusable by Git ๐Ÿ’€

There are three different approaches: use an add-on to turn off line wraps, configure Thunderbird to not mangle patches, or use an external editor to keep Thunderbird from mangling the patches.

โœจ Approach #1 (add-on) โœจ

Install the Toggle Line Wrap add-on that is available from https://addons.thunderbird.net/thunderbird/addon/toggle-line-wrap It adds a button "Line Wrap" to the composerโ€™s toolbar that you can tick off. Now you can compose the message as you otherwise do (cut + paste, git format-patch | git imap-send, etc), but you have to insert line breaks manually in any text that you type.

As a bonus feature, the add-on can detect patch text in the composer and warns when line wrapping has not yet been turned off.

The add-on requires a few tweaks of the advanced configuration (about:config). These are listed on the download page.

๐Ÿ› ๏ธ Approach #2 (configuration) ๐Ÿ› ๏ธ

Three steps:

  1. Configure your mail server composition as plain text: Edit...Account Settings...Composition & Addressing, uncheck "Compose Messages in HTML".
  2. Configure your general composition window to not wrap.

Thunderbird 2: Edit..Preferences..Composition, wrap plain text messages at 0

Thunderbird 3: Edit..Preferences..Advanced..Config Editor. Search for mail.wrap_long_lines. Toggle it to make sure it is set to false. Also, search for mailnews.wraplength and set the value to 0.

  1. Disable the use of format=flowed: Edit..Preferences..Advanced..Config Editor. Search for mailnews.send_plaintext_flowed. Toggle it to make sure it is set to false.

After that is done, you should be able to compose email as you otherwise would (cut + paste, git format-patch | git imap-send, etc), and the patches will not be mangled.

๐Ÿงš Approach #3 (external editor) ๐Ÿงš

The following Thunderbird extensions are needed: AboutConfig from https://mjg.github.io/AboutConfig/ and External Editor from https://globs.org/articles.php?lng=en&pg=8

  1. Prepare the patch as a text file using your method of choice.
  2. Before opening a compose window, use Editโ†’Account Settings to uncheck the "Compose messages in HTML format" setting in the "Composition & Addressing" panel of the account to be used to send the patch.
  3. In the main Thunderbird window, before you open the compose window for the patch, use Toolsโ†’about:config to set the following to the indicated values:
mailnews.send_plaintext_flowed  => false
mailnews.wraplength             => 0
  1. Open a compose window and click the external editor icon.
  2. In the external editor window, read in the patch file and exit the editor normally.
Side note: it may be possible to do step 2 with about:config and the following settings but no oneโ€™s tried yet.
mail.html_compose                       => false
mail.identity.default.compose_html      => false
mail.identity.id?.compose_html          => false

There is a script in contrib/thunderbird-patch-inline which can help you include patches with Thunderbird in an easy way. To use it, do the steps above and then use the script as the external editor.

๐ŸŸ KMail ๐ŸŸ

This should help you to submit patches inline using KMail.

  1. Prepare the patch as a text file.
  2. Click on New Mail.
  3. Go under "Options" in the Composer window and be sure that "Word wrap" is not set.
  4. Use Message โ†’ Insert file... and insert the patch.
  5. Back in the compose window: add whatever other text you wish to the message, complete the addressing and subject fields, and press send.

๐ŸŒณ BASE TREE INFORMATION ๐ŸŒณ

The base tree information block is used for maintainers or third party testers to know the exact state the patch series applies to. It consists of the "base commit", which is a well-known commit that is part of the stable part of the project history everybody else works off of, and zero or more "prerequisite patches", which are well-known patches in flight that is not yet part of the "base commit" that need to be applied on top of "base commit" in topological order before the patches can be applied.

The "base commit" is shown as base-commit: followed by the 40-hex of the commit object name. A "prerequisite patch" is shown as prerequisite-patch-id: followed by the 40-hex "patch id", which can be obtained by passing the patch through the git patch-id --stable command.

Imagine that on top of the public commit P, you applied well-known patches X, Y and Z from somebody else, and then built your three-patch series A, B, C, the history would be like:

---P---X---Y---Z---A---B---C

With git format-patch --base=P -3 C (or variants thereof, e.g. with --cover-letter or using Z..C instead of -3 C to specify the range), the base tree information block is shown at the end of the first message the command outputs (either the first patch, or the cover letter), like this:

base-commit: P
prerequisite-patch-id: X
prerequisite-patch-id: Y
prerequisite-patch-id: Z

For non-linear topology, such as

---P---X---A---M---C
    \         /
     Y---Z---B

You can also use git format-patch --base=P -3 C to generate patches for A, B and C, and the identifiers for P, X, Y, Z are appended at the end of the first message.

If set --base=auto in cmdline, it will automatically compute the base commit as the merge base of tip commit of the remote-tracking branch and revision-range specified in cmdline. For a local branch, you need to make it to track a remote branch by git branch --set-upstream-to before using this option.


๐Ÿ”ฅ EXAMPLES ๐Ÿ”ฅ

  • Extract commits between revisions R1 and R2, and apply them on top of the current branch using git am to cherry-pick them:
$ git format-patch -k --stdout R1..R2 | git am -3 -k
  • Extract all commits which are in the current branch but not in the origin branch:
$ git format-patch origin

For each commit a separate file is created in the current directory.

  • Extract all commits that lead to origin since the inception of the project:
$ git format-patch --root origin
  • The same as the previous one:
$ git format-patch -M -B origin

Additionally, it detects and handles renames and complete rewrites intelligently to produce a renaming patch. A renaming patch reduces the amount of text output, and generally makes it easier to review. Note that non-Git patch programs wonโ€™t understand renaming patches, so use it only when you know the recipient uses Git to apply your patch.

  • Extract three topmost commits from the current branch and format them as e-mailable patches:
$ git format-patch -3

๐Ÿ’€ CAVEATS ๐Ÿ’€

Note that format-patch will omit merge commits from the output, even if they are part of the requested range. A simple "patch" does not include enough information for the receiving end to reproduce the same merge commit.

๐Ÿšจ PATCH APPLICATION ๐Ÿšจ

The output from git-format-patch(1) can lead to a different commit message when applied with git-am(1). The patch that is applied may also be different from the one that was generated, or patch application may fail outright ๐Ÿ˜ญ

Any line that is of the form:

  • three-dashes and end-of-line, or
  • a line that begins with diff -, or
  • a line that begins with Index:

is taken as the beginning of a patch, and the commit log message is terminated before the first occurrence of such a line.

Note that this is especially problematic for unindented diffs that occur in the commit message; the diff in the commit message might get applied along with the patch section, or the patch application machinery might trip up because the patch target doesnโ€™t apply. This could for example be caused by a diff in a Markdown code block.

The solution for this is to indent the diff or other text that could cause problems.

This loss of fidelity might be simple to notice if you are applying patches directly from a mailbox. However, changes originating from Git could be applied in bulk, in which case this would be much harder to notice. This could for example be a Linux distribution which uses patch files to apply changes on top of the commits from the upstream repositories. This goes to show that this behavior does not only impact email workflows.

Given these limitations, one might be tempted to use a general-purpose utility like patch(1) instead. However, patch(1) will not only look for unindented diffs (like git-am(1)) but will try to apply indented diffs as well.


๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

git-am(1), git-send-email(1)

๐Ÿงš GIT ๐Ÿงš

Part of the git(1) suite.

๐Ÿ’– okay thatโ€™s the whole page, bestie! Source/version: Git 2.56.0; date: 2026-09-27; page: GIT-FORMAT-PATCH(1). Now go send those patches and slay, periodt ๐Ÿซถโœจ

๐Ÿ“ฆ where this page comes from