gunk-dev/the-valley

bundle.go

source0d53dda2bd02main's published tip history
14.0 KiB
1package export
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strings"
14)
15
16// GitProgram is the git this package runs: git on PATH, unless a build
17// fixes it to an absolute path with
18// -ldflags "-X the-valley/web/export.GitProgram=<path>".
19var GitProgram = "git"
20
21// MainRef is the one ref a bundle carries, and the one a generation's
22// repository holds.
23const MainRef = "refs/heads/main"
24
25// maxBundleHeader is the most bytes of a bundle's header read: its version
26// line, capabilities, prerequisites and refs.
27const maxBundleHeader = 64 << 10
28
29// AcceptBundle checks the bundle at path and fetches it into repo, a fresh
30// bare repository it creates, in this order:
31//
32// 1. the bundle's header has no prerequisite, so the bundle is complete;
33// 2. it carries exactly one ref, refs/heads/main, at tip;
34// 3. git fetches it into the fresh repository with the explicit refspec
35// refs/heads/main:refs/heads/main, no tags, and
36// transfer.fsckObjects=true, so every object is checked as it is
37// indexed;
38// 4. the repository then holds refs/heads/main at tip, and no other ref;
39// 5. git writes the repository's commit-graph, so a reader walks main's
40// history, as merge-base and log do, without parsing each commit.
41//
42// A refused bundle leaves no repository behind. Every refusal is an
43// *Error with CodeBadBundle.
44func AcceptBundle(ctx context.Context, path, repo, tip string) error {
45 format, err := checkBundleHeader(path, tip)
46 if err != nil {
47 return err
48 }
49 // git fetches in repo, so the bundle is named from the root.
50 abs, err := filepath.Abs(path)
51 if err != nil {
52 return err
53 }
54 return fetchMain(ctx, abs, repo, tip, format)
55}
56
57// CarryRepo fetches main from from, a repository the receiver holds at tip,
58// into repo, a fresh bare repository, by the same fetch and checks a
59// bundle is fetched by. A new generation carries a project's repository
60// this way when its source tip has not moved, so the project's bundle need
61// not be sent again.
62func CarryRepo(ctx context.Context, from, repo, tip string) error {
63 format := "sha1"
64 if len(tip) == 64 {
65 format = "sha256"
66 }
67 abs, err := filepath.Abs(from)
68 if err != nil {
69 return err
70 }
71 return fetchMain(ctx, abs, repo, tip, format)
72}
73
74// checkBundleHeader reads the bundle's header, as gitformat-bundle defines
75// it, and holds it to steps 1 and 2. It returns the object format.
76func checkBundleHeader(path, tip string) (format string, err error) {
77 bad := func(format string, args ...any) error { return refuse(CodeBadBundle, format, args...) }
78 f, err := os.Open(path)
79 if err != nil {
80 return "", err
81 }
82 defer f.Close()
83 // The bound is on the file, not on the lines read from it, so a line
84 // with no end is never buffered past it.
85 r := bufio.NewReader(io.LimitReader(f, maxBundleHeader+1))
86 read := 0
87 line := func() (string, error) {
88 s, err := r.ReadString('\n')
89 read += len(s)
90 if read > maxBundleHeader {
91 return "", bad("the bundle's header is longer than %d bytes", maxBundleHeader)
92 }
93 if err != nil {
94 return "", bad("the bundle's header ends before its blank line")
95 }
96 return strings.TrimSuffix(s, "\n"), nil
97 }
98 version, err := line()
99 if err != nil {
100 return "", err
101 }
102 if version != "# v2 git bundle" && version != "# v3 git bundle" {
103 return "", bad("the bundle opens with %q, which is not a v2 or v3 bundle", version)
104 }
105 format = "sha1"
106 var refs []string
107 for {
108 s, err := line()
109 if err != nil {
110 return "", err
111 }
112 switch {
113 case s == "":
114 if len(refs) != 1 {
115 return "", bad("the bundle carries %d refs; it carries %s alone", len(refs), MainRef)
116 }
117 oid, name, _ := strings.Cut(refs[0], " ")
118 if name != MainRef {
119 return "", bad("the bundle carries %s; it carries %s alone", name, MainRef)
120 }
121 if oid != tip {
122 return "", bad("the bundle carries %s at %s; the manifest declares %s", MainRef, oid, tip)
123 }
124 if want := map[string]int{"sha1": 40, "sha256": 64}[format]; len(tip) != want {
125 return "", bad("the bundle is %s, and the tip %s is not a %s object ID", format, tip, format)
126 }
127 return format, nil
128 case strings.HasPrefix(s, "@"):
129 if version != "# v3 git bundle" {
130 return "", bad("a v2 bundle has no capability line, and this one has %q", s)
131 }
132 switch s {
133 case "@object-format=sha1":
134 format = "sha1"
135 case "@object-format=sha256":
136 format = "sha256"
137 default:
138 return "", bad("the bundle has the capability %q; a bundle is a full, unfiltered one", s)
139 }
140 case strings.HasPrefix(s, "-"):
141 return "", bad("the bundle has a prerequisite, %q; a bundle carries main's whole history", strings.TrimPrefix(s, "-"))
142 default:
143 oid, name, ok := strings.Cut(s, " ")
144 if !ok || !ValidObjectID(oid) || name == "" {
145 return "", bad("the bundle's header holds %q, which is not a ref line", s)
146 }
147 refs = append(refs, s)
148 }
149 }
150}
151
152// fetchMain makes repo a fresh bare repository holding refs/heads/main at
153// tip, fetched from source, and nothing else but main's commit-graph. It
154// removes repo again on any failure.
155func fetchMain(ctx context.Context, source, repo, tip, format string) (err error) {
156 if !ValidObjectID(tip) {
157 return refuse(CodeBadBundle, "%q is not an object ID", tip)
158 }
159 if _, err := os.Lstat(repo); !errors.Is(err, os.ErrNotExist) {
160 return fmt.Errorf("%s is not a fresh repository: it exists already", repo)
161 }
162 defer func() {
163 if err != nil {
164 os.RemoveAll(repo)
165 }
166 }()
167 if _, err := git(ctx, "", "init", "--quiet", "--bare", "--template=", "--initial-branch=main",
168 "--object-format="+format, repo); err != nil {
169 return err
170 }
171 if _, err := git(ctx, repo, "-c", "transfer.fsckObjects=true", "-c", "core.fsync=all",
172 "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--end-of-options",
173 source, MainRef+":"+MainRef); err != nil {
174 return refuse(CodeBadBundle, "%v", err)
175 }
176 refs, err := git(ctx, repo, "for-each-ref", "--format=%(objectname) %(refname)")
177 if err != nil {
178 return err
179 }
180 if got, want := strings.TrimSuffix(string(refs), "\n"), tip+" "+MainRef; got != want {
181 return refuse(CodeBadBundle, "the fetched repository holds %q, not %q", got, want)
182 }
183 _, err = git(ctx, repo, "-c", "core.fsync=all", "commit-graph", "write", "--reachable", "--no-progress")
184 return err
185}
186
187// Reachable reports whether each of commits is a commit that tip reaches
188// in repo. Browsing serves a commit only when it is: a bundle can carry
189// objects main does not reach, and those are never shown. An argument
190// that is not an object ID, an object repo does not hold, and an object
191// that is not a commit are all unreachable. So is an object ID of another
192// length than tip's: git reads 40 hex digits in a SHA-256 repository as
193// an abbreviation, and a commit is named by its full ID alone. Reachable
194// fails when it is given no commit.
195func Reachable(ctx context.Context, repo, tip string, commits ...string) (bool, error) {
196 if !ValidObjectID(tip) {
197 return false, fmt.Errorf("%q is not an object ID", tip)
198 }
199 if len(commits) == 0 {
200 return false, errors.New("no commit to check")
201 }
202 var stdin bytes.Buffer
203 for _, commit := range commits {
204 if !ValidObjectID(commit) || len(commit) != len(tip) {
205 return false, nil
206 }
207 stdin.WriteString(commit + "\n")
208 }
209 // --git-dir, as Git does, so git neither looks above repo nor holds
210 // a repository another user owns to safe.directory.
211 var out []byte
212 err := run(command(ctx, "", "--git-dir="+repo, "cat-file", "--batch-check=%(objecttype)"), "cat-file",
213 stdin.Bytes(), maxOutput, func(r io.Reader) (err error) {
214 out, err = io.ReadAll(r)
215 return err
216 })
217 if err != nil {
218 return false, err
219 }
220 types := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n")
221 if len(types) != len(commits) {
222 return false, fmt.Errorf("git cat-file gave %d types for %d objects", len(types), len(commits))
223 }
224 for _, t := range types {
225 if t != "commit" {
226 return false, nil
227 }
228 }
229 for _, commit := range commits {
230 cmd := command(ctx, "", "--git-dir="+repo, "merge-base", "--is-ancestor", commit, tip)
231 stderr := &head{max: maxStderr}
232 cmd.Stderr = stderr
233 err = cmd.Run()
234 var exit *exec.ExitError
235 switch {
236 case err == nil:
237 continue
238 case errors.As(err, &exit) && exit.ExitCode() == 1:
239 return false, nil
240 }
241 return false, fmt.Errorf("git merge-base: %w: %s", err, strings.TrimSpace(stderr.String()))
242 }
243 return true, nil
244}
245
246// ErrOutputLimit is the error of a git command that writes more output
247// than its caller set as the limit. git is stopped, and waited for, before
248// the error is returned.
249var ErrOutputLimit = errors.New("git wrote more than its output limit")
250
251// The bounds on what this package keeps of a git command's output.
252const (
253 // maxStderr is the most of git's standard error kept for an error's
254 // message. The rest is read and dropped.
255 maxStderr = 16 << 10
256 // maxOutput is the most standard output this package reads from a
257 // git command it runs for itself: a ref listing or an object's type.
258 maxOutput = 64 << 10
259)
260
261// Git runs git with args on the bare repository at repo and returns what
262// git prints, which may be at most limit bytes. It runs git the way this
263// package runs every git: replacement refs off, none of the caller's GIT_
264// variables, and no system or global configuration. --git-dir names the
265// repository, so git never reads a repository it finds above repo, and
266// reads one another user owns without holding it to safe.directory. When
267// git prints more than limit bytes, Git stops it and fails with
268// ErrOutputLimit. A server reads a generation's repositories with it, and
269// gives it object IDs it has checked, never a name a reader typed.
270func Git(ctx context.Context, repo string, limit int64, args ...string) ([]byte, error) {
271 var out []byte
272 err := GitStream(ctx, repo, limit, func(r io.Reader) (err error) {
273 out, err = io.ReadAll(r)
274 return err
275 }, args...)
276 return out, err
277}
278
279// GitStream runs git as Git does, and calls read with git's standard
280// output as git prints it. read may read at most limit bytes: a read past
281// them fails with ErrOutputLimit. read may also return before the output
282// ends, once it has what it needs. Once read returns, GitStream stops git
283// if it is still running, and waits for it to exit, so no git outlives the
284// call. GitStream returns read's error. When read succeeds, it returns
285// git's own failure only if read reached the end of the output: a git
286// stopped early is not held to how it exited.
287func GitStream(ctx context.Context, repo string, limit int64, read func(io.Reader) error, args ...string) error {
288 if len(args) == 0 {
289 return errors.New("git needs a command")
290 }
291 return run(command(ctx, "", append([]string{"--git-dir=" + repo}, args...)...), args[0], nil, limit, read)
292}
293
294// run starts cmd, with stdin as its standard input when it is not nil,
295// and gives read cmd's standard output, at most limit bytes of it. It
296// keeps the first maxStderr bytes of cmd's standard error for its error,
297// which names git's verb.
298func run(cmd *exec.Cmd, verb string, stdin []byte, limit int64, read func(io.Reader) error) error {
299 if stdin != nil {
300 cmd.Stdin = bytes.NewReader(stdin)
301 }
302 stderr := &head{max: maxStderr}
303 cmd.Stderr = stderr
304 pipe, err := cmd.StdoutPipe()
305 if err != nil {
306 return fmt.Errorf("git %s: %w", verb, err)
307 }
308 if err := cmd.Start(); err != nil {
309 return fmt.Errorf("git %s: %w", verb, err)
310 }
311 out := &bounded{r: pipe, n: limit, err: fmt.Errorf("git %s: %w", verb, ErrOutputLimit)}
312 readErr := read(out)
313 if readErr != nil || !out.eof {
314 // git may be blocked writing to a pipe nobody reads any more.
315 cmd.Process.Kill()
316 }
317 err = cmd.Wait()
318 switch {
319 case readErr != nil:
320 return readErr
321 case !out.eof:
322 return nil
323 case err != nil:
324 return fmt.Errorf("git %s: %w: %s", verb, err, strings.TrimSpace(stderr.String()))
325 }
326 return nil
327}
328
329// bounded reads r, at most n bytes of it. A read once n bytes are read
330// fails with err if r holds more, and is the end of the output if it does
331// not. eof is set once r's end is read.
332type bounded struct {
333 r io.Reader
334 n int64
335 err error
336 over bool
337 eof bool
338}
339
340func (b *bounded) Read(p []byte) (int, error) {
341 switch {
342 case b.over:
343 return 0, b.err
344 case b.eof:
345 return 0, io.EOF
346 case len(p) == 0:
347 return 0, nil
348 case b.n <= 0:
349 // One byte more is past the limit, and the end is not.
350 var one [1]byte
351 n, err := b.r.Read(one[:])
352 if n > 0 {
353 b.over = true
354 return 0, b.err
355 }
356 b.eof = err == io.EOF
357 return 0, err
358 }
359 if int64(len(p)) > b.n {
360 p = p[:b.n]
361 }
362 n, err := b.r.Read(p)
363 b.n -= int64(n)
364 b.eof = err == io.EOF
365 return n, err
366}
367
368// head keeps the first max bytes written to it and drops the rest, so a
369// command's standard error is read to its end and never held whole.
370type head struct {
371 max int
372 b bytes.Buffer
373}
374
375func (h *head) Write(p []byte) (int, error) {
376 if room := h.max - h.b.Len(); room > 0 {
377 h.b.Write(p[:min(len(p), room)])
378 }
379 return len(p), nil
380}
381
382func (h *head) String() string { return h.b.String() }
383
384// command is git, run in dir unless it is "", with replacement refs off
385// and an environment that holds none of the caller's GIT_ variables and
386// reads no system or global configuration.
387func command(ctx context.Context, dir string, args ...string) *exec.Cmd {
388 if dir != "" {
389 args = append([]string{"-C", dir}, args...)
390 }
391 cmd := exec.CommandContext(ctx, GitProgram, append([]string{"--no-replace-objects"}, args...)...)
392 cmd.Env = gitEnvironment(os.Environ())
393 return cmd
394}
395
396func gitEnvironment(inherited []string) []string {
397 var env []string
398 for _, kv := range inherited {
399 if !strings.HasPrefix(kv, "GIT_") {
400 env = append(env, kv)
401 }
402 }
403 return append(env,
404 "GIT_CONFIG_NOSYSTEM=1",
405 "GIT_CONFIG_GLOBAL=/dev/null",
406 "GIT_NO_REPLACE_OBJECTS=1",
407 "GIT_ATTR_NOSYSTEM=1",
408 "GIT_TERMINAL_PROMPT=0",
409 )
410}
411
412func git(ctx context.Context, dir string, args ...string) ([]byte, error) {
413 return gitInput(ctx, dir, nil, args...)
414}
415
416func gitInput(ctx context.Context, dir string, stdin []byte, args ...string) ([]byte, error) {
417 verb := args[0]
418 for i := 0; verb == "-c" && i+2 < len(args); i += 2 {
419 verb = args[i+2]
420 }
421 var out []byte
422 err := run(command(ctx, dir, args...), verb, stdin, maxOutput, func(r io.Reader) (err error) {
423 out, err = io.ReadAll(r)
424 return err
425 })
426 return out, err
427}