package thin import ( "context" "encoding/json" "errors" "net/http" "os" "path/filepath" "strings" "testing" "amadan.net/oficina/equipo/internal/wire" ) // creatingForge makes each repository it creates as an empty bare // repository, the way the hub serves a new one. type creatingForge struct { pathForge t *testing.T failPush bool } func (f *creatingForge) Create(ctx context.Context, repo string) error { if err := f.countingForge.Create(ctx, repo); err != nil { return err } gitT(f.t, filepath.Dir(f.path(repo)), "init", "-q", "--bare", "-b", "main", f.path(repo)) if f.failPush { // The hub refuses the first push: no main, and nothing recorded. os.Chmod(filepath.Join(f.path(repo), "objects"), 0500) f.t.Cleanup(func() { os.Chmod(filepath.Join(f.path(repo), "objects"), 0700) }) } return nil } func startRig(t *testing.T) (*creatingForge, *Clones) { t.Helper() root := t.TempDir() f := &creatingForge{pathForge: pathForge{root: filepath.Join(root, "forge")}, t: t} os.MkdirAll(f.root, 0700) os.MkdirAll(filepath.Join(root, "work"), 0700) return f, &Clones{Root: filepath.Join(root, "work"), Git: "git", Forge: f} } // A repository Equipo creates gets its default branch, main, at an empty // first commit before any task branch exists. Task branches then start // from main and every merge targets it. Without it, the hub made the // first task branch pushed the default, and the next task's merge was // asked to merge into that unrelated branch ("could not compute the // merge"). func TestStartDefaultMakesMainBeforeAnyTaskBranch(t *testing.T) { f, c := startRig(t) const repo = "amadan.net/oficina/site" ctx := context.Background() if err := f.Create(ctx, repo); err != nil { t.Fatal(err) } if _, err := c.DefaultBranch(ctx, repo); !errors.Is(err, ErrEmptyRepo) { t.Fatalf("a new repository should start empty: %v", err) } if err := c.StartDefault(ctx, repo); err != nil { t.Fatal(err) } remote := f.path(repo) if refs := gitT(t, remote, "for-each-ref", "--format=%(refname)"); refs != "refs/heads/main" { t.Fatalf("refs after start: %q", refs) } main := gitT(t, remote, "rev-parse", "refs/heads/main") if tree := gitT(t, remote, "rev-parse", main+"^{tree}"); tree != gitT(t, remote, "hash-object", "-t", "tree", "/dev/null") { t.Fatalf("main's first commit is not empty: tree %s", tree) } if parents := gitT(t, remote, "rev-list", "--parents", "-n1", main); parents != main { t.Fatalf("main's first commit has parents: %s", parents) } if def, err := c.DefaultBranch(ctx, repo); err != nil || def != "main" { t.Fatalf("default after start: %q %v", def, err) } // Again (a resent create): nothing new. if err := c.StartDefault(ctx, repo); err != nil { t.Fatal(err) } if again := gitT(t, remote, "rev-parse", "refs/heads/main"); again != main { t.Fatalf("main moved on a second start: %s -> %s", main, again) } } // A repository with any branch already, including one holding only task // branches (the stuck ones), is left exactly as it is. func TestStartDefaultLeavesBranchesAlone(t *testing.T) { f, c := startRig(t) const repo = "amadan.net/oficina/stuck" ctx := context.Background() if err := f.Create(ctx, repo); err != nil { t.Fatal(err) } seed := filepath.Join(t.TempDir(), "seed") gitT(t, filepath.Dir(seed), "init", "-q", "-b", "equipo/tk1-demo", seed) os.WriteFile(filepath.Join(seed, "index.html"), []byte("demo\n"), 0600) gitT(t, seed, "add", "-A") gitT(t, seed, "commit", "-q", "-m", "demo") gitT(t, seed, "push", "-q", f.path(repo), "equipo/tk1-demo") before := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)") if err := c.StartDefault(ctx, repo); err != nil { t.Fatal(err) } if after := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)"); after != before { t.Fatalf("refs changed: %q -> %q", before, after) } } // create_project starts main as part of creating the repository; a // failed start is not recorded as created, so the resent call (the // repository exists by then) starts it. func TestCreateProjectStartsMain(t *testing.T) { state, err := OpenState(context.Background(), t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() f, c := startRig(t) f.failPush = true b := &bridge{State: state, Forge: f, Clones: c, speaks: wire.ProtocolCurrent, trip: func(_ context.Context, call wire.ToolCall) wire.ToolResult { var in struct{ Repo string } _ = json.Unmarshal(call.Args, &in) if call.Name == wire.ToolCreateProject { return wire.ToolResult{Code: "create", Repo: in.Repo} } return wire.ToolResult{Code: "created", Repo: in.Repo, Text: "Created."} }} args := json.RawMessage(`{"namespace":"oficina","name":"site"}`) if _, isErr := b.Call(context.Background(), "p", "t1", 1, wire.ToolCreateProject, "toolu_1", args); !isErr { t.Fatal("a repository without main was reported created") } remote := f.path("amadan.net/oficina/site") os.Chmod(filepath.Join(remote, "objects"), 0700) if text, isErr := b.Call(context.Background(), "p", "t1", 1, wire.ToolCreateProject, "toolu_1", args); isErr { t.Fatalf("resent create: %s", text) } if f.creates != 1 { t.Fatalf("created %d times", f.creates) } if refs := gitT(t, remote, "for-each-ref", "--format=%(refname)"); strings.TrimSpace(refs) != "refs/heads/main" { t.Fatalf("refs after create: %q", refs) } } // Only a repository this bridge created is started. One that already // existed, empty or holding only tags, is adopted exactly as it is. func TestCreateProjectAdoptsExistingRepositoriesAsTheyAre(t *testing.T) { state, err := OpenState(context.Background(), t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() f, c := startRig(t) b := &bridge{State: state, Forge: f, Clones: c, speaks: wire.ProtocolCurrent, trip: func(_ context.Context, call wire.ToolCall) wire.ToolResult { var in struct{ Repo string } _ = json.Unmarshal(call.Args, &in) if call.Name == wire.ToolCreateProject { return wire.ToolResult{Code: "create", Repo: in.Repo} } return wire.ToolResult{Code: "created", Repo: in.Repo, Text: "Created."} }} ctx := context.Background() for i, name := range []string{"empty", "tagged"} { repo := "amadan.net/oficina/" + name if err := f.Create(ctx, repo); err != nil { // someone else's, before the call t.Fatal(err) } if name == "tagged" { seed := filepath.Join(t.TempDir(), "seed") gitT(t, filepath.Dir(seed), "init", "-q", seed) gitT(t, seed, "commit", "-q", "--allow-empty", "-m", "tagged") gitT(t, seed, "push", "-q", f.path(repo), "HEAD:refs/tags/v1") } before := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)") call := "toolu_adopt" + string(rune('0'+i)) if text, isErr := b.Call(ctx, "p", "t3", 1, wire.ToolCreateProject, call, json.RawMessage(`{"namespace":"oficina","name":"`+name+`"}`)); isErr { t.Fatalf("adopt %s: %s", name, text) } if after := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)"); after != before { t.Fatalf("%s changed on adoption: %q -> %q", name, before, after) } } if f.creates != 2 { t.Fatalf("adoption created repositories: %d creates", f.creates) } } // A repository holding only tags is not empty: StartDefault leaves it. func TestStartDefaultLeavesTagsAlone(t *testing.T) { f, c := startRig(t) const repo = "amadan.net/oficina/tags" ctx := context.Background() if err := f.Create(ctx, repo); err != nil { t.Fatal(err) } seed := filepath.Join(t.TempDir(), "seed") gitT(t, filepath.Dir(seed), "init", "-q", seed) gitT(t, seed, "commit", "-q", "--allow-empty", "-m", "tagged") gitT(t, seed, "push", "-q", f.path(repo), "HEAD:refs/tags/v1") if err := c.StartDefault(ctx, repo); err != nil { t.Fatal(err) } if refs := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname)"); refs != "refs/tags/v1" { t.Fatalf("refs: %q", refs) } } // Another writer between the emptiness check and the push. A main of // theirs is never replaced and is the default. A branch of theirs that // does not start from main fails the start, every time it is retried; // main is withdrawn where the forge allows deleting it (git refuses to // delete the current branch, so both are tested). func TestStartDefaultConcurrentWriter(t *testing.T) { for _, c := range []struct { name, theirs string deletable bool }{{"their main", "main", false}, {"their branch", "trunk", false}, {"their branch, main withdrawn", "trunk", true}} { t.Run(c.name, func(t *testing.T) { f, clones := startRig(t) const repo = "amadan.net/oficina/raced" ctx := context.Background() if err := f.Create(ctx, repo); err != nil { t.Fatal(err) } if c.deletable { gitT(t, f.path(repo), "config", "receive.denyDeleteCurrent", "false") } seed := filepath.Join(t.TempDir(), "seed") gitT(t, filepath.Dir(seed), "init", "-q", "-b", c.theirs, seed) os.WriteFile(filepath.Join(seed, "index.html"), []byte("theirs\n"), 0600) gitT(t, seed, "add", "-A") gitT(t, seed, "commit", "-q", "-m", "theirs") tip := gitT(t, seed, "rev-parse", "HEAD") old := startDefaultGap t.Cleanup(func() { startDefaultGap = old }) startDefaultGap = func() { gitT(t, seed, "push", "-q", f.path(repo), c.theirs) } err := clones.StartDefault(ctx, repo) startDefaultGap = func() {} again := clones.StartDefault(ctx, repo) refs := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)") theirs := "refs/heads/" + c.theirs + " " + tip switch { case c.theirs == "main": if err != nil || again != nil || refs != theirs { t.Fatalf("their main: %v / %v, refs %q", err, again, refs) } case c.deletable: if err == nil || refs != theirs { t.Fatalf("main left beside their branch: %v, refs %q", err, refs) } default: if err == nil || again == nil || !strings.Contains(refs, theirs) { t.Fatalf("a start beside their unrelated branch reported success: %v / %v, refs %q", err, again, refs) } } }) } } // Create owns a repository only when the hub answered that it created // it. "Already exists", or an answer that never came while the // repository turns out to exist, is adopted and not this runner's. func TestFileForgeCreateOwnsOnlyWhatTheHubCreated(t *testing.T) { for _, c := range []struct { name string before bool // the repository exists before the request status int // the hub's answer to the create; 0 drops it afterward bool // it exists when asked again want error }{ {"created", false, http.StatusOK, true, nil}, {"exists already", true, 0, true, ErrAdopted}, {"another writer won", false, http.StatusConflict, true, ErrAdopted}, {"answer lost", false, 0, true, ErrAdopted}, {"refused", false, http.StatusForbidden, false, ErrNoCreate}, } { t.Run(c.name, func(t *testing.T) { exists, posts := c.before, 0 f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { switch { case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos": repos := `{"ns":"oficina","name":"other"}` if exists { repos += `,{"ns":"oficina","name":"site"}` } w.Write([]byte(`{"repos":[` + repos + `]}`)) case r.Method == http.MethodPost && r.URL.Path == "/api/v1/repos": posts++ exists = c.afterward if c.status == 0 { hj, _ := w.(http.Hijacker) conn, _, _ := hj.Hijack() conn.Close() return } w.WriteHeader(c.status) default: w.WriteHeader(http.StatusNotFound) } }) err := f.Create(context.Background(), "amadan.net/oficina/site") if !errors.Is(err, c.want) || c.want == nil && err != nil { t.Fatalf("Create = %v, want %v", err, c.want) } if c.before && posts != 0 { t.Fatal("asked the hub to create a repository that exists") } }) } } // Another writer creates the repository between Exists and Create: // create_project adopts it and never starts main in it, then or on retry. func TestCreateProjectNeverStartsARepositoryItDidNotMake(t *testing.T) { state, err := OpenState(context.Background(), t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() f, c := startRig(t) lost := &adoptingForge{creatingForge: f} b := &bridge{State: state, Forge: lost, Clones: c, speaks: wire.ProtocolCurrent, trip: func(_ context.Context, call wire.ToolCall) wire.ToolResult { var in struct{ Repo string } _ = json.Unmarshal(call.Args, &in) if call.Name == wire.ToolCreateProject { return wire.ToolResult{Code: "create", Repo: in.Repo} } return wire.ToolResult{Code: "created", Repo: in.Repo, Text: "Created."} }} args := json.RawMessage(`{"namespace":"oficina","name":"site"}`) for range 2 { if text, isErr := b.Call(context.Background(), "p", "t4", 1, wire.ToolCreateProject, "toolu_4", args); isErr { t.Fatalf("adopt: %s", text) } if refs := gitT(t, f.path("amadan.net/oficina/site"), "for-each-ref"); refs != "" { t.Fatalf("main started in someone else's repository: %q", refs) } } } // adoptingForge loses the race: the repository is made, by someone else. type adoptingForge struct{ *creatingForge } func (f *adoptingForge) Create(ctx context.Context, repo string) error { if err := f.creatingForge.Create(ctx, repo); err != nil { return err } return ErrAdopted } // An annotated tag on the start commit: ls-remote lists it peeled too // (refs/tags/v1^{}), and neither line is someone else's unrelated work. func TestStartDefaultAnnotatedTagOnMain(t *testing.T) { f, c := startRig(t) const repo = "amadan.net/oficina/tagged-main" ctx := context.Background() if err := f.Create(ctx, repo); err != nil { t.Fatal(err) } if err := c.StartDefault(ctx, repo); err != nil { t.Fatal(err) } main := gitT(t, f.path(repo), "rev-parse", "refs/heads/main") gitT(t, f.path(repo), "tag", "-a", "-m", "first", "v1", main) if err := c.StartDefault(ctx, repo); err != nil { t.Fatalf("an annotated tag on main failed the start: %v", err) } if again := gitT(t, f.path(repo), "rev-parse", "refs/heads/main"); again != main { t.Fatalf("main changed: %s -> %s", main, again) } } // lsRefs keeps each ref once: HEAD and the peeled lines of annotated tags // (refs/tags/v1^{}) are not refs of their own. func TestLsRefsSkipsHeadAndPeeledTags(t *testing.T) { a, b := strings.Repeat("a", 40), strings.Repeat("b", 40) got := lsRefs(a + "\tHEAD\n" + a + "\trefs/heads/main\n" + b + "\trefs/tags/v1\n" + a + "\trefs/tags/v1^{}\n") if len(got) != 2 || got["refs/heads/main"] != a || got["refs/tags/v1"] != b { t.Fatalf("lsRefs = %v", got) } }