gunk-dev/the-valley

bundle_test.go

sourceabcc65061e04main's published tip history
11.9 KiB
1package export_test
2
3import (
4 "bytes"
5 "context"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "syscall"
12 "testing"
13
14 "the-valley/webui/export"
15)
16
17// git runs git for a test, with none of the caller's GIT_ variables and no
18// system or global configuration, and returns its trimmed output.
19func git(t *testing.T, dir string, stdin []byte, args ...string) string {
20 t.Helper()
21 if dir != "" {
22 args = append([]string{"-C", dir}, args...)
23 }
24 cmd := exec.Command("git", args...)
25 for _, kv := range os.Environ() {
26 if !strings.HasPrefix(kv, "GIT_") {
27 cmd.Env = append(cmd.Env, kv)
28 }
29 }
30 cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
31 "GIT_AUTHOR_NAME=Example Author", "GIT_AUTHOR_EMAIL=author@example.org",
32 "GIT_COMMITTER_NAME=Example Author", "GIT_COMMITTER_EMAIL=author@example.org",
33 "GIT_AUTHOR_DATE=2026-10-01T09:00:00Z", "GIT_COMMITTER_DATE=2026-10-01T09:00:00Z")
34 if stdin != nil {
35 cmd.Stdin = bytes.NewReader(stdin)
36 }
37 var stderr bytes.Buffer
38 cmd.Stderr = &stderr
39 out, err := cmd.Output()
40 if err != nil {
41 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String())
42 }
43 return strings.TrimSpace(string(out))
44}
45
46// source is a bare repository whose main has two commits, first and tip,
47// and whose side branch has a commit main does not reach.
48type source struct {
49 repo, first, tip, side string
50}
51
52func newSource(t *testing.T, format string) source {
53 t.Helper()
54 repo := filepath.Join(t.TempDir(), "source.git")
55 git(t, "", nil, "init", "--quiet", "--bare", "--initial-branch=main", "--object-format="+format, repo)
56 commit := func(parent, file, content string) string {
57 blob := git(t, repo, []byte(content), "hash-object", "-w", "--stdin")
58 tree := git(t, repo, []byte(fmt.Sprintf("100644 blob %s\t%s\n", blob, file)), "mktree")
59 args := []string{"commit-tree", tree, "-m", file}
60 if parent != "" {
61 args = append(args, "-p", parent)
62 }
63 return git(t, repo, nil, args...)
64 }
65 s := source{repo: repo}
66 s.first = commit("", "README.md", "# source\n")
67 s.tip = commit(s.first, "main.go", "package main\n")
68 s.side = commit(s.first, "side.txt", "not on main\n")
69 git(t, repo, nil, "update-ref", "refs/heads/main", s.tip)
70 git(t, repo, nil, "update-ref", "refs/heads/side", s.side)
71 return s
72}
73
74func (s source) bundle(t *testing.T, args ...string) string {
75 t.Helper()
76 path := filepath.Join(t.TempDir(), "b.bundle")
77 git(t, s.repo, nil, append([]string{"bundle", "create", "--quiet", path}, args...)...)
78 return path
79}
80
81// A full bundle of main at the declared tip is accepted into a fresh bare
82// repository holding main alone.
83func TestAcceptBundle(t *testing.T) {
84 ctx := context.Background()
85 for _, format := range []string{"sha1", "sha256"} {
86 t.Run(format, func(t *testing.T) {
87 s := newSource(t, format)
88 repo := filepath.Join(t.TempDir(), "app.git")
89 if err := export.AcceptBundle(ctx, s.bundle(t, "main"), repo, s.tip); err != nil {
90 t.Fatal(err)
91 }
92 if refs := git(t, repo, nil, "for-each-ref", "--format=%(refname) %(objectname)"); refs != "refs/heads/main "+s.tip {
93 t.Errorf("the repository holds %q", refs)
94 }
95 if got := git(t, repo, nil, "rev-parse", "--show-object-format"); got != format {
96 t.Errorf("the repository is %s", got)
97 }
98 })
99 }
100}
101
102// A bundle and a repository named relative to the working directory are
103// read and written there.
104func TestAcceptBundleTakesRelativePaths(t *testing.T) {
105 s := newSource(t, "sha1")
106 bundle := s.bundle(t, "main")
107 t.Chdir(filepath.Dir(bundle))
108 if err := export.AcceptBundle(context.Background(), filepath.Base(bundle), "app.git", s.tip); err != nil {
109 t.Fatal(err)
110 }
111 if _, err := os.Stat(filepath.Join(filepath.Dir(bundle), "app.git", "HEAD")); err != nil {
112 t.Error(err)
113 }
114}
115
116// What the acceptance procedure refuses, each leaving no repository.
117func TestAcceptBundleRefuses(t *testing.T) {
118 ctx := context.Background()
119 s := newSource(t, "sha1")
120 good := s.bundle(t, "main")
121 corrupt := func() string {
122 data, err := os.ReadFile(good)
123 if err != nil {
124 t.Fatal(err)
125 }
126 // Past the header, in the pack: flip one byte of the last object.
127 data[len(data)-30] ^= 0xff
128 path := filepath.Join(t.TempDir(), "corrupt.bundle")
129 if err := os.WriteFile(path, data, 0o644); err != nil {
130 t.Fatal(err)
131 }
132 return path
133 }
134 cases := []struct {
135 name, bundle, tip, says string
136 }{
137 {"a wrong tip", good, s.first, "the manifest declares"},
138 {"prerequisites", s.bundle(t, "main~1..main"), s.tip, "prerequisite"},
139 {"an extra ref", s.bundle(t, "main", "side"), s.tip, "2 refs"},
140 {"another ref than main", s.bundle(t, "side"), s.side, "refs/heads/side"},
141 {"a corrupt pack", corrupt(), s.tip, "git fetch"},
142 {"a malformed commit", malformedBundle(t), "", "fsck"},
143 {"no bundle", filepath.Join(t.TempDir(), "missing.bundle"), s.tip, "no such file"},
144 }
145 for _, c := range cases {
146 t.Run(c.name, func(t *testing.T) {
147 tip := c.tip
148 if tip == "" {
149 tip = bundleTip(t, c.bundle)
150 }
151 repo := filepath.Join(t.TempDir(), "app.git")
152 err := export.AcceptBundle(ctx, c.bundle, repo, tip)
153 if err == nil || !strings.Contains(err.Error(), c.says) {
154 t.Fatalf("AcceptBundle gave %v, want an error saying %q", err, c.says)
155 }
156 if c.name != "no bundle" {
157 wantCode(t, err, export.CodeBadBundle)
158 }
159 if _, err := os.Lstat(repo); !os.IsNotExist(err) {
160 t.Errorf("the refusal left %s behind", repo)
161 }
162 })
163 }
164 t.Run("a repository that exists", func(t *testing.T) {
165 repo := t.TempDir()
166 if err := export.AcceptBundle(ctx, good, repo, s.tip); err == nil {
167 t.Fatal("AcceptBundle fetched into a directory that existed")
168 }
169 if _, err := os.Lstat(repo); err != nil {
170 t.Errorf("the refusal removed the directory that was there: %v", err)
171 }
172 })
173}
174
175// A bundle's header is read through a 64 KiB bound on the file. A header
176// with no line end, a thousand times longer, is refused once the bound
177// is reached: the receiver reads about 64 KiB of it, not the whole of it.
178// The bundle is a named pipe, so the test counts what was read.
179func TestAcceptBundleBoundsTheHeader(t *testing.T) {
180 path := filepath.Join(t.TempDir(), "endless.bundle")
181 if err := syscall.Mkfifo(path, 0o600); err != nil {
182 t.Fatal(err)
183 }
184 const offered = 64 << 20
185 taken := make(chan int64, 1)
186 go func() {
187 w, err := os.OpenFile(path, os.O_WRONLY, 0)
188 if err != nil {
189 taken <- -1
190 return
191 }
192 defer w.Close()
193 n, _ := w.Write([]byte("# v2 git bundle\n"))
194 total := int64(n)
195 chunk := bytes.Repeat([]byte("a"), 32<<10)
196 for total < offered {
197 n, err := w.Write(chunk)
198 total += int64(n)
199 if err != nil {
200 break // the receiver closed the bundle
201 }
202 }
203 taken <- total
204 }()
205 repo := filepath.Join(t.TempDir(), "app.git")
206 err := export.AcceptBundle(context.Background(), path, repo, strings.Repeat("1", 40))
207 if err == nil || !strings.Contains(err.Error(), "longer than") {
208 t.Fatalf("AcceptBundle gave %v, want a refusal of the header's length", err)
209 }
210 wantCode(t, err, export.CodeBadBundle)
211 // What the pipe holds unread comes on top of what was read.
212 if n := <-taken; n < 0 || n > 4<<20 {
213 t.Errorf("the receiver took %d bytes of a header with no end, want about 64 KiB", n)
214 }
215 if _, err := os.Lstat(repo); !os.IsNotExist(err) {
216 t.Errorf("the refusal left %s behind", repo)
217 }
218}
219
220// bundleTip is the one ref a bundle's header names.
221func bundleTip(t *testing.T, path string) string {
222 t.Helper()
223 return strings.Fields(git(t, "", nil, "bundle", "list-heads", path))[0]
224}
225
226// malformedBundle is a bundle of a main whose tip is a commit fsck
227// refuses: its author has no email and no date.
228func malformedBundle(t *testing.T) string {
229 t.Helper()
230 repo := filepath.Join(t.TempDir(), "bad.git")
231 git(t, "", nil, "init", "--quiet", "--bare", "--initial-branch=main", repo)
232 tree := git(t, repo, nil, "mktree")
233 bad := git(t, repo, []byte("tree "+tree+"\nauthor nobody\ncommitter nobody\n\nmalformed\n"),
234 "hash-object", "-t", "commit", "--literally", "-w", "--stdin")
235 git(t, repo, nil, "update-ref", "refs/heads/main", bad)
236 path := filepath.Join(t.TempDir(), "bad.bundle")
237 git(t, repo, nil, "bundle", "create", "--quiet", path, "main")
238 return path
239}
240
241// unreachableBundle is a bundle of main whose pack also carries a commit
242// main does not reach, as a hostile publisher could write one.
243func unreachableBundle(t *testing.T, s source) string {
244 t.Helper()
245 objects := git(t, s.repo, nil, "rev-list", "--objects", "main", "side")
246 pack := packObjects(t, s.repo, objects)
247 header := "# v2 git bundle\n" + s.tip + " refs/heads/main\n\n"
248 path := filepath.Join(t.TempDir(), "unreachable.bundle")
249 if err := os.WriteFile(path, append([]byte(header), pack...), 0o644); err != nil {
250 t.Fatal(err)
251 }
252 return path
253}
254
255func packObjects(t *testing.T, repo, objects string) []byte {
256 t.Helper()
257 cmd := exec.Command("git", "-C", repo, "pack-objects", "--stdout", "--quiet")
258 cmd.Env = append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null")
259 cmd.Stdin = strings.NewReader(objects + "\n")
260 out, err := cmd.Output()
261 if err != nil {
262 t.Fatal(err)
263 }
264 return out
265}
266
267// Reachable admits only commits main's tip reaches. A bundle can carry
268// other objects; they are in the repository and never reachable.
269func TestReachable(t *testing.T) {
270 ctx := context.Background()
271 s := newSource(t, "sha1")
272 repo := filepath.Join(t.TempDir(), "app.git")
273 if err := export.AcceptBundle(ctx, unreachableBundle(t, s), repo, s.tip); err != nil {
274 t.Fatal(err)
275 }
276 if got := git(t, repo, nil, "cat-file", "-t", s.side); got != "commit" {
277 t.Fatalf("the unreachable commit is not in the repository: %q", got)
278 }
279 tree := git(t, repo, nil, "rev-parse", s.tip+"^{tree}")
280 for _, c := range []struct {
281 name, commit string
282 want bool
283 }{
284 {"the tip", s.tip, true},
285 {"its parent", s.first, true},
286 {"a commit in the bundle that main does not reach", s.side, false},
287 {"a tree", tree, false},
288 {"an object the repository does not hold", strings.Repeat("1", 40), false},
289 {"an abbreviated ID", s.tip[:12], false},
290 {"a revision expression", s.tip + "~1", false},
291 {"an option", "--all", false},
292 } {
293 t.Run(c.name, func(t *testing.T) {
294 got, err := export.Reachable(ctx, repo, s.tip, c.commit)
295 if err != nil || got != c.want {
296 t.Errorf("Reachable gave %v, %v; want %v", got, err, c.want)
297 }
298 })
299 }
300 if _, err := export.Reachable(ctx, repo, "main", s.tip); err == nil {
301 t.Error("Reachable took a tip that is no object ID")
302 }
303}
304
305// A carried repository is fetched and checked as a bundle is, and holds
306// main alone.
307func TestCarryRepo(t *testing.T) {
308 ctx := context.Background()
309 s := newSource(t, "sha1")
310 held := filepath.Join(t.TempDir(), "held.git")
311 if err := export.AcceptBundle(ctx, s.bundle(t, "main"), held, s.tip); err != nil {
312 t.Fatal(err)
313 }
314 carried := filepath.Join(t.TempDir(), "carried.git")
315 if err := export.CarryRepo(ctx, held, carried, s.tip); err != nil {
316 t.Fatal(err)
317 }
318 if refs := git(t, carried, nil, "for-each-ref", "--format=%(refname) %(objectname)"); refs != "refs/heads/main "+s.tip {
319 t.Errorf("the carried repository holds %q", refs)
320 }
321 wrong := filepath.Join(t.TempDir(), "wrong.git")
322 if err := export.CarryRepo(ctx, held, wrong, s.first); err == nil {
323 t.Error("CarryRepo carried a repository at another tip")
324 }
325 if _, err := os.Lstat(wrong); !os.IsNotExist(err) {
326 t.Error("the refusal left a repository behind")
327 }
328}
329
330// Git reads the repository it is given and no other: a directory that is
331// not a repository fails, even when a repository holds it.
332func TestGit(t *testing.T) {
333 ctx := context.Background()
334 s := newSource(t, "sha1")
335 repo := filepath.Join(t.TempDir(), "app.git")
336 if err := export.AcceptBundle(ctx, s.bundle(t, "main"), repo, s.tip); err != nil {
337 t.Fatal(err)
338 }
339 out, err := export.Git(ctx, repo, "rev-parse", export.MainRef)
340 if err != nil || strings.TrimSpace(string(out)) != s.tip {
341 t.Errorf("Git read main as %q, %v; want %s", out, err, s.tip)
342 }
343 if out, err := export.Git(ctx, filepath.Join(repo, "refs"), "rev-parse", export.MainRef); err == nil {
344 t.Errorf("Git read %q from a directory inside the repository", out)
345 }
346}