gunk-dev/the-valley

bundle.go

sourcec736503d91ecmain's published tip history
8.1 KiB
1package export
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "fmt"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13)
14
15// GitProgram is the git this package runs: git on PATH, unless a build
16// fixes it to an absolute path with
17// -ldflags "-X the-valley/webui/export.GitProgram=<path>".
18var GitProgram = "git"
19
20// MainRef is the one ref a bundle carries, and the one a generation's
21// repository holds.
22const MainRef = "refs/heads/main"
23
24// maxBundleHeader is the most bytes of a bundle's header read: its version
25// line, capabilities, prerequisites and refs.
26const maxBundleHeader = 64 << 10
27
28// AcceptBundle checks the bundle at path and fetches it into repo, a fresh
29// bare repository it creates, in this order:
30//
31// 1. the bundle's header has no prerequisite, so the bundle is complete;
32// 2. it carries exactly one ref, refs/heads/main, at tip;
33// 3. git fetches it into the fresh repository with the explicit refspec
34// refs/heads/main:refs/heads/main, no tags, and
35// transfer.fsckObjects=true, so every object is checked as it is
36// indexed;
37// 4. the repository then holds refs/heads/main at tip, and no other ref.
38//
39// A refused bundle leaves no repository behind. Every refusal is an
40// *Error with CodeBadBundle.
41func AcceptBundle(ctx context.Context, path, repo, tip string) error {
42 format, err := checkBundleHeader(path, tip)
43 if err != nil {
44 return err
45 }
46 return fetchMain(ctx, path, repo, tip, format)
47}
48
49// CarryRepo fetches main from from, a repository the receiver holds at tip,
50// into repo, a fresh bare repository, by the same fetch and checks a
51// bundle is fetched by. A new generation carries a project's repository
52// this way when its source tip has not moved, so the project's bundle need
53// not be sent again.
54func CarryRepo(ctx context.Context, from, repo, tip string) error {
55 format := "sha1"
56 if len(tip) == 64 {
57 format = "sha256"
58 }
59 abs, err := filepath.Abs(from)
60 if err != nil {
61 return err
62 }
63 return fetchMain(ctx, abs, repo, tip, format)
64}
65
66// checkBundleHeader reads the bundle's header, as gitformat-bundle defines
67// it, and holds it to steps 1 and 2. It returns the object format.
68func checkBundleHeader(path, tip string) (format string, err error) {
69 bad := func(format string, args ...any) error { return refuse(CodeBadBundle, format, args...) }
70 f, err := os.Open(path)
71 if err != nil {
72 return "", err
73 }
74 defer f.Close()
75 r := bufio.NewReader(f)
76 read := 0
77 line := func() (string, error) {
78 s, err := r.ReadString('\n')
79 read += len(s)
80 if read > maxBundleHeader {
81 return "", bad("the bundle's header is longer than %d bytes", maxBundleHeader)
82 }
83 if err != nil {
84 return "", bad("the bundle's header ends before its blank line")
85 }
86 return strings.TrimSuffix(s, "\n"), nil
87 }
88 version, err := line()
89 if err != nil {
90 return "", err
91 }
92 if version != "# v2 git bundle" && version != "# v3 git bundle" {
93 return "", bad("the bundle opens with %q, which is not a v2 or v3 bundle", version)
94 }
95 format = "sha1"
96 var refs []string
97 for {
98 s, err := line()
99 if err != nil {
100 return "", err
101 }
102 switch {
103 case s == "":
104 if len(refs) != 1 {
105 return "", bad("the bundle carries %d refs; it carries %s alone", len(refs), MainRef)
106 }
107 oid, name, _ := strings.Cut(refs[0], " ")
108 if name != MainRef {
109 return "", bad("the bundle carries %s; it carries %s alone", name, MainRef)
110 }
111 if oid != tip {
112 return "", bad("the bundle carries %s at %s; the manifest declares %s", MainRef, oid, tip)
113 }
114 if want := map[string]int{"sha1": 40, "sha256": 64}[format]; len(tip) != want {
115 return "", bad("the bundle is %s, and the tip %s is not a %s object ID", format, tip, format)
116 }
117 return format, nil
118 case strings.HasPrefix(s, "@"):
119 if version != "# v3 git bundle" {
120 return "", bad("a v2 bundle has no capability line, and this one has %q", s)
121 }
122 switch s {
123 case "@object-format=sha1":
124 format = "sha1"
125 case "@object-format=sha256":
126 format = "sha256"
127 default:
128 return "", bad("the bundle has the capability %q; a bundle is a full, unfiltered one", s)
129 }
130 case strings.HasPrefix(s, "-"):
131 return "", bad("the bundle has a prerequisite, %q; a bundle carries main's whole history", strings.TrimPrefix(s, "-"))
132 default:
133 oid, name, ok := strings.Cut(s, " ")
134 if !ok || !ValidObjectID(oid) || name == "" {
135 return "", bad("the bundle's header holds %q, which is not a ref line", s)
136 }
137 refs = append(refs, s)
138 }
139 }
140}
141
142// fetchMain makes repo a fresh bare repository holding refs/heads/main at
143// tip, fetched from source, and nothing else. It removes repo again on
144// any failure.
145func fetchMain(ctx context.Context, source, repo, tip, format string) (err error) {
146 if !ValidObjectID(tip) {
147 return refuse(CodeBadBundle, "%q is not an object ID", tip)
148 }
149 if _, err := os.Lstat(repo); !errors.Is(err, os.ErrNotExist) {
150 return fmt.Errorf("%s is not a fresh repository: it exists already", repo)
151 }
152 defer func() {
153 if err != nil {
154 os.RemoveAll(repo)
155 }
156 }()
157 if _, err := git(ctx, "", "init", "--quiet", "--bare", "--template=", "--initial-branch=main",
158 "--object-format="+format, repo); err != nil {
159 return err
160 }
161 if _, err := git(ctx, repo, "-c", "transfer.fsckObjects=true", "-c", "core.fsync=all",
162 "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--end-of-options",
163 source, MainRef+":"+MainRef); err != nil {
164 return refuse(CodeBadBundle, "%v", err)
165 }
166 refs, err := git(ctx, repo, "for-each-ref", "--format=%(objectname) %(refname)")
167 if err != nil {
168 return err
169 }
170 if got, want := strings.TrimSuffix(string(refs), "\n"), tip+" "+MainRef; got != want {
171 return refuse(CodeBadBundle, "the fetched repository holds %q, not %q", got, want)
172 }
173 return nil
174}
175
176// Reachable reports whether commit is a commit that tip reaches in repo.
177// Browsing serves a commit only when it is: a bundle can carry objects
178// main does not reach, and those are never shown. An argument that is not
179// an object ID, an object repo does not hold, and an object that is not a
180// commit are all unreachable.
181func Reachable(ctx context.Context, repo, tip, commit string) (bool, error) {
182 if !ValidObjectID(tip) {
183 return false, fmt.Errorf("%q is not an object ID", tip)
184 }
185 if !ValidObjectID(commit) {
186 return false, nil
187 }
188 out, err := gitInput(ctx, repo, []byte(commit+"\n"), "cat-file", "--batch-check=%(objecttype)")
189 if err != nil {
190 return false, err
191 }
192 if strings.TrimSpace(string(out)) != "commit" {
193 return false, nil
194 }
195 cmd := command(ctx, repo, "merge-base", "--is-ancestor", commit, tip)
196 var stderr bytes.Buffer
197 cmd.Stderr = &stderr
198 err = cmd.Run()
199 var exit *exec.ExitError
200 switch {
201 case err == nil:
202 return true, nil
203 case errors.As(err, &exit) && exit.ExitCode() == 1:
204 return false, nil
205 }
206 return false, fmt.Errorf("git merge-base: %w: %s", err, strings.TrimSpace(stderr.String()))
207}
208
209// command is git, run in dir unless it is "", with replacement refs off
210// and an environment that holds none of the caller's GIT_ variables and
211// reads no system or global configuration.
212func command(ctx context.Context, dir string, args ...string) *exec.Cmd {
213 if dir != "" {
214 args = append([]string{"-C", dir}, args...)
215 }
216 cmd := exec.CommandContext(ctx, GitProgram, append([]string{"--no-replace-objects"}, args...)...)
217 cmd.Env = gitEnvironment(os.Environ())
218 return cmd
219}
220
221func gitEnvironment(inherited []string) []string {
222 var env []string
223 for _, kv := range inherited {
224 if !strings.HasPrefix(kv, "GIT_") {
225 env = append(env, kv)
226 }
227 }
228 return append(env,
229 "GIT_CONFIG_NOSYSTEM=1",
230 "GIT_CONFIG_GLOBAL=/dev/null",
231 "GIT_NO_REPLACE_OBJECTS=1",
232 "GIT_ATTR_NOSYSTEM=1",
233 "GIT_TERMINAL_PROMPT=0",
234 )
235}
236
237func git(ctx context.Context, dir string, args ...string) ([]byte, error) {
238 return gitInput(ctx, dir, nil, args...)
239}
240
241func gitInput(ctx context.Context, dir string, stdin []byte, args ...string) ([]byte, error) {
242 cmd := command(ctx, dir, args...)
243 if stdin != nil {
244 cmd.Stdin = bytes.NewReader(stdin)
245 }
246 var stderr bytes.Buffer
247 cmd.Stderr = &stderr
248 out, err := cmd.Output()
249 if err != nil {
250 verb := args[0]
251 for i := 0; verb == "-c" && i+2 < len(args); i += 2 {
252 verb = args[i+2]
253 }
254 return out, fmt.Errorf("git %s: %w: %s", verb, err, strings.TrimSpace(stderr.String()))
255 }
256 return out, nil
257}