Parsing a Patch

Parse turns one format-patch email into a Patch. This page covers what each field holds and how the message is taken apart.

Anatomy of a format-patch email

The body is split at the first diff --git line (or, for a bare diff with no git header, the first --- / +++ pair). Everything before the --- separator that precedes the diffstat becomes Body; the diffstat itself is dropped. The trailing -- \n<git version> mail signature is stripped from Diff.

The Patch fields

type Patch struct {
	From        string    // raw From header, RFC 2047 decoded
	AuthorName  string
	AuthorEmail string
	Date        time.Time

	Subject    string // prefix stripped
	RawSubject string // original subject line

	MessageID  string
	InReplyTo  string
	References []string

	Series SeriesInfo

	Body  string       // commit message
	Diff  string       // raw unified diff
	Files []FileChange // Diff parsed
	Stat  DiffStat

	Header mail.Header // full decoded headers
}

HasDiff() reports whether a diff was present; IsCoverLetter() reports a 0/n subject or a diff-less patch mail.

Subject prefixes

The [PATCH ...] prefix is parsed into SeriesInfo and removed from Subject:

type SeriesInfo struct {
	Index   int    // n in "[PATCH n/m]"
	Total   int    // m
	Version int    // 2 for "v2"; 1 if unspecified
	Prefix  string // e.g. "PATCH" or "RFC PATCH"
	IsCover bool   // the "0/m" message
}
SubjectCleanIndexTotalVersionIsCover
[PATCH] add thingadd thing001false
[PATCH 1/4] firstfirst141false
[PATCH v3 2/4] xx243false
[RFC PATCH 0/2] covercover021true
[bug] not a patch[bug] not a patch001false
Note

Leading brackets are only treated as a patch prefix when they contain a PATCH or RFC token. A subject like [bug] … is left exactly as-is.

Encodings and MIME

Parse decodes:

  • RFC 2047 encoded-words in headers (=?utf-8?q?...?=).
  • quoted-printable and base64 message bodies, per the Content-Transfer-Encoding header.
  • multipart messages — it extracts the first text/plain part.

So a patch mailed with a UTF-8 subject and a quoted-printable body parses without any extra work from you.