gunk-dev/the-valley

bundle.go

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