| 1 | package git |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "os/exec" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | const ( |
| 15 | testChangeID = "zyxwvutsrqponmlkzyxwvutsrqponmlk" |
| 16 | testRunA = "20261013-1200-aaaaaaaa" |
| 17 | testRunB = "20261013-1300-bbbbbbbb" |
| 18 | ) |
| 19 | |
| 20 | // isolateGitConfig points git at an empty system config and a temp global |
| 21 | // config holding only a committer identity, so the host's hooksPath or |
| 22 | // trailer settings cannot leak into the tests. |
| 23 | func isolateGitConfig(t *testing.T) { |
| 24 | t.Helper() |
| 25 | global := filepath.Join(t.TempDir(), "gitconfig") |
| 26 | if err := os.WriteFile(global, []byte("[user]\n\tname = Test\n\temail = test@test.com\n"), 0o644); err != nil { |
| 27 | t.Fatal(err) |
| 28 | } |
| 29 | t.Setenv("GIT_CONFIG_GLOBAL", global) |
| 30 | t.Setenv("GIT_CONFIG_NOSYSTEM", "1") |
| 31 | } |
| 32 | |
| 33 | // testClone creates a bare origin with one commit on main and returns a clone |
| 34 | // of it, the way klaus clones target repos. |
| 35 | func testClone(t *testing.T) string { |
| 36 | t.Helper() |
| 37 | isolateGitConfig(t) |
| 38 | seed := initTestRepo(t) |
| 39 | origin := filepath.Join(t.TempDir(), "origin.git") |
| 40 | clone := filepath.Join(t.TempDir(), "clone") |
| 41 | mustGit(t, "", "init", "--quiet", "--bare", "--initial-branch=main", origin) |
| 42 | mustGit(t, seed, "push", "--quiet", origin, "main") |
| 43 | mustGit(t, "", "clone", "--quiet", origin, clone) |
| 44 | return clone |
| 45 | } |
| 46 | |
| 47 | // addWorktree adds a linked worktree of clone on a new branch and returns it. |
| 48 | func addWorktree(t *testing.T, clone, name string) string { |
| 49 | t.Helper() |
| 50 | wt := filepath.Join(t.TempDir(), name) |
| 51 | if err := WorktreeAdd(context.Background(), clone, wt, name, "main"); err != nil { |
| 52 | t.Fatalf("WorktreeAdd: %v", err) |
| 53 | } |
| 54 | return wt |
| 55 | } |
| 56 | |
| 57 | func mustGit(t *testing.T, dir string, args ...string) string { |
| 58 | t.Helper() |
| 59 | cmd := exec.Command("git", args...) |
| 60 | cmd.Dir = dir |
| 61 | out, err := cmd.CombinedOutput() |
| 62 | if err != nil { |
| 63 | t.Fatalf("git %v: %v\n%s", args, err, out) |
| 64 | } |
| 65 | return strings.TrimSpace(string(out)) |
| 66 | } |
| 67 | |
| 68 | // commitFile writes a file in dir and commits it with msg, running hooks. |
| 69 | func commitFile(t *testing.T, dir, name, msg string) { |
| 70 | t.Helper() |
| 71 | if err := os.WriteFile(filepath.Join(dir, name), []byte(name+"\n"), 0o644); err != nil { |
| 72 | t.Fatal(err) |
| 73 | } |
| 74 | mustGit(t, dir, "add", name) |
| 75 | mustGit(t, dir, "commit", "--quiet", "-m", msg) |
| 76 | } |
| 77 | |
| 78 | func headMessage(t *testing.T, dir string) string { |
| 79 | t.Helper() |
| 80 | return mustGit(t, dir, "log", "-1", "--format=%B") |
| 81 | } |
| 82 | |
| 83 | // trailerValues returns the values of key in HEAD's trailer block, in order. |
| 84 | func trailerValues(t *testing.T, dir, key string) []string { |
| 85 | t.Helper() |
| 86 | out := mustGit(t, dir, "log", "-1", "--format=%(trailers:key="+key+",valueonly,separator=%x0A)") |
| 87 | if out == "" { |
| 88 | return nil |
| 89 | } |
| 90 | return strings.Split(out, "\n") |
| 91 | } |
| 92 | |
| 93 | func sharedHooksPaths(t *testing.T, clone string) []string { |
| 94 | t.Helper() |
| 95 | out, err := runGit(context.Background(), clone, "config", "--local", "--get-all", "core.hooksPath") |
| 96 | if err != nil || out == "" { |
| 97 | return nil |
| 98 | } |
| 99 | return strings.Split(out, "\n") |
| 100 | } |
| 101 | |
| 102 | func install(t *testing.T, wt string, prov Provenance) { |
| 103 | t.Helper() |
| 104 | if err := InstallHooks(context.Background(), wt, prov, nil); err != nil { |
| 105 | t.Fatalf("InstallHooks: %v", err) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | func TestInstallHooks_ScopedToWorktree(t *testing.T) { |
| 110 | clone := testClone(t) |
| 111 | wtA := addWorktree(t, clone, "run-a") |
| 112 | wtB := addWorktree(t, clone, "run-b") |
| 113 | install(t, wtA, Provenance{RunID: testRunA, ChangeID: testChangeID}) |
| 114 | install(t, wtB, Provenance{RunID: testRunB, ChangeID: "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"}) |
| 115 | |
| 116 | if got := sharedHooksPaths(t, clone); len(got) != 0 { |
| 117 | t.Errorf("shared config has core.hooksPath %v, want none", got) |
| 118 | } |
| 119 | |
| 120 | commitFile(t, wtA, "a.txt", "change in a") |
| 121 | commitFile(t, wtB, "b.txt", "change in b") |
| 122 | if got := trailerValues(t, wtA, "Klaus-Run"); len(got) != 1 || got[0] != testRunA { |
| 123 | t.Errorf("worktree a Klaus-Run = %v, want [%s]\n%s", got, testRunA, headMessage(t, wtA)) |
| 124 | } |
| 125 | if got := trailerValues(t, wtB, "Klaus-Run"); len(got) != 1 || got[0] != testRunB { |
| 126 | t.Errorf("worktree b Klaus-Run = %v, want [%s]\n%s", got, testRunB, headMessage(t, wtB)) |
| 127 | } |
| 128 | |
| 129 | // The main clone runs no klaus hook, before and after a worktree goes. |
| 130 | commitFile(t, clone, "main.txt", "change in main") |
| 131 | if msg := headMessage(t, clone); msg != "change in main" { |
| 132 | t.Errorf("main clone commit was rewritten by a hook:\n%s", msg) |
| 133 | } |
| 134 | if err := WorktreeRemove(context.Background(), clone, wtA); err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | commitFile(t, wtB, "b2.txt", "another change in b") |
| 138 | if got := trailerValues(t, wtB, "Klaus-Run"); len(got) != 1 || got[0] != testRunB { |
| 139 | t.Errorf("worktree b lost its hook after a removed: Klaus-Run = %v", got) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | func TestInstallHooks_RepairsLeakedSharedHooksPath(t *testing.T) { |
| 144 | t.Run("value inside a worktree's git dir is removed", func(t *testing.T) { |
| 145 | clone := testClone(t) |
| 146 | gone := addWorktree(t, clone, "gone") |
| 147 | goneHooks := filepath.Join(clone, ".git", "worktrees", "gone", "hooks") |
| 148 | mustGit(t, clone, "config", "core.hooksPath", goneHooks) |
| 149 | if err := WorktreeRemove(context.Background(), clone, gone); err != nil { |
| 150 | t.Fatal(err) |
| 151 | } |
| 152 | |
| 153 | install(t, addWorktree(t, clone, "run-a"), Provenance{RunID: testRunA}) |
| 154 | if got := sharedHooksPaths(t, clone); len(got) != 0 { |
| 155 | t.Errorf("shared core.hooksPath = %v, want the leaked value removed", got) |
| 156 | } |
| 157 | }) |
| 158 | |
| 159 | t.Run("value elsewhere is kept", func(t *testing.T) { |
| 160 | clone := testClone(t) |
| 161 | own := filepath.Join(clone, ".git", "hooks") |
| 162 | mustGit(t, clone, "config", "core.hooksPath", own) |
| 163 | |
| 164 | install(t, addWorktree(t, clone, "run-a"), Provenance{RunID: testRunA}) |
| 165 | if got := sharedHooksPaths(t, clone); len(got) != 1 || got[0] != own { |
| 166 | t.Errorf("shared core.hooksPath = %v, want [%s] kept", got, own) |
| 167 | } |
| 168 | }) |
| 169 | } |
| 170 | |
| 171 | // holdConfigLock takes the clone's config.lock, as a concurrent git config |
| 172 | // does. After delay it writes the shared config with the git config args in |
| 173 | // update applied into the lock and renames the lock into place, the way git |
| 174 | // commits a config change. The returned channel reports how that went. |
| 175 | func holdConfigLock(t *testing.T, clone string, delay time.Duration, update ...string) <-chan error { |
| 176 | t.Helper() |
| 177 | config := filepath.Join(clone, ".git", "config") |
| 178 | lock := config + ".lock" |
| 179 | f, err := os.OpenFile(lock, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) |
| 180 | if err != nil { |
| 181 | t.Fatal(err) |
| 182 | } |
| 183 | f.Close() |
| 184 | scratch := filepath.Join(t.TempDir(), "config") |
| 185 | released := make(chan error, 1) |
| 186 | go func() { |
| 187 | time.Sleep(delay) |
| 188 | released <- func() error { |
| 189 | old, err := os.ReadFile(config) |
| 190 | if err != nil { |
| 191 | return err |
| 192 | } |
| 193 | if err := os.WriteFile(scratch, old, 0o644); err != nil { |
| 194 | return err |
| 195 | } |
| 196 | args := append([]string{"config", "--file", scratch}, update...) |
| 197 | if out, err := exec.Command("git", args...).CombinedOutput(); err != nil { |
| 198 | return fmt.Errorf("git %v: %v\n%s", args, err, out) |
| 199 | } |
| 200 | next, err := os.ReadFile(scratch) |
| 201 | if err != nil { |
| 202 | return err |
| 203 | } |
| 204 | if err := os.WriteFile(lock, next, 0o644); err != nil { |
| 205 | return err |
| 206 | } |
| 207 | return os.Rename(lock, config) |
| 208 | }() |
| 209 | }() |
| 210 | return released |
| 211 | } |
| 212 | |
| 213 | // TestInstallHooks_WaitsForConcurrentConfigWrite covers two launches |
| 214 | // installing at once: the one that loses config.lock must wait for the winner |
| 215 | // to put the same change in place, not fail on seeing the old config. |
| 216 | func TestInstallHooks_WaitsForConcurrentConfigWrite(t *testing.T) { |
| 217 | t.Run("enabling extensions.worktreeConfig", func(t *testing.T) { |
| 218 | clone := testClone(t) |
| 219 | wt := addWorktree(t, clone, "run-a") |
| 220 | released := holdConfigLock(t, clone, 300*time.Millisecond, "extensions.worktreeConfig", "true") |
| 221 | |
| 222 | install(t, wt, Provenance{RunID: testRunA}) |
| 223 | if err := <-released; err != nil { |
| 224 | t.Fatalf("releasing config.lock: %v", err) |
| 225 | } |
| 226 | commitFile(t, wt, "a.txt", "change in a") |
| 227 | if got := trailerValues(t, wt, "Klaus-Run"); len(got) != 1 || got[0] != testRunA { |
| 228 | t.Errorf("Klaus-Run = %v, want [%s]", got, testRunA) |
| 229 | } |
| 230 | }) |
| 231 | |
| 232 | t.Run("removing a leaked core.hooksPath", func(t *testing.T) { |
| 233 | clone := testClone(t) |
| 234 | leakedHooks := filepath.Join(clone, ".git", "worktrees", "gone", "hooks") |
| 235 | mustGit(t, clone, "config", "core.hooksPath", leakedHooks) |
| 236 | wt := addWorktree(t, clone, "run-a") |
| 237 | released := holdConfigLock(t, clone, 300*time.Millisecond, "--unset-all", "core.hooksPath") |
| 238 | |
| 239 | install(t, wt, Provenance{RunID: testRunA}) |
| 240 | if err := <-released; err != nil { |
| 241 | t.Fatalf("releasing config.lock: %v", err) |
| 242 | } |
| 243 | if got := sharedHooksPaths(t, clone); len(got) != 0 { |
| 244 | t.Errorf("shared core.hooksPath = %v, want the leaked value removed", got) |
| 245 | } |
| 246 | }) |
| 247 | |
| 248 | t.Run("a lock never released fails once the wait is over", func(t *testing.T) { |
| 249 | defer func(d time.Duration) { configLockWait = d }(configLockWait) |
| 250 | configLockWait = 200 * time.Millisecond |
| 251 | clone := testClone(t) |
| 252 | wt := addWorktree(t, clone, "run-a") |
| 253 | lock := filepath.Join(clone, ".git", "config.lock") |
| 254 | if err := os.WriteFile(lock, nil, 0o644); err != nil { |
| 255 | t.Fatal(err) |
| 256 | } |
| 257 | |
| 258 | err := InstallHooks(context.Background(), wt, Provenance{RunID: testRunA}, nil) |
| 259 | if err == nil || !strings.Contains(err.Error(), "extensions.worktreeConfig") { |
| 260 | t.Errorf("InstallHooks with a stale config.lock = %v, want an error enabling extensions.worktreeConfig", err) |
| 261 | } |
| 262 | }) |
| 263 | } |
| 264 | |
| 265 | // writeRepoHook installs hooks in dir: a commit-msg hook that appends a |
| 266 | // trailer and saves the message it was given to seen, and a pre-commit hook |
| 267 | // that saves the staged a.txt to seen.pre. |
| 268 | func writeRepoHook(t *testing.T, dir, seen string) { |
| 269 | t.Helper() |
| 270 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 271 | t.Fatal(err) |
| 272 | } |
| 273 | script := "#!/bin/sh\ncp \"$1\" '" + seen + "'\nprintf 'Repo-Hook: ran\\n' >> \"$1\"\n" |
| 274 | if err := os.WriteFile(filepath.Join(dir, "commit-msg"), []byte(script), 0o755); err != nil { |
| 275 | t.Fatal(err) |
| 276 | } |
| 277 | script = "#!/bin/sh\ngit show :a.txt > '" + seen + ".pre'\n" |
| 278 | if err := os.WriteFile(filepath.Join(dir, "pre-commit"), []byte(script), 0o755); err != nil { |
| 279 | t.Fatal(err) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | func TestInstallHooks_ChainsRepositoryHook(t *testing.T) { |
| 284 | for _, tc := range []struct { |
| 285 | name string |
| 286 | hooks func(clone string) string // where the repository's hook lives |
| 287 | }{ |
| 288 | {"common hooks dir", func(clone string) string { return filepath.Join(clone, ".git", "hooks") }}, |
| 289 | {"shared core.hooksPath", func(clone string) string { |
| 290 | dir := filepath.Join(filepath.Dir(clone), "repo-hooks") |
| 291 | mustGit(t, clone, "config", "core.hooksPath", dir) |
| 292 | return dir |
| 293 | }}, |
| 294 | } { |
| 295 | t.Run(tc.name, func(t *testing.T) { |
| 296 | clone := testClone(t) |
| 297 | seen := filepath.Join(t.TempDir(), "seen") |
| 298 | writeRepoHook(t, tc.hooks(clone), seen) |
| 299 | wt := addWorktree(t, clone, "run-a") |
| 300 | upcase := []string{"sh", "-c", "tr a-z A-Z < a.txt > a.tmp && mv a.tmp a.txt"} |
| 301 | if err := InstallHooks(context.Background(), wt, Provenance{RunID: testRunA, ChangeID: testChangeID}, upcase); err != nil { |
| 302 | t.Fatalf("InstallHooks: %v", err) |
| 303 | } |
| 304 | |
| 305 | commitFile(t, wt, "a.txt", "change\n\nCo-Authored-By: Claude <noreply@anthropic.com>") |
| 306 | |
| 307 | if got, err := os.ReadFile(seen + ".pre"); err != nil || string(got) != "A.TXT\n" { |
| 308 | t.Errorf("repository pre-commit hook should run after the formatter and see a.txt formatted, saw %q (%v)", got, err) |
| 309 | } |
| 310 | |
| 311 | got, err := os.ReadFile(seen) |
| 312 | if err != nil { |
| 313 | t.Fatalf("repository hook did not run: %v", err) |
| 314 | } |
| 315 | if !strings.Contains(string(got), "Klaus-Run: "+testRunA) || strings.Contains(string(got), "Claude") { |
| 316 | t.Errorf("repository hook should run after klaus's, but saw:\n%s", got) |
| 317 | } |
| 318 | if msg := headMessage(t, wt); !strings.HasSuffix(msg, "Repo-Hook: ran") { |
| 319 | t.Errorf("commit should carry the repository hook's edit:\n%s", msg) |
| 320 | } |
| 321 | }) |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | func TestInstallHooks_ProvenanceTrailers(t *testing.T) { |
| 326 | clone := testClone(t) |
| 327 | wt := addWorktree(t, clone, "run-a") |
| 328 | install(t, wt, Provenance{RunID: testRunA, ChangeID: testChangeID}) |
| 329 | |
| 330 | commitFile(t, wt, "a.txt", "add a\n\nBody text.") |
| 331 | want := "add a\n\nBody text.\n\nChange-Id: " + testChangeID + "\nKlaus-Run: " + testRunA |
| 332 | if msg := headMessage(t, wt); msg != want { |
| 333 | t.Errorf("message =\n%s\nwant\n%s", msg, want) |
| 334 | } |
| 335 | |
| 336 | // A later run on the same change amends the commit. |
| 337 | install(t, wt, Provenance{RunID: testRunB, ChangeID: testChangeID}) |
| 338 | if err := os.WriteFile(filepath.Join(wt, "a.txt"), []byte("amended\n"), 0o644); err != nil { |
| 339 | t.Fatal(err) |
| 340 | } |
| 341 | mustGit(t, wt, "commit", "--quiet", "-a", "--amend", "--no-edit") |
| 342 | if got := trailerValues(t, wt, "Change-Id"); len(got) != 1 || got[0] != testChangeID { |
| 343 | t.Errorf("Change-Id = %v, want one %s", got, testChangeID) |
| 344 | } |
| 345 | if got := trailerValues(t, wt, "Klaus-Run"); len(got) != 2 || got[0] != testRunA || got[1] != testRunB { |
| 346 | t.Errorf("Klaus-Run = %v, want [%s %s]", got, testRunA, testRunB) |
| 347 | } |
| 348 | |
| 349 | // The same run amending again adds nothing. |
| 350 | mustGit(t, wt, "commit", "--quiet", "--amend", "--no-edit") |
| 351 | if got := trailerValues(t, wt, "Klaus-Run"); len(got) != 2 { |
| 352 | t.Errorf("Klaus-Run = %v after a same-run amend, want 2 entries", got) |
| 353 | } |
| 354 | |
| 355 | // An empty message still aborts the commit instead of becoming trailers. |
| 356 | cmd := exec.Command("git", "commit", "--allow-empty", "-m", "") |
| 357 | cmd.Dir = wt |
| 358 | if out, err := cmd.CombinedOutput(); err == nil { |
| 359 | t.Errorf("empty-message commit should abort, got success:\n%s\n%s", out, headMessage(t, wt)) |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | // TestInstallHooks_AttributionAndTrailers checks attribution stripping |
| 364 | // and the trailers together: the stripped lines go, a human co-author stays in |
| 365 | // the trailer block, and the provenance trailers join it. |
| 366 | func TestInstallHooks_AttributionAndTrailers(t *testing.T) { |
| 367 | clone := testClone(t) |
| 368 | wt := addWorktree(t, clone, "run-a") |
| 369 | install(t, wt, Provenance{RunID: testRunA, ChangeID: testChangeID}) |
| 370 | |
| 371 | commitFile(t, wt, "a.txt", "fix bug\n\n"+ |
| 372 | "Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>\n"+ |
| 373 | "Co-Authored-By: Alice Smith <alice@example.com>\n"+ |
| 374 | "🤖 Generated with Claude Code") |
| 375 | |
| 376 | want := "fix bug\n\nCo-Authored-By: Alice Smith <alice@example.com>\nChange-Id: " + testChangeID + "\nKlaus-Run: " + testRunA |
| 377 | if msg := headMessage(t, wt); msg != want { |
| 378 | t.Errorf("message =\n%s\nwant\n%s", msg, want) |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | func TestInstallHooks_RejectsMainWorktree(t *testing.T) { |
| 383 | clone := testClone(t) |
| 384 | if err := InstallHooks(context.Background(), clone, Provenance{}, nil); err == nil { |
| 385 | t.Fatal("installing in the main worktree should fail: its hooks dir is the repository's own") |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | func TestCommitChangeID(t *testing.T) { |
| 390 | clone := testClone(t) |
| 391 | wt := addWorktree(t, clone, "run-a") |
| 392 | ctx := context.Background() |
| 393 | if id, err := CommitChangeID(ctx, wt, "HEAD"); err != nil || id != "" { |
| 394 | t.Errorf("CommitChangeID on an unstamped commit = %q, %v; want empty", id, err) |
| 395 | } |
| 396 | install(t, wt, Provenance{RunID: testRunA, ChangeID: testChangeID}) |
| 397 | commitFile(t, wt, "a.txt", "add a") |
| 398 | if id, err := CommitChangeID(ctx, wt, "HEAD"); err != nil || id != testChangeID { |
| 399 | t.Errorf("CommitChangeID = %q, %v; want %s", id, err, testChangeID) |
| 400 | } |
| 401 | } |