gunk-dev/the-valley

git.go

sourcee4ada5512f03main's published tip history
5.2 KiB
1package main
2
3import (
4 "archive/tar"
5 "bufio"
6 "bytes"
7 "crypto/sha256"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "sort"
14 "strconv"
15 "strings"
16)
17
18// git runs a git command in repo and returns its stdout. Stderr is folded
19// into the error, because a git failure that does not say what git said is
20// a failure the reader has to reproduce by hand.
21func git(repo string, args ...string) (string, error) {
22 return gitInput(repo, nil, args...)
23}
24
25func gitInput(repo string, stdin []byte, args ...string) (string, error) {
26 cmd := exec.Command("git", args...)
27 cmd.Dir = repo
28 if stdin != nil {
29 cmd.Stdin = bytes.NewReader(stdin)
30 }
31 var out, errb bytes.Buffer
32 cmd.Stdout = &out
33 cmd.Stderr = &errb
34 if err := cmd.Run(); err != nil {
35 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
36 }
37 return out.String(), nil
38}
39
40func gitLine(repo string, args ...string) (string, error) {
41 out, err := git(repo, args...)
42 return strings.TrimSpace(out), err
43}
44
45// gitBlobSums returns the SHA-256 of each named blob's content, in the
46// order asked for. One `cat-file --batch` serves the whole tree.
47func gitBlobSums(repo string, oids []string) ([][32]byte, error) {
48 sums := make([][32]byte, len(oids))
49 if len(oids) == 0 {
50 return sums, nil
51 }
52 cmd := exec.Command("git", "cat-file", "--batch")
53 cmd.Dir = repo
54 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
55 var errb bytes.Buffer
56 cmd.Stderr = &errb
57 stdout, err := cmd.StdoutPipe()
58 if err != nil {
59 return nil, err
60 }
61 if err := cmd.Start(); err != nil {
62 return nil, err
63 }
64 r := bufio.NewReader(stdout)
65 for i := range oids {
66 header, err := r.ReadString('\n')
67 if err != nil {
68 return nil, fmt.Errorf("cat-file: %w: %s", err, strings.TrimSpace(errb.String()))
69 }
70 fields := strings.Fields(strings.TrimSpace(header))
71 if len(fields) != 3 || fields[1] != "blob" {
72 return nil, fmt.Errorf("cat-file: unexpected header %q for %s", strings.TrimSpace(header), oids[i])
73 }
74 size, err := strconv.Atoi(fields[2])
75 if err != nil {
76 return nil, fmt.Errorf("cat-file: bad size in %q", strings.TrimSpace(header))
77 }
78 h := sha256.New()
79 if _, err := io.CopyN(h, r, int64(size)); err != nil {
80 return nil, fmt.Errorf("cat-file: reading %s: %w", oids[i], err)
81 }
82 if _, err := r.Discard(1); err != nil { // the record's trailing newline
83 return nil, err
84 }
85 copy(sums[i][:], h.Sum(nil))
86 }
87 if err := cmd.Wait(); err != nil {
88 return nil, fmt.Errorf("cat-file: %w: %s", err, strings.TrimSpace(errb.String()))
89 }
90 return sums, nil
91}
92
93// exportTree writes a revision's tree to dir. Checks run over the exported
94// tree rather than the working tree, so what was checked is exactly what
95// the subject digest names — an uncommitted edit cannot ride along inside
96// an attestation.
97func exportTree(repo, rev, dir string) error {
98 cmd := exec.Command("git", "archive", "--format=tar", rev)
99 cmd.Dir = repo
100 var errb bytes.Buffer
101 cmd.Stderr = &errb
102 stdout, err := cmd.StdoutPipe()
103 if err != nil {
104 return err
105 }
106 if err := cmd.Start(); err != nil {
107 return err
108 }
109 tr := tar.NewReader(stdout)
110 for {
111 h, err := tr.Next()
112 if err == io.EOF {
113 break
114 }
115 if err != nil {
116 return fmt.Errorf("git archive: %w", err)
117 }
118 if h.Typeflag == tar.TypeXGlobalHeader {
119 continue // git archive stamps the commit id here; not a tree entry
120 }
121 target := filepath.Join(dir, filepath.Clean("/"+h.Name))
122 switch h.Typeflag {
123 case tar.TypeDir:
124 if err := os.MkdirAll(target, 0o755); err != nil {
125 return err
126 }
127 case tar.TypeSymlink:
128 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
129 return err
130 }
131 if err := os.Symlink(h.Linkname, target); err != nil {
132 return err
133 }
134 case tar.TypeReg:
135 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
136 return err
137 }
138 f, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(h.Mode)&0o777)
139 if err != nil {
140 return err
141 }
142 if _, err := io.Copy(f, tr); err != nil {
143 f.Close()
144 return err
145 }
146 if err := f.Close(); err != nil {
147 return err
148 }
149 default:
150 return fmt.Errorf("git archive: unsupported entry %s", h.Name)
151 }
152 }
153 if err := cmd.Wait(); err != nil {
154 return fmt.Errorf("git archive: %w: %s", err, strings.TrimSpace(errb.String()))
155 }
156 return nil
157}
158
159// writeBlob stores content as a loose object and returns its id.
160func writeBlob(repo string, content []byte) (string, error) {
161 out, err := gitInput(repo, content, "hash-object", "-w", "--stdin")
162 return strings.TrimSpace(out), err
163}
164
165// mkTree builds a tree object from named blobs and subtrees. Deterministic
166// by construction: the attestation ref's value is a function of the
167// statements under it and nothing else, so re-running attest over an
168// unchanged tree produces the identical ref and a create-only push stays
169// idempotent.
170func mkTree(repo string, blobs, trees map[string]string) (string, error) {
171 var lines []string
172 for name, oid := range blobs {
173 lines = append(lines, fmt.Sprintf("100644 blob %s\t%s", oid, name))
174 }
175 for name, oid := range trees {
176 lines = append(lines, fmt.Sprintf("040000 tree %s\t%s", oid, name))
177 }
178 sort.Strings(lines)
179 out, err := gitInput(repo, []byte(strings.Join(lines, "\n")+"\n"), "mktree")
180 return strings.TrimSpace(out), err
181}