aboutsummaryrefslogtreecommitdiff
path: root/object/commit/serialize.go
blob: 0642d6563f134270d48c3d88700214bf2b4167a5 (about) (plain) (blame)
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
package commit

import (
	"bytes"
	"errors"
	"fmt"

	objectheader "codeberg.org/lindenii/furgit/object/header"
	objecttype "codeberg.org/lindenii/furgit/object/type"
)

// BytesWithoutHeader renders the raw commit body bytes.
func (commit *Commit) BytesWithoutHeader() ([]byte, error) {
	var buf bytes.Buffer

	if commit.Tree.Algorithm().Size() == 0 {
		return nil, errors.New("object: commit: missing tree id")
	}

	fmt.Fprintf(&buf, "tree %s\n", commit.Tree.String())

	for _, parent := range commit.Parents {
		fmt.Fprintf(&buf, "parent %s\n", parent.String())
	}

	authorBytes, err := commit.Author.Serialize()
	if err != nil {
		return nil, err
	}

	buf.WriteString("author ")
	buf.Write(authorBytes)
	buf.WriteByte('\n')

	committerBytes, err := commit.Committer.Serialize()
	if err != nil {
		return nil, err
	}

	buf.WriteString("committer ")
	buf.Write(committerBytes)
	buf.WriteByte('\n')

	if commit.ChangeID != "" {
		buf.WriteString("change-id ")
		buf.WriteString(commit.ChangeID)
		buf.WriteByte('\n')
	}

	for _, h := range commit.ExtraHeaders {
		if h.Key == "" {
			return nil, errors.New("object: commit: extra header has empty key")
		}

		buf.WriteString(h.Key)
		buf.WriteByte(' ')
		buf.Write(h.Value)
		buf.WriteByte('\n')
	}

	buf.WriteByte('\n')
	buf.Write(commit.Message)

	return buf.Bytes(), nil
}

// BytesWithHeader renders the raw object (header + body).
func (commit *Commit) BytesWithHeader() ([]byte, error) {
	body, err := commit.BytesWithoutHeader()
	if err != nil {
		return nil, err
	}

	header, ok := objectheader.Encode(objecttype.TypeCommit, int64(len(body)))
	if !ok {
		return nil, errors.New("object: commit: failed to encode object header")
	}

	raw := make([]byte, len(header)+len(body))
	copy(raw, header)
	copy(raw[len(header):], body)

	return raw, nil
}