package thin import ( "context" "encoding/json" "fmt" "os" "path/filepath" "strings" "testing" "amadan.net/oficina/equipo/internal/equipo/mergegate" "amadan.net/oficina/equipo/internal/wire" ) func TestEngineeringChangeFiles(t *testing.T) { dir, git := factsRepo(t) base := git("rev-parse", "HEAD") git("mv", "README.md", "read me 日本語.md") git("rm", "Sources/Pane.swift") writeFile(t, dir, "new space.txt", "one\ntwo\n") writeFile(t, dir, "assets/icon.png", "\x89PNG\x00changed") git("add", "-A") git("commit", "-qm", "candidate") sha := git("rev-parse", "HEAD") before := measure(t, dir, base, sha, "") decision := func(f *wire.ChangeFacts) []byte { b, err := json.Marshal(mergegate.Decide(mergegate.Inputs{Candidate: sha, Verdict: wire.VerdictApprove, Checks: wire.ChecksPassed, BaseChecks: true, Eligible: true, Change: f, Protocol: wire.ProtocolCurrent, Policy: mergegate.DefaultPolicy()})) if err != nil { t.Fatal(err) } return b } previous := string(decision(before)) f := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, sha) if f == nil || f.Base != base || f.SHA != sha || f.Files != 4 || f.Additions != 2 || f.Deletions != 1 || f.Binary != 1 || f.Truncated || len(f.Entries) != 4 { t.Fatalf("facts: %+v", f) } entries := map[string]wire.ChangedFile{} for _, e := range f.Entries { entries[e.Path] = e } if e := entries["read me 日本語.md"]; e.Status != "renamed" || e.OldPath != "README.md" { t.Fatalf("rename: %+v", e) } if e := entries["Sources/Pane.swift"]; e.Status != "deleted" || e.Deletions != 1 { t.Fatalf("delete: %+v", e) } if e := entries["assets/icon.png"]; !e.Binary || e.Status != "modified" || e.Additions != 0 { t.Fatalf("binary: %+v", e) } if e := entries["new space.txt"]; e.Status != "added" || e.Additions != 2 { t.Fatalf("added: %+v", e) } _ = collectChangeDiffs(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), f, nil) after := measure(t, dir, base, sha, "") a, _ := json.Marshal(before) b, _ := json.Marshal(after) if string(a) != string(b) || previous != string(decision(after)) { t.Fatal("presentation changed Review facts or gate decision") } if changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), sha, base) != nil { t.Fatal("nonancestor accepted") } } func TestChangeFilesBounds(t *testing.T) { dir, git := factsRepo(t) base := git("rev-parse", "HEAD") for i := 0; i < wire.MaxChangeEntries+3; i++ { writeFile(t, dir, fmt.Sprintf("many/%03d.txt", i), "one\n") } git("add", "-A") git("commit", "-qm", "many") f := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, git("rev-parse", "HEAD")) if f == nil || len(f.Entries) != 200 || !f.Truncated || f.Files != 203 || f.Additions != 203 || f.Deletions != 0 { t.Fatalf("bounded exact totals: %+v", f) } } func TestChangeFilesByteBoundAndMalformedListings(t *testing.T) { base, sha := strings.Repeat("a", 40), strings.Repeat("b", 40) var raw, num strings.Builder for i := 0; i < 200; i++ { name := fmt.Sprintf("%03d/%s", i, strings.Repeat("x", 3900)) fmt.Fprintf(&raw, ":000000 100644 %s %s A\x00%s\x00", base, sha, name) fmt.Fprintf(&num, "1\t0\t%s\x00", name) } f := changeFileListings(base, sha, raw.String(), num.String()) if f == nil || !f.Truncated || len(f.Entries) >= 200 || len(f.Entries) == 0 || f.Files != 200 || f.Additions != 200 { t.Fatalf("byte bound: %+v", f) } encoded, _ := json.Marshal(f) if len(encoded) > wire.MaxChangeFilesBytes { t.Fatalf("encoded %d bytes", len(encoded)) } for name, parts := range map[string][2]string{ "bad-raw": {"not raw", num.String()}, "bad-num": {raw.String(), "not numstat"}, "missing-stat": {raw.String(), ""}, "mismatched-path": {":000000 100644 " + base + " " + sha + " A\x00one\x00", "1\t0\ttwo\x00"}, "traversal": {":000000 100644 " + base + " " + sha + " A\x00../secret\x00", "1\t0\t../secret\x00"}, } { t.Run(name, func(t *testing.T) { if changeFileListings(base, sha, parts[0], parts[1]) != nil { t.Fatal("malformed listing accepted") } }) } } func TestChangeFilesClippedScanNeverInventsTotals(t *testing.T) { dir := t.TempDir() fake := filepath.Join(dir, "git") // Exactly 4096 complete raw records fit the 1 MiB read bound. A final // complete record is clipped, so parsing the prefix alone would look valid. script := `#!/usr/bin/python3 import sys head=":000000 100644 "+"a"*40+" "+"b"*40+" A\0" width=256-len(head)-1 if "--raw" in sys.argv: for i in range(4097): name=str(i).zfill(width) sys.stdout.buffer.write((head+name+"\0").encode()) elif "--numstat" in sys.argv: for i in range(4096): sys.stdout.buffer.write(("1\t0\t"+str(i).zfill(width)+"\0").encode()) ` if err := os.WriteFile(fake, []byte(script), 0700); err != nil { t.Fatal(err) } f := changeFiles(context.Background(), fake, dir, strings.Repeat("a", 40), strings.Repeat("b", 40)) if f != nil { t.Fatalf("clipped scan has invented totals: %+v", f) } } func TestChangeFilesInitialCommit(t *testing.T) { dir, git := factsRepo(t) root := git("rev-parse", "HEAD") f := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), "", root) if f == nil || f.Base != "" || f.SHA != root || f.Files != 5 { t.Fatalf("initial commit: %+v", f) } writeFile(t, dir, "later.txt", "later\n") git("add", "-A") git("commit", "-qm", "later") if changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), "", git("rev-parse", "HEAD")) != nil { t.Fatal("missing base on non-root commit was guessed") } } func TestChangeFilesFinalValidationAndTypeChange(t *testing.T) { base, sha := strings.Repeat("a", 40), strings.Repeat("b", 40) raw := fmt.Sprintf(":100644 120000 %s %s T\x00link\x00", base, sha) f := changeFileListings(base, sha, raw, "1\t1\tlink\x00") if f == nil || len(f.Entries) != 1 || f.Entries[0].Status != wire.ChangeFileModified { t.Fatalf("type change: %+v", f) } if changeFileListings(base, sha, raw+raw, "1\t1\tlink\x001\t1\tlink\x00") != nil { t.Fatal("duplicate paths passed final validation") } } func TestChangeFilesInvalidCommitsNeverInvokeGit(t *testing.T) { dir := t.TempDir() fake := filepath.Join(dir, "git") if err := os.WriteFile(fake, []byte("#!/bin/sh\n: > \"$0.called\"\n"), 0700); err != nil { t.Fatal(err) } good := strings.Repeat("a", 40) for _, pair := range [][2]string{{good, strings.Repeat("b", 39)}, {strings.Repeat("b", 39), good}, {good, strings.Repeat("z", 40)}} { if changeFiles(context.Background(), fake, dir, pair[0], pair[1]) != nil { t.Fatal("invalid commit accepted") } if _, err := os.Stat(fake + ".called"); !os.IsNotExist(err) { t.Fatal("git invoked for invalid commit") } } } func TestChangeFilesPublishedOnlyByEngineering(t *testing.T) { for _, specialist := range []string{wire.SpecialistEngineering, wire.SpecialistCopy} { t.Run(specialist, func(t *testing.T) { e, f, r, _ := hubRig(t) r.Specialist, r.StepID, r.Branch = specialist, "s2", "equipo/tk1-another-fix" base := gitOut(t, f.dir, "rev-parse", "main") gitDir := e.tree(r, base).GitDir gitOut(t, filepath.Dir(f.dir), "clone", "-q", "--bare", f.dir, gitDir) tree := gitOut(t, filepath.Dir(f.dir), "--git-dir="+gitDir, "rev-parse", base+"^{tree}") r.Base, r.Candidate = base, gitOut(t, filepath.Dir(f.dir), "--git-dir="+gitDir, "commit-tree", tree, "-p", base, "-m", "another fix") r.CandidateSHA = base rep := e.publish(context.Background(), r, wire.StepReport{}) if (rep.ChangeFiles != nil) != (specialist == wire.SpecialistEngineering) { t.Fatalf("%s facts: %+v", specialist, rep.ChangeFiles) } }) } }