gunk-dev/the-valley

bundle.go

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