gunk-dev/the-valley

delta.go

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