Debian Codegraph @

plumbing/object/commit_scanner.go

raw
1 package object
2
3 import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "io"
8 "strings"
9
10 "github.com/go-git/go-git/v5/plumbing"
11 )
12
13 // commitScanner holds the working state of the commit decoder driven by the
14 // stateFn loop in (*Commit).Decode. Each commitState reads one or more lines
15 // from r, updates the in-progress *Commit and the scanner's bookkeeping, and
16 // returns the state that should run next (or nil to stop).
17 type commitScanner struct {
18 r *bufio.Reader
19 c *Commit
20 msgbuf bytes.Buffer
21
22 // pending holds a line that was read but the current state decided to
23 // hand back to the next state, paired with the io.EOF flag that was
24 // returned when the line was originally read.
25 pending []byte
26 pendingErr error
27
28 // First-occurrence tracking: once the corresponding field has been
29 // decoded, subsequent occurrences are silently dropped (matches
30 // upstream's find_commit_header / first-wins semantics).
31 //
32 // gpgsig is not tracked here: upstream's parse_buffer_signed_by_header
33 // (commit.c:1186) accumulates every occurrence into one signature buffer,
34 // so we do the same on the scanner side to keep verification payloads
35 // byte-aligned. gpgsig-sha256 is recognized and skipped without exposing a
36 // new field in v5.
37 sawTree, sawAuthor, sawCommitter bool
38 sawEncoding, sawMergetag bool
39
40 // extra is the multi-line ExtraHeader currently being assembled.
41 extra *ExtraHeader
42 }
43
44 // commitState is one step of the decoder state machine. Each function reads
45 // the lines it needs, mutates *Commit via s.c, and returns the next state to
46 // run (or nil to terminate the loop).
47 type commitState func(*commitScanner) (commitState, error)
48
49 // readLine returns the next line from the buffer, transparently consuming any
50 // line that was previously pushed back by a state that decided not to handle
51 // it.
52 func (s *commitScanner) readLine() ([]byte, error) {
53 if s.pending != nil {
54 line, err := s.pending, s.pendingErr
55 s.pending, s.pendingErr = nil, nil
56 return line, err
57 }
58 line, err := s.r.ReadBytes('\n')
59 if err != nil && err != io.EOF {
60 return line, err
61 }
62 return line, err
63 }
64
65 // pushBack stashes an unconsumed line so the next state's readLine call sees
66 // it. Only one line can be pushed back at a time.
67 func (s *commitScanner) pushBack(line []byte, err error) {
68 s.pending = line
69 s.pendingErr = err
70 }
71
72 // scanTree expects the first non-empty header to be `tree HASH`. Anything
73 // else (or an empty buffer) is rejected with ErrMalformedCommit, matching
74 // upstream's `bogus commit object` check.
75 func scanTree(s *commitScanner) (commitState, error) {
76 line, err := s.readLine()
77 if err != nil && err != io.EOF {
78 return nil, err
79 }
80 if len(line) == 0 || isBlankLine(line) {
81 return nil, fmt.Errorf("%w: missing tree header", ErrMalformedCommit)
82 }
83
84 key, data := splitHeader(line)
85 if key != "tree" {
86 return nil, fmt.Errorf("%w: tree header must be first", ErrMalformedCommit)
87 }
88 h, herr := parseObjectIDHex(data, ErrMalformedCommit, "tree")
89 if herr != nil {
90 return nil, herr
91 }
92 s.c.TreeHash = h
93 s.sawTree = true
94 if err == io.EOF {
95 return nil, nil
96 }
97 return scanParents, nil
98 }
99
100 // scanParents consumes contiguous `parent HASH` lines. The first non-parent
101 // line ends the parent block and is handed off to scanAuthor; any later
102 // `parent` line is silently dropped (matches upstream's parse_commit_buffer
103 // exiting its parent loop at the first non-parent line and
104 // read_commit_extra_header_lines filtering `parent` out of extras).
105 func scanParents(s *commitScanner) (commitState, error) {
106 line, err := s.readLine()
107 if err != nil && err != io.EOF {
108 return nil, err
109 }
110 if len(line) == 0 {
111 return nil, nil
112 }
113 if isBlankLine(line) {
114 return scanMessage, nil
115 }
116
117 key, data := splitHeader(line)
118 if key == "parent" {
119 h, herr := parseObjectIDHex(data, ErrMalformedCommit, "parent")
120 if herr != nil {
121 return nil, herr
122 }
123 s.c.ParentHashes = append(s.c.ParentHashes, h)
124 if err == io.EOF {
125 return nil, nil
126 }
127 return scanParents, nil
128 }
129 s.pushBack(line, err)
130 return scanAuthor, nil
131 }
132
133 // scanAuthor accepts an `author` line at its canonical position immediately
134 // after the parent block. Any other header here is pushed back for
135 // scanCommitter; an out-of-place author is therefore silently dropped.
136 // Mirrors upstream's parse_commit_date func.
137 func scanAuthor(s *commitScanner) (commitState, error) {
138 line, err := s.readLine()
139 if err != nil && err != io.EOF {
140 return nil, err
141 }
142 if len(line) == 0 {
143 return nil, nil
144 }
145 if isBlankLine(line) {
146 return scanMessage, nil
147 }
148
149 key, data := splitHeader(line)
150 if key == "author" {
151 s.c.Author.Decode(data)
152 s.sawAuthor = true
153 if err == io.EOF {
154 return nil, nil
155 }
156 return scanCommitter, nil
157 }
158 s.pushBack(line, err)
159 return scanCommitter, nil
160 }
161
162 // scanCommitter accepts a `committer` line at its canonical position
163 // immediately after the author. Any other header is pushed back for
164 // scanHeaders. Same upstream rationale as scanAuthor.
165 func scanCommitter(s *commitScanner) (commitState, error) {
166 line, err := s.readLine()
167 if err != nil && err != io.EOF {
168 return nil, err
169 }
170 if len(line) == 0 {
171 return nil, nil
172 }
173 if isBlankLine(line) {
174 return scanMessage, nil
175 }
176
177 key, data := splitHeader(line)
178 if key == "committer" {
179 s.c.Committer.Decode(data)
180 s.sawCommitter = true
181 if err == io.EOF {
182 return nil, nil
183 }
184 return scanHeaders, nil
185 }
186 s.pushBack(line, err)
187 return scanHeaders, nil
188 }
189
190 // scanHeaders dispatches one header line. Continuation-bearing headers
191 // (mergetag, gpgsig, gpgsig-sha256, and unknown extras whose value is
192 // continued on subsequent lines) hand off to a dedicated continuation state
193 // that handles the `<space>...` lines and then returns here.
194 func scanHeaders(s *commitScanner) (commitState, error) {
195 line, err := s.readLine()
196 if err != nil && err != io.EOF {
197 return nil, err
198 }
199 if len(line) == 0 {
200 return nil, nil
201 }
202 if isBlankLine(line) {
203 return scanMessage, nil
204 }
205
206 originalLine := line
207 key, data := splitHeader(line)
208
209 var next commitState = scanHeaders
210 switch key {
211 case "tree", "parent", "author", "committer":
212 // Anything reaching scanHeaders with one of these keys is out of
213 // canonical position: duplicate tree, parent past the contiguous
214 // block, or author/committer not at their expected slot. Drop them
215 // the same way upstream's standard_header_field filter excludes
216 // them from the extras list (read_commit_extra_header_lines,
217 // commit.c:1520-1522).
218 case headerencoding:
219 if !s.sawEncoding {
220 s.c.Encoding = MessageEncoding(data)
221 s.sawEncoding = true
222 }
223 case headermergetag:
224 if s.sawMergetag {
225 next = scanSkipCont
226 } else {
227 s.c.MergeTag += string(data) + "\n"
228 s.sawMergetag = true
229 next = scanMergetagCont
230 }
231 case headerpgp:
232 s.c.PGPSignature += string(data) + "\n"
233 next = scanPgpCont
234 case headerpgp256:
235 next = scanSkipCont
236 default:
237 h, multiline := parseExtraHeader(originalLine)
238 if multiline {
239 s.extra = &h
240 next = scanExtraCont
241 } else {
242 s.c.ExtraHeaders = append(s.c.ExtraHeaders, h)
243 }
244 }
245
246 if err == io.EOF {
247 return nil, nil
248 }
249 return next, nil
250 }
251
252 // scanMergetagCont accumulates continuation lines for the first mergetag
253 // header. Continuations strip exactly one leading space, mirroring upstream's
254 // `line + 1` (commit.c:1509). The first non-continuation line is pushed back
255 // so scanHeaders can dispatch it.
256 func scanMergetagCont(s *commitScanner) (commitState, error) {
257 return continuationCont(s, &s.c.MergeTag, scanMergetagCont)
258 }
259
260 // scanPgpCont accumulates continuation lines for a signature header.
261 // Continuations strip exactly one leading space, mirroring upstream's
262 // `line + 1` (commit.c:1509). The first non-continuation line is pushed back
263 // so scanHeaders can dispatch it. Repeat occurrences of the same signature
264 // header land back here and concatenate, matching upstream's
265 // parse_buffer_signed_by_header (commit.c:1186).
266 func scanPgpCont(s *commitScanner) (commitState, error) {
267 return continuationCont(s, &s.c.PGPSignature, scanPgpCont)
268 }
269
270 func continuationCont(s *commitScanner, dst *string, self commitState) (commitState, error) {
271 line, err := s.readLine()
272 if err != nil && err != io.EOF {
273 return nil, err
274 }
275 if len(line) > 0 && line[0] == ' ' {
276 *dst += string(line[1:])
277 if err == io.EOF {
278 return nil, nil
279 }
280 return self, nil
281 }
282 if len(line) > 0 {
283 s.pushBack(line, err)
284 }
285 return scanHeaders, nil
286 }
287
288 // scanSkipCont discards continuation lines that belong to a header scanHeaders
289 // chose to drop.
290 func scanSkipCont(s *commitScanner) (commitState, error) {
291 line, err := s.readLine()
292 if err != nil && err != io.EOF {
293 return nil, err
294 }
295 if len(line) > 0 && line[0] == ' ' {
296 if err == io.EOF {
297 return nil, nil
298 }
299 return scanSkipCont, nil
300 }
301 if len(line) > 0 {
302 s.pushBack(line, err)
303 }
304 return scanHeaders, nil
305 }
306
307 // scanExtraCont accumulates continuation lines for an unknown ExtraHeader
308 // whose value spans multiple lines, then finalises the entry once the
309 // continuation block ends.
310 func scanExtraCont(s *commitScanner) (commitState, error) {
311 line, err := s.readLine()
312 if err != nil && err != io.EOF {
313 return nil, err
314 }
315 if len(line) > 0 && line[0] == ' ' {
316 s.extra.Value += string(line[1:])
317 if err == io.EOF {
318 s.finaliseExtra()
319 return nil, nil
320 }
321 return scanExtraCont, nil
322 }
323 s.finaliseExtra()
324 if len(line) > 0 {
325 s.pushBack(line, err)
326 }
327 return scanHeaders, nil
328 }
329
330 func (s *commitScanner) finaliseExtra() {
331 s.extra.Value = strings.TrimRight(s.extra.Value, "\n")
332 s.c.ExtraHeaders = append(s.c.ExtraHeaders, *s.extra)
333 s.extra = nil
334 }
335
336 // scanMessage drains the remaining bytes into the message buffer.
337 func scanMessage(s *commitScanner) (commitState, error) {
338 for {
339 line, err := s.readLine()
340 if err != nil && err != io.EOF {
341 return nil, err
342 }
343 if len(line) > 0 {
344 s.msgbuf.Write(line)
345 }
346 if err == io.EOF {
347 return nil, nil
348 }
349 }
350 }
351
352 // isBlankLine reports whether line is the canonical header/body separator:
353 // a single newline. Mirrors upstream's `*line == '\n'` test in
354 // read_commit_extra_header_lines (commit.c:1502).
355 func isBlankLine(line []byte) bool {
356 return len(line) == 1 && line[0] == '\n'
357 }
358
359 // splitHeader returns the header keyword (everything before the first space)
360 // and the value (everything after, with the trailing newline stripped). If
361 // the header has no value the returned data is nil.
362 func splitHeader(line []byte) (string, []byte) {
363 trimmed := bytes.TrimRight(line, "\n")
364 key, value, ok := bytes.Cut(trimmed, []byte{' '})
365 if !ok {
366 return string(trimmed), nil
367 }
368 return string(key), value
369 }
370
371 func parseObjectIDHex(data []byte, malformedErr error, header string) (plumbing.Hash, error) {
372 id := string(data)
373 if !plumbing.IsHash(id) {
374 return plumbing.ZeroHash, fmt.Errorf("%w: bad %s hash", malformedErr, header)
375 }
376 return plumbing.NewHash(id), nil
377 }