gunk-dev/the-valley

delta.go

source885985671589main's published tip history
10.0 KiB
1// Package delta is valley-delta-v1: the change between two git trees, as
2// whole files.
3//
4// The delta of a tree R against a tree T is the set of paths whose entries
5// differ between T and R. Each path has a pre-image, its entry in T or
6// absent, and a post-image, its entry in R or absent. An entry is a git
7// mode and the SHA-256 of the content, as in valley-tree-v1: the mode is
8// 100644, 100755 or 120000, and a symlink's content is its target. A
9// rename is a deletion and an addition. Whole contents are hashed, so
10// binary content, the executable bit, symlink targets, CRLF and final
11// newlines are all bound, and nothing is positional.
12//
13// The encoding is exact. It is the header line, then one line per path,
14// sorted bytewise, each path once:
15//
16// valley-delta-v1\n
17// <len> <path> <pre> <post>\n
18//
19// <len> is the path's byte length in decimal, with no sign and no leading
20// zero. <path> is the path's raw bytes as git stores them in the tree, so a
21// reader takes exactly <len> bytes of it, spaces and newlines included.
22// Each image is - for absent, or <mode> <sha256> with the hash in 64
23// lowercase hex digits. Paths are never cleaned, case-folded or
24// Unicode-normalised. The digest is the SHA-256 of the encoding.
25//
26// Parse reads an encoding strictly: it accepts exactly the encodings
27// Between can produce, and Encode writes a parsed delta back byte for byte.
28//
29// The package depends on the standard library alone, and on git for
30// Between.
31package delta
32
33import (
34 "bytes"
35 "crypto/sha256"
36 "encoding/hex"
37 "fmt"
38 "strconv"
39 "strings"
40)
41
42// Header opens every encoding.
43const Header = "valley-delta-v1\n"
44
45// The modes an entry may have: a file, an executable file, and a symlink.
46const (
47 ModeFile = "100644"
48 ModeExec = "100755"
49 ModeSymlink = "120000"
50)
51
52// Image is a path's entry on one side of a delta: its mode and the SHA-256
53// of its content. The zero Image is absent.
54type Image struct {
55 Mode string // ModeFile, ModeExec or ModeSymlink; "" for absent
56 Sum [32]byte
57}
58
59// Absent reports whether the path has no entry on this side.
60func (i Image) Absent() bool { return i.Mode == "" }
61
62// String is the image as the encoding writes it.
63func (i Image) String() string {
64 if i.Absent() {
65 return "-"
66 }
67 return i.Mode + " " + hex.EncodeToString(i.Sum[:])
68}
69
70// Change is one path of a delta, with its two images. The images differ.
71type Change struct {
72 Path string // the raw bytes git stores, which need not be UTF-8
73 Pre, Post Image
74}
75
76// Delta is the changes between two trees, sorted bytewise by path, each
77// path once.
78type Delta []Change
79
80// Encode is the delta's valley-delta-v1 encoding.
81func (d Delta) Encode() []byte {
82 var b bytes.Buffer
83 b.WriteString(Header)
84 for _, c := range d {
85 b.WriteString(strconv.Itoa(len(c.Path)))
86 b.WriteByte(' ')
87 b.WriteString(c.Path)
88 b.WriteByte(' ')
89 b.WriteString(c.Pre.String())
90 b.WriteByte(' ')
91 b.WriteString(c.Post.String())
92 b.WriteByte('\n')
93 }
94 return b.Bytes()
95}
96
97// Digest is the SHA-256 of the delta's encoding, in lowercase hex.
98func (d Delta) Digest() string {
99 sum := sha256.Sum256(d.Encode())
100 return hex.EncodeToString(sum[:])
101}
102
103// maxLenDigits bounds the digits of a length, so that reading one can
104// never overflow. No path git can store is near ten digits long.
105const maxLenDigits = 10
106
107// Parse reads a valley-delta-v1 encoding, strictly. It refuses anything
108// Encode would not write for some pair of trees Between accepts: another
109// header, a length with a sign or a leading zero, or one that does not
110// end at a space; a path that is empty, out of order or given twice, or
111// that no tree could hold; an image whose mode is not one of the three,
112// or whose hash is not 64 lowercase hex digits; a line whose images are
113// equal; and a missing final newline or anything after it.
114func Parse(data []byte) (Delta, error) {
115 if !bytes.HasPrefix(data, []byte(Header)) {
116 return nil, fmt.Errorf("it does not open with the header %q", strings.TrimSuffix(Header, "\n"))
117 }
118 rest := data[len(Header):]
119 var d Delta
120 for k := 1; len(rest) > 0; k++ {
121 c, after, err := parseLine(rest)
122 if err != nil {
123 return nil, fmt.Errorf("entry %d: %w", k, err)
124 }
125 if n := len(d); n > 0 {
126 switch prev := d[n-1].Path; {
127 case c.Path == prev:
128 return nil, fmt.Errorf("entry %d: the path %q is given twice", k, c.Path)
129 case c.Path < prev:
130 return nil, fmt.Errorf("entry %d: the path %q is out of order after %q", k, c.Path, prev)
131 }
132 }
133 d = append(d, c)
134 rest = after
135 }
136 if err := d.checkSides(); err != nil {
137 return nil, err
138 }
139 return d, nil
140}
141
142// parseLine reads one line of an encoding, and returns what follows it.
143func parseLine(b []byte) (Change, []byte, error) {
144 digits := 0
145 for digits < len(b) && b[digits] >= '0' && b[digits] <= '9' {
146 digits++
147 }
148 switch {
149 case digits == 0:
150 return Change{}, nil, fmt.Errorf("it does not open with a length")
151 case digits > maxLenDigits:
152 return Change{}, nil, fmt.Errorf("its length has more than %d digits", maxLenDigits)
153 case b[0] == '0' && digits > 1:
154 return Change{}, nil, fmt.Errorf("its length %s has a leading zero", b[:digits])
155 case digits == len(b) || b[digits] != ' ':
156 return Change{}, nil, fmt.Errorf("its length is not followed by a space")
157 }
158 n, err := strconv.Atoi(string(b[:digits]))
159 if err != nil {
160 return Change{}, nil, fmt.Errorf("its length %s does not read: %v", b[:digits], err)
161 }
162 b = b[digits+1:]
163 if n > len(b) {
164 return Change{}, nil, fmt.Errorf("its length %d runs past the end", n)
165 }
166 c := Change{Path: string(b[:n])}
167 if err := checkPath(c.Path); err != nil {
168 return Change{}, nil, err
169 }
170 b = b[n:]
171 if len(b) == 0 || b[0] != ' ' {
172 return Change{}, nil, fmt.Errorf("the path %q is not followed by a space", c.Path)
173 }
174 if c.Pre, b, err = parseImage(b[1:]); err != nil {
175 return Change{}, nil, fmt.Errorf("the pre-image of %q: %w", c.Path, err)
176 }
177 if len(b) == 0 || b[0] != ' ' {
178 return Change{}, nil, fmt.Errorf("the pre-image of %q is not followed by a space", c.Path)
179 }
180 if c.Post, b, err = parseImage(b[1:]); err != nil {
181 return Change{}, nil, fmt.Errorf("the post-image of %q: %w", c.Path, err)
182 }
183 if len(b) == 0 || b[0] != '\n' {
184 return Change{}, nil, fmt.Errorf("the line of %q does not end in a newline after its post-image", c.Path)
185 }
186 if c.Pre == c.Post {
187 return Change{}, nil, fmt.Errorf("the path %q has the same pre-image and post-image, so it is no change", c.Path)
188 }
189 return c, b[1:], nil
190}
191
192// parseImage reads one image, and returns what follows it.
193func parseImage(b []byte) (Image, []byte, error) {
194 if len(b) > 0 && b[0] == '-' {
195 return Image{}, b[1:], nil
196 }
197 mode := 0
198 for mode < len(b) && mode <= len(ModeFile) && b[mode] != ' ' {
199 mode++
200 }
201 if err := checkMode(string(b[:mode])); err != nil {
202 return Image{}, nil, err
203 }
204 if mode == len(b) {
205 return Image{}, nil, fmt.Errorf("its mode is not followed by a space")
206 }
207 i := Image{Mode: string(b[:mode])}
208 b = b[mode+1:]
209 const hexLen = 2 * sha256.Size
210 if len(b) < hexLen || !lowerHex(b[:hexLen]) || (len(b) > hexLen && isHexDigit(b[hexLen])) {
211 return Image{}, nil, fmt.Errorf("its hash is not 64 lowercase hex digits")
212 }
213 hex.Decode(i.Sum[:], b[:hexLen])
214 return i, b[hexLen:], nil
215}
216
217// checkMode refuses a mode no image can have, naming what it is when git
218// would write it: a directory or a submodule is no entry of a delta.
219func checkMode(mode string) error {
220 switch mode {
221 case ModeFile, ModeExec, ModeSymlink:
222 return nil
223 case "40000", "040000":
224 return fmt.Errorf("its mode %s is a directory's, which is no entry", mode)
225 case "160000":
226 return fmt.Errorf("its mode %s is a submodule's, which valley-delta-v1 does not support", mode)
227 case "":
228 return fmt.Errorf("it has no mode")
229 }
230 return fmt.Errorf("its mode %q is not %s, %s or %s", mode, ModeFile, ModeExec, ModeSymlink)
231}
232
233func lowerHex(b []byte) bool {
234 for _, c := range b {
235 if !isHexDigit(c) {
236 return false
237 }
238 }
239 return true
240}
241
242func isHexDigit(c byte) bool {
243 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')
244}
245
246// checkPath refuses a path that no tree a checkout can hold on
247// case-sensitive Linux could give: an empty path, an empty component (a
248// leading, trailing or doubled slash), a component that is . or .., or
249// .git in any case, which git keeps for itself, and a NUL, which a tree
250// entry's name cannot hold.
251func checkPath(p string) error {
252 if p == "" {
253 return fmt.Errorf("a path is empty")
254 }
255 if strings.IndexByte(p, 0) >= 0 {
256 return fmt.Errorf("the path %q holds a NUL", p)
257 }
258 for _, name := range strings.Split(p, "/") {
259 if err := checkName(name); err != nil {
260 return fmt.Errorf("the path %q %w", p, err)
261 }
262 }
263 return nil
264}
265
266// checkName refuses one component of a path, as checkPath describes.
267func checkName(name string) error {
268 switch {
269 case name == "":
270 return fmt.Errorf("has an empty component")
271 case name == "." || name == "..":
272 return fmt.Errorf("has the component %s", name)
273 case strings.EqualFold(name, ".git"):
274 return fmt.Errorf("has the component %s, which git keeps for itself", name)
275 case strings.IndexByte(name, '/') >= 0:
276 return fmt.Errorf("has a component holding a slash")
277 }
278 return nil
279}
280
281// checkSides refuses a delta that names, on one side, a path that is an
282// entry and a directory at once: an image at a and another at a/b. No
283// tree holds both, so no pair of trees gives that delta.
284func (d Delta) checkSides() error {
285 pre, post := map[string]bool{}, map[string]bool{}
286 for _, c := range d {
287 if !c.Pre.Absent() {
288 pre[c.Path] = true
289 }
290 if !c.Post.Absent() {
291 post[c.Path] = true
292 }
293 }
294 for _, c := range d {
295 for i := strings.IndexByte(c.Path, '/'); i >= 0; i = nextSlash(c.Path, i) {
296 dir := c.Path[:i]
297 if !c.Pre.Absent() && pre[dir] {
298 return fmt.Errorf("the pre-images have an entry at %q and another under it at %q", dir, c.Path)
299 }
300 if !c.Post.Absent() && post[dir] {
301 return fmt.Errorf("the post-images have an entry at %q and another under it at %q", dir, c.Path)
302 }
303 }
304 }
305 return nil
306}
307
308// nextSlash is the index of the next slash in p after i, or -1.
309func nextSlash(p string, i int) int {
310 j := strings.IndexByte(p[i+1:], '/')
311 if j < 0 {
312 return -1
313 }
314 return i + 1 + j
315}