-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail.go
More file actions
217 lines (192 loc) · 6.17 KB
/
Copy pathemail.go
File metadata and controls
217 lines (192 loc) · 6.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package mailpatch
import (
"encoding/base64"
"errors"
"io"
"mime"
"mime/multipart"
"mime/quotedprintable"
"net/mail"
"regexp"
"strconv"
"strings"
)
// extractText returns the text/plain body of a message, decoding the
// Content-Transfer-Encoding and, for multipart messages, picking the first
// text/plain part. format-patch mail is almost always single-part text, but
// some mailers wrap it.
func extractText(h mail.Header, body io.Reader) ([]byte, error) {
ctype := h.Get("Content-Type")
mediatype, params, _ := mime.ParseMediaType(ctype)
if strings.HasPrefix(mediatype, "multipart/") {
if b := firstTextPart(body, params["boundary"]); b != nil {
return b, nil
}
// Fall through: treat the whole thing as text if no part matched.
}
raw, err := io.ReadAll(body)
if err != nil {
return nil, errors.Join(ErrMalformed, err)
}
return decodeCTE(h.Get("Content-Transfer-Encoding"), raw), nil
}
// firstTextPart walks a multipart body and returns the decoded bytes of the
// first text/plain part, or nil if none is found.
func firstTextPart(body io.Reader, boundary string) []byte {
if boundary == "" {
return nil
}
mr := multipart.NewReader(body, boundary)
for {
part, err := mr.NextPart()
if err != nil {
return nil
}
mt, _, _ := mime.ParseMediaType(part.Header.Get("Content-Type"))
if mt == "" || mt == "text/plain" {
raw, err := io.ReadAll(part)
if err != nil {
return nil
}
return decodeCTE(part.Header.Get("Content-Transfer-Encoding"), raw)
}
}
}
func decodeCTE(enc string, raw []byte) []byte {
switch strings.ToLower(strings.TrimSpace(enc)) {
case "quoted-printable":
if out, err := io.ReadAll(quotedprintable.NewReader(strings.NewReader(string(raw)))); err == nil {
return out
}
case "base64":
s := strings.Join(strings.Fields(string(raw)), "")
if out, err := base64.StdEncoding.DecodeString(s); err == nil {
return out
}
}
return raw
}
// patchPrefixRe matches a run of leading "[...]" bracket groups.
var patchPrefixRe = regexp.MustCompile(`^\s*((?:\[[^\]]*\]\s*)+)(.*)$`)
// parseSubject strips a "[PATCH ...]" prefix from a subject and returns the
// clean subject plus the parsed series position. If the leading brackets do
// not look like a patch prefix (no "PATCH"/"RFC" token), the subject is
// returned unchanged.
func parseSubject(subject string) (clean string, info SeriesInfo) {
info.Version = 1
m := patchPrefixRe.FindStringSubmatch(subject)
if m == nil {
return strings.TrimSpace(subject), info
}
brackets, rest := m[1], m[2]
tokens := bracketTokens(brackets)
if !hasPatchToken(tokens) {
// Leading brackets are something else (e.g. "[bug]"); leave as-is.
return strings.TrimSpace(subject), info
}
var prefixWords []string
for _, tok := range tokens {
switch {
case isCountToken(tok):
n, total := parseCount(tok)
info.Index, info.Total = n, total
info.IsCover = total > 0 && n == 0
case isVersionToken(tok):
info.Version, _ = strconv.Atoi(tok[1:])
default:
prefixWords = append(prefixWords, tok)
}
}
info.Prefix = strings.Join(prefixWords, " ")
return strings.TrimSpace(rest), info
}
var bracketGroupRe = regexp.MustCompile(`\[([^\]]*)\]`)
// bracketTokens flattens "[RFC PATCH v2 1/3]" into its whitespace-separated
// words across all leading bracket groups.
func bracketTokens(brackets string) []string {
groups := bracketGroupRe.FindAllStringSubmatch(brackets, -1)
toks := make([]string, 0, len(groups))
for _, group := range groups {
toks = append(toks, strings.Fields(group[1])...)
}
return toks
}
func hasPatchToken(tokens []string) bool {
for _, t := range tokens {
switch strings.ToUpper(t) {
case "PATCH", "RFC":
return true
}
}
return false
}
var countRe = regexp.MustCompile(`^(\d+)/(\d+)$`)
func isCountToken(t string) bool { return countRe.MatchString(t) }
func parseCount(t string) (n, total int) {
m := countRe.FindStringSubmatch(t)
n, _ = strconv.Atoi(m[1])
total, _ = strconv.Atoi(m[2])
return n, total
}
var versionRe = regexp.MustCompile(`^v\d+$`)
func isVersionToken(t string) bool { return versionRe.MatchString(strings.ToLower(t)) }
// splitBodyDiff separates the commit message from the diff in a format-patch
// body. The diff begins at the first "diff --git" line, or failing that at the
// first unified-diff "--- " / "+++ " header pair. The "---" separator line and
// the diffstat that git places before the diff are dropped from the body, and
// the trailing "-- \n<git version>" signature is dropped from the diff.
func splitBodyDiff(body string) (commitMsg, diff string) {
lines := strings.Split(body, "\n")
start := diffStart(lines)
if start < 0 {
return strings.TrimRight(stripSignature(lines), "\n"), ""
}
// Walk back over the diffstat to the "---" separator, if present, so the
// body excludes it.
bodyEnd := start
if sep := separatorBefore(lines, start); sep >= 0 {
bodyEnd = sep
}
commitMsg = strings.TrimRight(strings.Join(lines[:bodyEnd], "\n"), "\n")
diffLines := lines[start:]
diff = strings.TrimRight(trimSignatureLines(diffLines), "\n")
return commitMsg, diff
}
func diffStart(lines []string) int {
for i, ln := range lines {
if strings.HasPrefix(ln, "diff --git ") {
return i
}
}
// No git header: look for a "--- " immediately followed by "+++ ".
for i := 0; i+1 < len(lines); i++ {
if strings.HasPrefix(lines[i], "--- ") && strings.HasPrefix(lines[i+1], "+++ ") {
return i
}
}
return -1
}
// separatorBefore finds the index of the lone "---" git separator line that
// sits between the commit message and the diffstat, searching backward from
// the diff start. Returns -1 if there is none.
func separatorBefore(lines []string, start int) int {
for i := start - 1; i >= 0; i-- {
if strings.TrimRight(lines[i], " \t") == "---" {
return i
}
}
return -1
}
// trimSignatureLines drops a trailing mail signature ("-- " followed by the
// git version line) from a slice of diff lines and rejoins them.
func trimSignatureLines(lines []string) string {
for i := len(lines) - 1; i >= 0; i-- {
if strings.TrimRight(lines[i], " \t") == "--" || lines[i] == "-- " {
return strings.Join(lines[:i], "\n")
}
}
return strings.Join(lines, "\n")
}
func stripSignature(lines []string) string {
return trimSignatureLines(lines)
}