gunk-dev/the-valley

bundle.go

source876e6ddf614dmain's published tip history
13.5 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/webui/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 commit is a commit that tip reaches in repo.
188// Browsing serves a commit only when it is: a bundle can carry objects
189// main does not reach, and those are never shown. An argument that is not
190// an object ID, an object repo does not hold, and an object that is not a
191// commit are all unreachable. So is an object ID of another length than
192// tip's: git reads 40 hex digits in a SHA-256 repository as an
193// abbreviation, and a commit is named by its full ID alone.
194func Reachable(ctx context.Context, repo, tip, commit string) (bool, error) {
195 if !ValidObjectID(tip) {
196 return false, fmt.Errorf("%q is not an object ID", tip)
197 }
198 if !ValidObjectID(commit) || len(commit) != len(tip) {
199 return false, nil
200 }
201 // --git-dir, as Git does, so git neither looks above repo nor holds
202 // a repository another user owns to safe.directory.
203 var out []byte
204 err := run(command(ctx, "", "--git-dir="+repo, "cat-file", "--batch-check=%(objecttype)"), "cat-file",
205 []byte(commit+"\n"), maxOutput, func(r io.Reader) (err error) {
206 out, err = io.ReadAll(r)
207 return err
208 })
209 if err != nil {
210 return false, err
211 }
212 if strings.TrimSpace(string(out)) != "commit" {
213 return false, nil
214 }
215 cmd := command(ctx, "", "--git-dir="+repo, "merge-base", "--is-ancestor", commit, tip)
216 stderr := &head{max: maxStderr}
217 cmd.Stderr = stderr
218 err = cmd.Run()
219 var exit *exec.ExitError
220 switch {
221 case err == nil:
222 return true, nil
223 case errors.As(err, &exit) && exit.ExitCode() == 1:
224 return false, nil
225 }
226 return false, fmt.Errorf("git merge-base: %w: %s", err, strings.TrimSpace(stderr.String()))
227}
228
229// ErrOutputLimit is the error of a git command that writes more output
230// than its caller set as the limit. git is stopped, and waited for, before
231// the error is returned.
232var ErrOutputLimit = errors.New("git wrote more than its output limit")
233
234// The bounds on what this package keeps of a git command's output.
235const (
236 // maxStderr is the most of git's standard error kept for an error's
237 // message. The rest is read and dropped.
238 maxStderr = 16 << 10
239 // maxOutput is the most standard output this package reads from a
240 // git command it runs for itself: a ref listing or an object's type.
241 maxOutput = 64 << 10
242)
243
244// Git runs git with args on the bare repository at repo and returns what
245// git prints, which may be at most limit bytes. It runs git the way this
246// package runs every git: replacement refs off, none of the caller's GIT_
247// variables, and no system or global configuration. --git-dir names the
248// repository, so git never reads a repository it finds above repo, and
249// reads one another user owns without holding it to safe.directory. When
250// git prints more than limit bytes, Git stops it and fails with
251// ErrOutputLimit. A server reads a generation's repositories with it, and
252// gives it object IDs it has checked, never a name a reader typed.
253func Git(ctx context.Context, repo string, limit int64, args ...string) ([]byte, error) {
254 var out []byte
255 err := GitStream(ctx, repo, limit, func(r io.Reader) (err error) {
256 out, err = io.ReadAll(r)
257 return err
258 }, args...)
259 return out, err
260}
261
262// GitStream runs git as Git does, and calls read with git's standard
263// output as git prints it. read may read at most limit bytes: a read past
264// them fails with ErrOutputLimit. read may also return before the output
265// ends, once it has what it needs. Once read returns, GitStream stops git
266// if it is still running, and waits for it to exit, so no git outlives the
267// call. GitStream returns read's error. When read succeeds, it returns
268// git's own failure only if read reached the end of the output: a git
269// stopped early is not held to how it exited.
270func GitStream(ctx context.Context, repo string, limit int64, read func(io.Reader) error, args ...string) error {
271 if len(args) == 0 {
272 return errors.New("git needs a command")
273 }
274 return run(command(ctx, "", append([]string{"--git-dir=" + repo}, args...)...), args[0], nil, limit, read)
275}
276
277// run starts cmd, with stdin as its standard input when it is not nil,
278// and gives read cmd's standard output, at most limit bytes of it. It
279// keeps the first maxStderr bytes of cmd's standard error for its error,
280// which names git's verb.
281func run(cmd *exec.Cmd, verb string, stdin []byte, limit int64, read func(io.Reader) error) error {
282 if stdin != nil {
283 cmd.Stdin = bytes.NewReader(stdin)
284 }
285 stderr := &head{max: maxStderr}
286 cmd.Stderr = stderr
287 pipe, err := cmd.StdoutPipe()
288 if err != nil {
289 return fmt.Errorf("git %s: %w", verb, err)
290 }
291 if err := cmd.Start(); err != nil {
292 return fmt.Errorf("git %s: %w", verb, err)
293 }
294 out := &bounded{r: pipe, n: limit, err: fmt.Errorf("git %s: %w", verb, ErrOutputLimit)}
295 readErr := read(out)
296 if readErr != nil || !out.eof {
297 // git may be blocked writing to a pipe nobody reads any more.
298 cmd.Process.Kill()
299 }
300 err = cmd.Wait()
301 switch {
302 case readErr != nil:
303 return readErr
304 case !out.eof:
305 return nil
306 case err != nil:
307 return fmt.Errorf("git %s: %w: %s", verb, err, strings.TrimSpace(stderr.String()))
308 }
309 return nil
310}
311
312// bounded reads r, at most n bytes of it. A read once n bytes are read
313// fails with err if r holds more, and is the end of the output if it does
314// not. eof is set once r's end is read.
315type bounded struct {
316 r io.Reader
317 n int64
318 err error
319 over bool
320 eof bool
321}
322
323func (b *bounded) Read(p []byte) (int, error) {
324 switch {
325 case b.over:
326 return 0, b.err
327 case b.eof:
328 return 0, io.EOF
329 case len(p) == 0:
330 return 0, nil
331 case b.n <= 0:
332 // One byte more is past the limit, and the end is not.
333 var one [1]byte
334 n, err := b.r.Read(one[:])
335 if n > 0 {
336 b.over = true
337 return 0, b.err
338 }
339 b.eof = err == io.EOF
340 return 0, err
341 }
342 if int64(len(p)) > b.n {
343 p = p[:b.n]
344 }
345 n, err := b.r.Read(p)
346 b.n -= int64(n)
347 b.eof = err == io.EOF
348 return n, err
349}
350
351// head keeps the first max bytes written to it and drops the rest, so a
352// command's standard error is read to its end and never held whole.
353type head struct {
354 max int
355 b bytes.Buffer
356}
357
358func (h *head) Write(p []byte) (int, error) {
359 if room := h.max - h.b.Len(); room > 0 {
360 h.b.Write(p[:min(len(p), room)])
361 }
362 return len(p), nil
363}
364
365func (h *head) String() string { return h.b.String() }
366
367// command is git, run in dir unless it is "", with replacement refs off
368// and an environment that holds none of the caller's GIT_ variables and
369// reads no system or global configuration.
370func command(ctx context.Context, dir string, args ...string) *exec.Cmd {
371 if dir != "" {
372 args = append([]string{"-C", dir}, args...)
373 }
374 cmd := exec.CommandContext(ctx, GitProgram, append([]string{"--no-replace-objects"}, args...)...)
375 cmd.Env = gitEnvironment(os.Environ())
376 return cmd
377}
378
379func gitEnvironment(inherited []string) []string {
380 var env []string
381 for _, kv := range inherited {
382 if !strings.HasPrefix(kv, "GIT_") {
383 env = append(env, kv)
384 }
385 }
386 return append(env,
387 "GIT_CONFIG_NOSYSTEM=1",
388 "GIT_CONFIG_GLOBAL=/dev/null",
389 "GIT_NO_REPLACE_OBJECTS=1",
390 "GIT_ATTR_NOSYSTEM=1",
391 "GIT_TERMINAL_PROMPT=0",
392 )
393}
394
395func git(ctx context.Context, dir string, args ...string) ([]byte, error) {
396 return gitInput(ctx, dir, nil, args...)
397}
398
399func gitInput(ctx context.Context, dir string, stdin []byte, args ...string) ([]byte, error) {
400 verb := args[0]
401 for i := 0; verb == "-c" && i+2 < len(args); i += 2 {
402 verb = args[i+2]
403 }
404 var out []byte
405 err := run(command(ctx, dir, args...), verb, stdin, maxOutput, func(r io.Reader) (err error) {
406 out, err = io.ReadAll(r)
407 return err
408 })
409 return out, err
410}