gunk-dev/the-valley

hook_test.go

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