| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/wire" |
| 14 | ) |
| 15 | |
| 16 | // creatingForge makes each repository it creates as an empty bare |
| 17 | // repository, the way the hub serves a new one. |
| 18 | type creatingForge struct { |
| 19 | pathForge |
| 20 | t *testing.T |
| 21 | failPush bool |
| 22 | } |
| 23 | |
| 24 | func (f *creatingForge) Create(ctx context.Context, repo string) error { |
| 25 | if err := f.countingForge.Create(ctx, repo); err != nil { |
| 26 | return err |
| 27 | } |
| 28 | gitT(f.t, filepath.Dir(f.path(repo)), "init", "-q", "--bare", "-b", "main", f.path(repo)) |
| 29 | if f.failPush { |
| 30 | // The hub refuses the first push: no main, and nothing recorded. |
| 31 | os.Chmod(filepath.Join(f.path(repo), "objects"), 0500) |
| 32 | f.t.Cleanup(func() { os.Chmod(filepath.Join(f.path(repo), "objects"), 0700) }) |
| 33 | } |
| 34 | return nil |
| 35 | } |
| 36 | |
| 37 | func startRig(t *testing.T) (*creatingForge, *Clones) { |
| 38 | t.Helper() |
| 39 | root := t.TempDir() |
| 40 | f := &creatingForge{pathForge: pathForge{root: filepath.Join(root, "forge")}, t: t} |
| 41 | os.MkdirAll(f.root, 0700) |
| 42 | os.MkdirAll(filepath.Join(root, "work"), 0700) |
| 43 | return f, &Clones{Root: filepath.Join(root, "work"), Git: "git", Forge: f} |
| 44 | } |
| 45 | |
| 46 | // A repository Equipo creates gets its default branch, main, at an empty |
| 47 | // first commit before any task branch exists. Task branches then start |
| 48 | // from main and every merge targets it. Without it, the hub made the |
| 49 | // first task branch pushed the default, and the next task's merge was |
| 50 | // asked to merge into that unrelated branch ("could not compute the |
| 51 | // merge"). |
| 52 | func TestStartDefaultMakesMainBeforeAnyTaskBranch(t *testing.T) { |
| 53 | f, c := startRig(t) |
| 54 | const repo = "amadan.net/oficina/site" |
| 55 | ctx := context.Background() |
| 56 | if err := f.Create(ctx, repo); err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | if _, err := c.DefaultBranch(ctx, repo); !errors.Is(err, ErrEmptyRepo) { |
| 60 | t.Fatalf("a new repository should start empty: %v", err) |
| 61 | } |
| 62 | if err := c.StartDefault(ctx, repo); err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | remote := f.path(repo) |
| 66 | if refs := gitT(t, remote, "for-each-ref", "--format=%(refname)"); refs != "refs/heads/main" { |
| 67 | t.Fatalf("refs after start: %q", refs) |
| 68 | } |
| 69 | main := gitT(t, remote, "rev-parse", "refs/heads/main") |
| 70 | if tree := gitT(t, remote, "rev-parse", main+"^{tree}"); tree != gitT(t, remote, "hash-object", "-t", "tree", "/dev/null") { |
| 71 | t.Fatalf("main's first commit is not empty: tree %s", tree) |
| 72 | } |
| 73 | if parents := gitT(t, remote, "rev-list", "--parents", "-n1", main); parents != main { |
| 74 | t.Fatalf("main's first commit has parents: %s", parents) |
| 75 | } |
| 76 | if def, err := c.DefaultBranch(ctx, repo); err != nil || def != "main" { |
| 77 | t.Fatalf("default after start: %q %v", def, err) |
| 78 | } |
| 79 | // Again (a resent create): nothing new. |
| 80 | if err := c.StartDefault(ctx, repo); err != nil { |
| 81 | t.Fatal(err) |
| 82 | } |
| 83 | if again := gitT(t, remote, "rev-parse", "refs/heads/main"); again != main { |
| 84 | t.Fatalf("main moved on a second start: %s -> %s", main, again) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | // A repository with any branch already, including one holding only task |
| 89 | // branches (the stuck ones), is left exactly as it is. |
| 90 | func TestStartDefaultLeavesBranchesAlone(t *testing.T) { |
| 91 | f, c := startRig(t) |
| 92 | const repo = "amadan.net/oficina/stuck" |
| 93 | ctx := context.Background() |
| 94 | if err := f.Create(ctx, repo); err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | seed := filepath.Join(t.TempDir(), "seed") |
| 98 | gitT(t, filepath.Dir(seed), "init", "-q", "-b", "equipo/tk1-demo", seed) |
| 99 | os.WriteFile(filepath.Join(seed, "index.html"), []byte("demo\n"), 0600) |
| 100 | gitT(t, seed, "add", "-A") |
| 101 | gitT(t, seed, "commit", "-q", "-m", "demo") |
| 102 | gitT(t, seed, "push", "-q", f.path(repo), "equipo/tk1-demo") |
| 103 | before := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)") |
| 104 | if err := c.StartDefault(ctx, repo); err != nil { |
| 105 | t.Fatal(err) |
| 106 | } |
| 107 | if after := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)"); after != before { |
| 108 | t.Fatalf("refs changed: %q -> %q", before, after) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | // create_project starts main as part of creating the repository; a |
| 113 | // failed start is not recorded as created, so the resent call (the |
| 114 | // repository exists by then) starts it. |
| 115 | func TestCreateProjectStartsMain(t *testing.T) { |
| 116 | state, err := OpenState(context.Background(), t.TempDir()) |
| 117 | if err != nil { |
| 118 | t.Fatal(err) |
| 119 | } |
| 120 | defer state.Close() |
| 121 | f, c := startRig(t) |
| 122 | f.failPush = true |
| 123 | b := &bridge{State: state, Forge: f, Clones: c, speaks: wire.ProtocolCurrent, trip: func(_ context.Context, call wire.ToolCall) wire.ToolResult { |
| 124 | var in struct{ Repo string } |
| 125 | _ = json.Unmarshal(call.Args, &in) |
| 126 | if call.Name == wire.ToolCreateProject { |
| 127 | return wire.ToolResult{Code: "create", Repo: in.Repo} |
| 128 | } |
| 129 | return wire.ToolResult{Code: "created", Repo: in.Repo, Text: "Created."} |
| 130 | }} |
| 131 | args := json.RawMessage(`{"namespace":"oficina","name":"site"}`) |
| 132 | if _, isErr := b.Call(context.Background(), "p", "t1", 1, wire.ToolCreateProject, "toolu_1", args); !isErr { |
| 133 | t.Fatal("a repository without main was reported created") |
| 134 | } |
| 135 | remote := f.path("amadan.net/oficina/site") |
| 136 | os.Chmod(filepath.Join(remote, "objects"), 0700) |
| 137 | if text, isErr := b.Call(context.Background(), "p", "t1", 1, wire.ToolCreateProject, "toolu_1", args); isErr { |
| 138 | t.Fatalf("resent create: %s", text) |
| 139 | } |
| 140 | if f.creates != 1 { |
| 141 | t.Fatalf("created %d times", f.creates) |
| 142 | } |
| 143 | if refs := gitT(t, remote, "for-each-ref", "--format=%(refname)"); strings.TrimSpace(refs) != "refs/heads/main" { |
| 144 | t.Fatalf("refs after create: %q", refs) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // Only a repository this bridge created is started. One that already |
| 149 | // existed, empty or holding only tags, is adopted exactly as it is. |
| 150 | func TestCreateProjectAdoptsExistingRepositoriesAsTheyAre(t *testing.T) { |
| 151 | state, err := OpenState(context.Background(), t.TempDir()) |
| 152 | if err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | defer state.Close() |
| 156 | f, c := startRig(t) |
| 157 | b := &bridge{State: state, Forge: f, Clones: c, speaks: wire.ProtocolCurrent, trip: func(_ context.Context, call wire.ToolCall) wire.ToolResult { |
| 158 | var in struct{ Repo string } |
| 159 | _ = json.Unmarshal(call.Args, &in) |
| 160 | if call.Name == wire.ToolCreateProject { |
| 161 | return wire.ToolResult{Code: "create", Repo: in.Repo} |
| 162 | } |
| 163 | return wire.ToolResult{Code: "created", Repo: in.Repo, Text: "Created."} |
| 164 | }} |
| 165 | ctx := context.Background() |
| 166 | for i, name := range []string{"empty", "tagged"} { |
| 167 | repo := "amadan.net/oficina/" + name |
| 168 | if err := f.Create(ctx, repo); err != nil { // someone else's, before the call |
| 169 | t.Fatal(err) |
| 170 | } |
| 171 | if name == "tagged" { |
| 172 | seed := filepath.Join(t.TempDir(), "seed") |
| 173 | gitT(t, filepath.Dir(seed), "init", "-q", seed) |
| 174 | gitT(t, seed, "commit", "-q", "--allow-empty", "-m", "tagged") |
| 175 | gitT(t, seed, "push", "-q", f.path(repo), "HEAD:refs/tags/v1") |
| 176 | } |
| 177 | before := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)") |
| 178 | call := "toolu_adopt" + string(rune('0'+i)) |
| 179 | if text, isErr := b.Call(ctx, "p", "t3", 1, wire.ToolCreateProject, call, json.RawMessage(`{"namespace":"oficina","name":"`+name+`"}`)); isErr { |
| 180 | t.Fatalf("adopt %s: %s", name, text) |
| 181 | } |
| 182 | if after := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)"); after != before { |
| 183 | t.Fatalf("%s changed on adoption: %q -> %q", name, before, after) |
| 184 | } |
| 185 | } |
| 186 | if f.creates != 2 { |
| 187 | t.Fatalf("adoption created repositories: %d creates", f.creates) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | // A repository holding only tags is not empty: StartDefault leaves it. |
| 192 | func TestStartDefaultLeavesTagsAlone(t *testing.T) { |
| 193 | f, c := startRig(t) |
| 194 | const repo = "amadan.net/oficina/tags" |
| 195 | ctx := context.Background() |
| 196 | if err := f.Create(ctx, repo); err != nil { |
| 197 | t.Fatal(err) |
| 198 | } |
| 199 | seed := filepath.Join(t.TempDir(), "seed") |
| 200 | gitT(t, filepath.Dir(seed), "init", "-q", seed) |
| 201 | gitT(t, seed, "commit", "-q", "--allow-empty", "-m", "tagged") |
| 202 | gitT(t, seed, "push", "-q", f.path(repo), "HEAD:refs/tags/v1") |
| 203 | if err := c.StartDefault(ctx, repo); err != nil { |
| 204 | t.Fatal(err) |
| 205 | } |
| 206 | if refs := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname)"); refs != "refs/tags/v1" { |
| 207 | t.Fatalf("refs: %q", refs) |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | // Another writer between the emptiness check and the push. A main of |
| 212 | // theirs is never replaced and is the default. A branch of theirs that |
| 213 | // does not start from main fails the start, every time it is retried; |
| 214 | // main is withdrawn where the forge allows deleting it (git refuses to |
| 215 | // delete the current branch, so both are tested). |
| 216 | func TestStartDefaultConcurrentWriter(t *testing.T) { |
| 217 | for _, c := range []struct { |
| 218 | name, theirs string |
| 219 | deletable bool |
| 220 | }{{"their main", "main", false}, {"their branch", "trunk", false}, {"their branch, main withdrawn", "trunk", true}} { |
| 221 | t.Run(c.name, func(t *testing.T) { |
| 222 | f, clones := startRig(t) |
| 223 | const repo = "amadan.net/oficina/raced" |
| 224 | ctx := context.Background() |
| 225 | if err := f.Create(ctx, repo); err != nil { |
| 226 | t.Fatal(err) |
| 227 | } |
| 228 | if c.deletable { |
| 229 | gitT(t, f.path(repo), "config", "receive.denyDeleteCurrent", "false") |
| 230 | } |
| 231 | seed := filepath.Join(t.TempDir(), "seed") |
| 232 | gitT(t, filepath.Dir(seed), "init", "-q", "-b", c.theirs, seed) |
| 233 | os.WriteFile(filepath.Join(seed, "index.html"), []byte("theirs\n"), 0600) |
| 234 | gitT(t, seed, "add", "-A") |
| 235 | gitT(t, seed, "commit", "-q", "-m", "theirs") |
| 236 | tip := gitT(t, seed, "rev-parse", "HEAD") |
| 237 | old := startDefaultGap |
| 238 | t.Cleanup(func() { startDefaultGap = old }) |
| 239 | startDefaultGap = func() { gitT(t, seed, "push", "-q", f.path(repo), c.theirs) } |
| 240 | err := clones.StartDefault(ctx, repo) |
| 241 | startDefaultGap = func() {} |
| 242 | again := clones.StartDefault(ctx, repo) |
| 243 | refs := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)") |
| 244 | theirs := "refs/heads/" + c.theirs + " " + tip |
| 245 | switch { |
| 246 | case c.theirs == "main": |
| 247 | if err != nil || again != nil || refs != theirs { |
| 248 | t.Fatalf("their main: %v / %v, refs %q", err, again, refs) |
| 249 | } |
| 250 | case c.deletable: |
| 251 | if err == nil || refs != theirs { |
| 252 | t.Fatalf("main left beside their branch: %v, refs %q", err, refs) |
| 253 | } |
| 254 | default: |
| 255 | if err == nil || again == nil || !strings.Contains(refs, theirs) { |
| 256 | t.Fatalf("a start beside their unrelated branch reported success: %v / %v, refs %q", err, again, refs) |
| 257 | } |
| 258 | } |
| 259 | }) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | // Create owns a repository only when the hub answered that it created |
| 264 | // it. "Already exists", or an answer that never came while the |
| 265 | // repository turns out to exist, is adopted and not this runner's. |
| 266 | func TestFileForgeCreateOwnsOnlyWhatTheHubCreated(t *testing.T) { |
| 267 | for _, c := range []struct { |
| 268 | name string |
| 269 | before bool // the repository exists before the request |
| 270 | status int // the hub's answer to the create; 0 drops it |
| 271 | afterward bool // it exists when asked again |
| 272 | want error |
| 273 | }{ |
| 274 | {"created", false, http.StatusOK, true, nil}, |
| 275 | {"exists already", true, 0, true, ErrAdopted}, |
| 276 | {"another writer won", false, http.StatusConflict, true, ErrAdopted}, |
| 277 | {"answer lost", false, 0, true, ErrAdopted}, |
| 278 | {"refused", false, http.StatusForbidden, false, ErrNoCreate}, |
| 279 | } { |
| 280 | t.Run(c.name, func(t *testing.T) { |
| 281 | exists, posts := c.before, 0 |
| 282 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 283 | switch { |
| 284 | case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos": |
| 285 | repos := `{"ns":"oficina","name":"other"}` |
| 286 | if exists { |
| 287 | repos += `,{"ns":"oficina","name":"site"}` |
| 288 | } |
| 289 | w.Write([]byte(`{"repos":[` + repos + `]}`)) |
| 290 | case r.Method == http.MethodPost && r.URL.Path == "/api/v1/repos": |
| 291 | posts++ |
| 292 | exists = c.afterward |
| 293 | if c.status == 0 { |
| 294 | hj, _ := w.(http.Hijacker) |
| 295 | conn, _, _ := hj.Hijack() |
| 296 | conn.Close() |
| 297 | return |
| 298 | } |
| 299 | w.WriteHeader(c.status) |
| 300 | default: |
| 301 | w.WriteHeader(http.StatusNotFound) |
| 302 | } |
| 303 | }) |
| 304 | err := f.Create(context.Background(), "amadan.net/oficina/site") |
| 305 | if !errors.Is(err, c.want) || c.want == nil && err != nil { |
| 306 | t.Fatalf("Create = %v, want %v", err, c.want) |
| 307 | } |
| 308 | if c.before && posts != 0 { |
| 309 | t.Fatal("asked the hub to create a repository that exists") |
| 310 | } |
| 311 | }) |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | // Another writer creates the repository between Exists and Create: |
| 316 | // create_project adopts it and never starts main in it, then or on retry. |
| 317 | func TestCreateProjectNeverStartsARepositoryItDidNotMake(t *testing.T) { |
| 318 | state, err := OpenState(context.Background(), t.TempDir()) |
| 319 | if err != nil { |
| 320 | t.Fatal(err) |
| 321 | } |
| 322 | defer state.Close() |
| 323 | f, c := startRig(t) |
| 324 | lost := &adoptingForge{creatingForge: f} |
| 325 | b := &bridge{State: state, Forge: lost, Clones: c, speaks: wire.ProtocolCurrent, trip: func(_ context.Context, call wire.ToolCall) wire.ToolResult { |
| 326 | var in struct{ Repo string } |
| 327 | _ = json.Unmarshal(call.Args, &in) |
| 328 | if call.Name == wire.ToolCreateProject { |
| 329 | return wire.ToolResult{Code: "create", Repo: in.Repo} |
| 330 | } |
| 331 | return wire.ToolResult{Code: "created", Repo: in.Repo, Text: "Created."} |
| 332 | }} |
| 333 | args := json.RawMessage(`{"namespace":"oficina","name":"site"}`) |
| 334 | for range 2 { |
| 335 | if text, isErr := b.Call(context.Background(), "p", "t4", 1, wire.ToolCreateProject, "toolu_4", args); isErr { |
| 336 | t.Fatalf("adopt: %s", text) |
| 337 | } |
| 338 | if refs := gitT(t, f.path("amadan.net/oficina/site"), "for-each-ref"); refs != "" { |
| 339 | t.Fatalf("main started in someone else's repository: %q", refs) |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | // adoptingForge loses the race: the repository is made, by someone else. |
| 345 | type adoptingForge struct{ *creatingForge } |
| 346 | |
| 347 | func (f *adoptingForge) Create(ctx context.Context, repo string) error { |
| 348 | if err := f.creatingForge.Create(ctx, repo); err != nil { |
| 349 | return err |
| 350 | } |
| 351 | return ErrAdopted |
| 352 | } |
| 353 | |
| 354 | // An annotated tag on the start commit: ls-remote lists it peeled too |
| 355 | // (refs/tags/v1^{}), and neither line is someone else's unrelated work. |
| 356 | func TestStartDefaultAnnotatedTagOnMain(t *testing.T) { |
| 357 | f, c := startRig(t) |
| 358 | const repo = "amadan.net/oficina/tagged-main" |
| 359 | ctx := context.Background() |
| 360 | if err := f.Create(ctx, repo); err != nil { |
| 361 | t.Fatal(err) |
| 362 | } |
| 363 | if err := c.StartDefault(ctx, repo); err != nil { |
| 364 | t.Fatal(err) |
| 365 | } |
| 366 | main := gitT(t, f.path(repo), "rev-parse", "refs/heads/main") |
| 367 | gitT(t, f.path(repo), "tag", "-a", "-m", "first", "v1", main) |
| 368 | if err := c.StartDefault(ctx, repo); err != nil { |
| 369 | t.Fatalf("an annotated tag on main failed the start: %v", err) |
| 370 | } |
| 371 | if again := gitT(t, f.path(repo), "rev-parse", "refs/heads/main"); again != main { |
| 372 | t.Fatalf("main changed: %s -> %s", main, again) |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | // lsRefs keeps each ref once: HEAD and the peeled lines of annotated tags |
| 377 | // (refs/tags/v1^{}) are not refs of their own. |
| 378 | func TestLsRefsSkipsHeadAndPeeledTags(t *testing.T) { |
| 379 | a, b := strings.Repeat("a", 40), strings.Repeat("b", 40) |
| 380 | got := lsRefs(a + "\tHEAD\n" + a + "\trefs/heads/main\n" + b + "\trefs/tags/v1\n" + a + "\trefs/tags/v1^{}\n") |
| 381 | if len(got) != 2 || got["refs/heads/main"] != a || got["refs/tags/v1"] != b { |
| 382 | t.Fatalf("lsRefs = %v", got) |
| 383 | } |
| 384 | } |
| 385 | |