Debian Codegraph @

plumbing/object/commit.go

raw
1 package object
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "slices"
9 "strings"
10
11 "github.com/ProtonMail/go-crypto/openpgp"
12
13 "github.com/go-git/go-git/v5/plumbing"
14 "github.com/go-git/go-git/v5/plumbing/storer"
15 "github.com/go-git/go-git/v5/utils/ioutil"
16 "github.com/go-git/go-git/v5/utils/sync"
17 )
18
19 const (
20 beginpgp string = "-----BEGIN PGP SIGNATURE-----"
21 endpgp string = "-----END PGP SIGNATURE-----"
22 headerpgp string = "gpgsig"
23 headerpgp256 string = "gpgsig-sha256"
24 headerencoding string = "encoding"
25
26 // https://github.com/git/git/blob/bcb6cae2966cc407ca1afc77413b3ef11103c175/Documentation/gitformat-signature.txt#L153
27 // When a merge commit is created from a signed tag, the tag is embedded in
28 // the commit with the "mergetag" header.
29 headermergetag string = "mergetag"
30
31 defaultUtf8CommitMessageEncoding MessageEncoding = "UTF-8"
32 )
33
34 // Hash represents the hash of an object
35 type Hash plumbing.Hash
36
37 // MessageEncoding represents the encoding of a commit
38 type MessageEncoding string
39
40 // Commit points to a single tree, marking it as what the project looked like
41 // at a certain point in time. It contains meta-information about that point
42 // in time, such as a timestamp, the author of the changes since the last
43 // commit, a pointer to the previous commit(s), etc.
44 // http://shafiulazam.com/gitbook/1_the_git_object_model.html
45 //
46 // When a Commit is populated by Decode it retains a reference to the source
47 // plumbing.EncodedObject so that EncodeWithoutSignature can reproduce the
48 // exact bytes the signature was computed over. Refer to EncodeWithoutSignature
49 // for more information.
50 type Commit struct {
51 // Hash of the commit object.
52 Hash plumbing.Hash
53 // Author is the original author of the commit.
54 Author Signature
55 // Committer is the one performing the commit, might be different from
56 // Author.
57 Committer Signature
58 // MergeTag is the embedded tag object when a merge commit is created by
59 // merging a signed tag.
60 MergeTag string
61 // PGPSignature is the PGP signature of the commit.
62 PGPSignature string
63 // Message is the commit message, contains arbitrary text.
64 Message string
65 // TreeHash is the hash of the root tree of the commit.
66 TreeHash plumbing.Hash
67 // ParentHashes are the hashes of the parent commits of the commit.
68 ParentHashes []plumbing.Hash
69 // Encoding is the encoding of the commit.
70 Encoding MessageEncoding
71 // List of extra headers of the commit
72 ExtraHeaders []ExtraHeader
73
74 s storer.EncodedObjectStorer
75 // src holds the encoded object this Commit was decoded from, used by
76 // EncodeWithoutSignature to recover the canonical signed bytes.
77 src plumbing.EncodedObject
78 }
79
80 // ExtraHeader holds any non-standard header
81 type ExtraHeader struct {
82 // Header name
83 Key string
84 // Value of the header
85 Value string
86 }
87
88 // Implement fmt.Formatter for ExtraHeader
89 func (h ExtraHeader) Format(f fmt.State, verb rune) {
90 switch verb {
91 case 'v':
92 fmt.Fprintf(f, "ExtraHeader{Key: %v, Value: %v}", h.Key, h.Value)
93 default:
94 fmt.Fprintf(f, "%s", h.Key)
95 if len(h.Value) > 0 {
96 fmt.Fprint(f, " ")
97 // Content may be spread on multiple lines, if so we need to
98 // prepend each of them with a space for "continuation".
99 value := strings.TrimSuffix(h.Value, "\n")
100 lines := strings.Split(value, "\n")
101 fmt.Fprint(f, strings.Join(lines, "\n "))
102 }
103 }
104 }
105
106 // Parse an extra header and indicate whether it may be continue on the next line
107 func parseExtraHeader(line []byte) (ExtraHeader, bool) {
108 split := bytes.SplitN(line, []byte{' '}, 2)
109
110 out := ExtraHeader{
111 Key: string(bytes.TrimRight(split[0], "\n")),
112 Value: "",
113 }
114
115 if len(split) == 2 {
116 out.Value += string(split[1])
117 return out, true
118 } else {
119 return out, false
120 }
121 }
122
123 // GetCommit gets a commit from an object storer and decodes it.
124 func GetCommit(s storer.EncodedObjectStorer, h plumbing.Hash) (*Commit, error) {
125 o, err := s.EncodedObject(plumbing.CommitObject, h)
126 if err != nil {
127 return nil, err
128 }
129
130 return DecodeCommit(s, o)
131 }
132
133 // DecodeCommit decodes an encoded object into a *Commit and associates it to
134 // the given object storer.
135 func DecodeCommit(s storer.EncodedObjectStorer, o plumbing.EncodedObject) (*Commit, error) {
136 c := &Commit{s: s}
137 if err := c.Decode(o); err != nil {
138 return nil, err
139 }
140
141 return c, nil
142 }
143
144 // Tree returns the Tree from the commit.
145 func (c *Commit) Tree() (*Tree, error) {
146 return GetTree(c.s, c.TreeHash)
147 }
148
149 // PatchContext returns the Patch between the actual commit and the provided one.
150 // Error will be return if context expires. Provided context must be non-nil.
151 //
152 // NOTE: Since version 5.1.0 the renames are correctly handled, the settings
153 // used are the recommended options DefaultDiffTreeOptions.
154 func (c *Commit) PatchContext(ctx context.Context, to *Commit) (*Patch, error) {
155 fromTree, err := c.Tree()
156 if err != nil {
157 return nil, err
158 }
159
160 var toTree *Tree
161 if to != nil {
162 toTree, err = to.Tree()
163 if err != nil {
164 return nil, err
165 }
166 }
167
168 return fromTree.PatchContext(ctx, toTree)
169 }
170
171 // Patch returns the Patch between the actual commit and the provided one.
172 //
173 // NOTE: Since version 5.1.0 the renames are correctly handled, the settings
174 // used are the recommended options DefaultDiffTreeOptions.
175 func (c *Commit) Patch(to *Commit) (*Patch, error) {
176 return c.PatchContext(context.Background(), to)
177 }
178
179 // Parents return a CommitIter to the parent Commits.
180 func (c *Commit) Parents() CommitIter {
181 return NewCommitIter(c.s,
182 storer.NewEncodedObjectLookupIter(c.s, plumbing.CommitObject, c.ParentHashes),
183 )
184 }
185
186 // NumParents returns the number of parents in a commit.
187 func (c *Commit) NumParents() int {
188 return len(c.ParentHashes)
189 }
190
191 var ErrParentNotFound = errors.New("commit parent not found")
192
193 // ErrMalformedCommit is returned when a commit object cannot be decoded
194 // because its standard headers (tree, parent, author, committer) are missing,
195 // duplicated, or out of order.
196 var ErrMalformedCommit = errors.New("malformed commit")
197
198 // Parent returns the ith parent of a commit.
199 func (c *Commit) Parent(i int) (*Commit, error) {
200 if len(c.ParentHashes) == 0 || i > len(c.ParentHashes)-1 {
201 return nil, ErrParentNotFound
202 }
203
204 return GetCommit(c.s, c.ParentHashes[i])
205 }
206
207 // File returns the file with the specified "path" in the commit and a
208 // nil error if the file exists. If the file does not exist, it returns
209 // a nil file and the ErrFileNotFound error.
210 func (c *Commit) File(path string) (*File, error) {
211 tree, err := c.Tree()
212 if err != nil {
213 return nil, err
214 }
215
216 return tree.File(path)
217 }
218
219 // Files returns a FileIter allowing to iterate over the Tree
220 func (c *Commit) Files() (*FileIter, error) {
221 tree, err := c.Tree()
222 if err != nil {
223 return nil, err
224 }
225
226 return tree.Files(), nil
227 }
228
229 // ID returns the object ID of the commit. The returned value will always match
230 // the current value of Commit.Hash.
231 //
232 // ID is present to fulfill the Object interface.
233 func (c *Commit) ID() plumbing.Hash {
234 return c.Hash
235 }
236
237 // Type returns the type of object. It always returns plumbing.CommitObject.
238 //
239 // Type is present to fulfill the Object interface.
240 func (c *Commit) Type() plumbing.ObjectType {
241 return plumbing.CommitObject
242 }
243
244 func (c *Commit) reset() {
245 storer := c.s
246 *c = Commit{
247 Encoding: defaultUtf8CommitMessageEncoding,
248 s: storer,
249 }
250 }
251
252 // Decode transforms a plumbing.EncodedObject into a Commit struct.
253 func (c *Commit) Decode(o plumbing.EncodedObject) (err error) {
254 if o.Type() != plumbing.CommitObject {
255 return ErrUnsupportedObject
256 }
257
258 c.reset()
259 c.Hash = o.Hash()
260 c.src = o
261
262 reader, err := o.Reader()
263 if err != nil {
264 return err
265 }
266 defer ioutil.CheckClose(reader, &err)
267
268 r := sync.GetBufioReader(reader)
269 defer sync.PutBufioReader(r)
270
271 s := &commitScanner{r: r, c: c}
272 for state := scanTree; state != nil; {
273 state, err = state(s)
274 if err != nil {
275 return err
276 }
277 }
278 if !s.sawTree {
279 return fmt.Errorf("%w: missing tree header", ErrMalformedCommit)
280 }
281 c.Message = s.msgbuf.String()
282 return nil
283 }
284
285 // Encode transforms a Commit into a plumbing.EncodedObject.
286 func (c *Commit) Encode(o plumbing.EncodedObject) error {
287 return c.encode(o, true)
288 }
289
290 // EncodeWithoutSignature exports a Commit into a plumbing.EncodedObject
291 // without any signature headers, producing the payload that PGP/GPG
292 // signatures are computed over.
293 //
294 // Behaviour depends on how the Commit was created:
295 //
296 // - For Commits populated by Decode whose exported fields still match the
297 // source object, the payload is streamed from the raw source bytes with
298 // gpgsig and gpgsig-sha256 headers (and their continuation lines)
299 // stripped verbatim. This preserves the exact bytes the signature was
300 // computed over, regardless of any normalization performed by Decode.
301 //
302 // - For Commits constructed in memory, or for decoded Commits whose
303 // exported fields have been mutated, the payload is derived from the
304 // current struct fields. Mutation is detected by re-decoding the source
305 // object and comparing exported fields; if any differ, the in-memory
306 // representation prevails.
307 func (c *Commit) EncodeWithoutSignature(o plumbing.EncodedObject) error {
308 if c.matchesSource() {
309 return stripObjectSignatures(o, c.src, plumbing.CommitObject)
310 }
311 return c.encode(o, false)
312 }
313
314 // matchesSource reports whether c.src is set and re-decoding it produces a
315 // Commit whose payload-affecting exported fields are identical to those of
316 // c. It is the auto-detection used by EncodeWithoutSignature to decide
317 // between the raw bytes and the struct-encoded payload.
318 //
319 // PGPSignature is intentionally excluded from the comparison: neither path
320 // emits it, so mutating it must not trigger a switch to struct-encode (which
321 // would change the byte layout the caller is trying to verify against).
322 func (c *Commit) matchesSource() bool {
323 if c.src == nil {
324 return false
325 }
326 fresh := &Commit{}
327 if err := fresh.Decode(c.src); err != nil {
328 return false
329 }
330 return c.Hash == fresh.Hash &&
331 signatureEqual(c.Author, fresh.Author) &&
332 signatureEqual(c.Committer, fresh.Committer) &&
333 c.MergeTag == fresh.MergeTag &&
334 c.Message == fresh.Message &&
335 c.TreeHash == fresh.TreeHash &&
336 c.Encoding == fresh.Encoding &&
337 slices.Equal(c.ParentHashes, fresh.ParentHashes) &&
338 slices.Equal(c.ExtraHeaders, fresh.ExtraHeaders)
339 }
340
341 func signatureEqual(a, b Signature) bool {
342 return a.Name == b.Name &&
343 a.Email == b.Email &&
344 a.When.Unix() == b.When.Unix() &&
345 a.When.Format("-0700") == b.When.Format("-0700")
346 }
347
348 func isStandardHeader(key string) bool {
349 switch key {
350 case "tree", "parent", "author", "committer",
351 headerencoding, headermergetag, headerpgp, headerpgp256:
352 return true
353 }
354 return false
355 }
356
357 func (c *Commit) encode(o plumbing.EncodedObject, includeSig bool) (err error) {
358 o.SetType(plumbing.CommitObject)
359 w, err := o.Writer()
360 if err != nil {
361 return err
362 }
363
364 defer ioutil.CheckClose(w, &err)
365
366 if _, err = fmt.Fprintf(w, "tree %s\n", c.TreeHash.String()); err != nil {
367 return err
368 }
369
370 for _, parent := range c.ParentHashes {
371 if _, err = fmt.Fprintf(w, "parent %s\n", parent.String()); err != nil {
372 return err
373 }
374 }
375
376 if _, err = fmt.Fprint(w, "author "); err != nil {
377 return err
378 }
379
380 if err = c.Author.Encode(w); err != nil {
381 return err
382 }
383
384 if _, err = fmt.Fprint(w, "\ncommitter "); err != nil {
385 return err
386 }
387
388 if err = c.Committer.Encode(w); err != nil {
389 return err
390 }
391
392 if c.MergeTag != "" {
393 if _, err = fmt.Fprint(w, "\n"+headermergetag+" "); err != nil {
394 return err
395 }
396
397 // Split tag information lines and re-write with a left padding and
398 // newline. Use join for this so it's clear that a newline should not be
399 // added after this section. The newline will be added either as part of
400 // the PGP signature or the commit message.
401 mergetag := strings.TrimSuffix(c.MergeTag, "\n")
402 lines := strings.Split(mergetag, "\n")
403 if _, err = fmt.Fprint(w, strings.Join(lines, "\n ")); err != nil {
404 return err
405 }
406 }
407
408 if string(c.Encoding) != "" && c.Encoding != defaultUtf8CommitMessageEncoding {
409 if _, err = fmt.Fprintf(w, "\n%s %s", headerencoding, c.Encoding); err != nil {
410 return err
411 }
412 }
413
414 for _, header := range c.ExtraHeaders {
415 if isStandardHeader(header.Key) {
416 continue
417 }
418 if _, err = fmt.Fprintf(w, "\n%s", header); err != nil {
419 return err
420 }
421 }
422
423 if c.PGPSignature != "" && includeSig {
424 if _, err = fmt.Fprint(w, "\n"+headerpgp+" "); err != nil {
425 return err
426 }
427
428 // Split all the signature lines and re-write with a left padding and
429 // newline. Use join for this so it's clear that a newline should not be
430 // added after this section, as it will be added when the message is
431 // printed.
432 signature := strings.TrimSuffix(c.PGPSignature, "\n")
433 lines := strings.Split(signature, "\n")
434 if _, err = fmt.Fprint(w, strings.Join(lines, "\n ")); err != nil {
435 return err
436 }
437 }
438
439 if _, err = fmt.Fprintf(w, "\n\n%s", c.Message); err != nil {
440 return err
441 }
442
443 return err
444 }
445
446 // Stats returns the stats of a commit.
447 func (c *Commit) Stats() (FileStats, error) {
448 return c.StatsContext(context.Background())
449 }
450
451 // StatsContext returns the stats of a commit. Error will be return if context
452 // expires. Provided context must be non-nil.
453 func (c *Commit) StatsContext(ctx context.Context) (FileStats, error) {
454 fromTree, err := c.Tree()
455 if err != nil {
456 return nil, err
457 }
458
459 toTree := &Tree{}
460 if c.NumParents() != 0 {
461 firstParent, err := c.Parents().Next()
462 if err != nil {
463 return nil, err
464 }
465
466 toTree, err = firstParent.Tree()
467 if err != nil {
468 return nil, err
469 }
470 }
471
472 patch, err := toTree.PatchContext(ctx, fromTree)
473 if err != nil {
474 return nil, err
475 }
476
477 return getFileStatsFromFilePatches(patch.FilePatches()), nil
478 }
479
480 func (c *Commit) String() string {
481 return fmt.Sprintf(
482 "%s %s\nAuthor: %s\nDate: %s\n\n%s\n",
483 plumbing.CommitObject, c.Hash, c.Author.String(),
484 c.Author.When.Format(DateFormat), indent(c.Message),
485 )
486 }
487
488 // ErrMultipleSignatures is returned by Verify when the commit carries more
489 // than one armored signature block. Mirrors upstream's parse_gpg_output
490 // rejection of GOODSIG/BADSIG status lines after the first
491 // (gpg-interface.c:257-269): multi-signature commits are intentionally
492 // unsupported because their provenance cannot be reduced to a single
493 // authoritative signer.
494 var ErrMultipleSignatures = errors.New("commit has multiple signatures")
495
496 // Verify performs PGP verification of the commit with a provided armored
497 // keyring and returns openpgp.Entity associated with verifying key on success.
498 func (c *Commit) Verify(armoredKeyRing string) (*openpgp.Entity, error) {
499 if countSignatureBlocks([]byte(c.PGPSignature)) > 1 {
500 return nil, ErrMultipleSignatures
501 }
502
503 keyRingReader := strings.NewReader(armoredKeyRing)
504 keyring, err := openpgp.ReadArmoredKeyRing(keyRingReader)
505 if err != nil {
506 return nil, err
507 }
508
509 // Extract signature.
510 signature := strings.NewReader(c.PGPSignature)
511
512 encoded := &plumbing.MemoryObject{}
513 // Encode commit components, excluding signature and get a reader object.
514 if err := c.EncodeWithoutSignature(encoded); err != nil {
515 return nil, err
516 }
517 er, err := encoded.Reader()
518 if err != nil {
519 return nil, err
520 }
521
522 return openpgp.CheckArmoredDetachedSignature(keyring, er, signature, nil)
523 }
524
525 // Less defines a compare function to determine which commit is 'earlier' by:
526 // - First use Committer.When
527 // - If Committer.When are equal then use Author.When
528 // - If Author.When also equal then compare the string value of the hash
529 func (c *Commit) Less(rhs *Commit) bool {
530 return c.Committer.When.Before(rhs.Committer.When) ||
531 (c.Committer.When.Equal(rhs.Committer.When) &&
532 (c.Author.When.Before(rhs.Author.When) ||
533 (c.Author.When.Equal(rhs.Author.When) && bytes.Compare(c.Hash[:], rhs.Hash[:]) < 0)))
534 }
535
536 func indent(t string) string {
537 var output []string
538 for _, line := range strings.Split(t, "\n") {
539 if len(line) != 0 {
540 line = " " + line
541 }
542
543 output = append(output, line)
544 }
545
546 return strings.Join(output, "\n")
547 }
548
549 // CommitIter is a generic closable interface for iterating over commits.
550 type CommitIter interface {
551 Next() (*Commit, error)
552 ForEach(func(*Commit) error) error
553 Close()
554 }
555
556 // storerCommitIter provides an iterator from commits in an EncodedObjectStorer.
557 type storerCommitIter struct {
558 storer.EncodedObjectIter
559 s storer.EncodedObjectStorer
560 }
561
562 // NewCommitIter takes a storer.EncodedObjectStorer and a
563 // storer.EncodedObjectIter and returns a CommitIter that iterates over all
564 // commits contained in the storer.EncodedObjectIter.
565 //
566 // Any non-commit object returned by the storer.EncodedObjectIter is skipped.
567 func NewCommitIter(s storer.EncodedObjectStorer, iter storer.EncodedObjectIter) CommitIter {
568 return &storerCommitIter{iter, s}
569 }
570
571 // Next moves the iterator to the next commit and returns a pointer to it. If
572 // there are no more commits, it returns io.EOF.
573 func (iter *storerCommitIter) Next() (*Commit, error) {
574 obj, err := iter.EncodedObjectIter.Next()
575 if err != nil {
576 return nil, err
577 }
578
579 return DecodeCommit(iter.s, obj)
580 }
581
582 // ForEach call the cb function for each commit contained on this iter until
583 // an error appends or the end of the iter is reached. If ErrStop is sent
584 // the iteration is stopped but no error is returned. The iterator is closed.
585 func (iter *storerCommitIter) ForEach(cb func(*Commit) error) error {
586 return iter.EncodedObjectIter.ForEach(func(obj plumbing.EncodedObject) error {
587 c, err := DecodeCommit(iter.s, obj)
588 if err != nil {
589 return err
590 }
591
592 return cb(c)
593 })
594 }
595
596 func (iter *storerCommitIter) Close() {
597 iter.EncodedObjectIter.Close()
598 }