-
Notifications
You must be signed in to change notification settings - Fork 0
/
commit.go
111 lines (102 loc) · 2.61 KB
/
commit.go
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
// SPDX-License-Identifier: Apache-2.0
// Copyright © 2022 Wrangle Ltd
package objects
import (
"errors"
"io"
"time"
"github.com/wrgl/wrgl/pkg/encoding"
"github.com/wrgl/wrgl/pkg/encoding/objline"
"github.com/wrgl/wrgl/pkg/misc"
)
type Commit struct {
Sum []byte
Table []byte
AuthorName string
AuthorEmail string
Time time.Time
Message string
Parents [][]byte
}
type fieldEncode struct {
label string
f objline.WriteFunc
}
func (c *Commit) WriteTo(w io.Writer) (int64, error) {
buf := misc.NewBuffer(nil)
fields := []fieldEncode{
{"table", objline.WriteBytes(c.Table)},
{"authorName", func(w io.Writer, buf encoding.Bufferer) (n int64, err error) {
return objline.WriteString(w, buf, c.AuthorName)
}},
{"authorEmail", func(w io.Writer, buf encoding.Bufferer) (n int64, err error) {
return objline.WriteString(w, buf, c.AuthorEmail)
}},
{"time", func(w io.Writer, buf encoding.Bufferer) (n int64, err error) {
return objline.WriteTime(w, buf, c.Time)
}},
{"message", func(w io.Writer, buf encoding.Bufferer) (n int64, err error) {
return objline.WriteString(w, buf, c.Message)
}},
}
for _, parent := range c.Parents {
fields = append(fields, fieldEncode{"parent", objline.WriteBytes(parent)})
}
var total int64
for _, l := range fields {
n, err := objline.WriteField(w, buf, l.label, l.f)
if err != nil {
return 0, err
}
total += n
}
return total, nil
}
type fieldDecode struct {
label string
f objline.ReadFunc
}
func (c *Commit) ReadFrom(r io.Reader) (int64, error) {
parser := encoding.NewParser(r)
c.Table = make([]byte, 16)
var total int64
for _, l := range []fieldDecode{
{"table", objline.ReadBytes(c.Table)},
{"authorName", func(p *encoding.Parser) (int64, error) {
return objline.ReadString(p, &c.AuthorName)
}},
{"authorEmail", func(p *encoding.Parser) (int64, error) {
return objline.ReadString(p, &c.AuthorEmail)
}},
{"time", func(p *encoding.Parser) (int64, error) {
return objline.ReadTime(p, &c.Time)
}},
{"message", func(p *encoding.Parser) (int64, error) {
return objline.ReadString(p, &c.Message)
}},
} {
n, err := objline.ReadField(parser, l.label, l.f)
if err != nil {
return 0, err
}
total += int64(n)
}
for {
b := make([]byte, 16)
n, err := objline.ReadField(parser, "parent", objline.ReadBytes(b))
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return 0, err
}
total += int64(n)
c.Parents = append(c.Parents, b)
}
return total, nil
}
func ReadCommitFrom(r io.Reader) (int64, *Commit, error) {
c := &Commit{}
n, err := c.ReadFrom(r)
return n, c, err
}