gunk-dev/the-valley

hook_test.go

sourcec14b0e68e9c3main's published tip history
16.3 KiB
1package git
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
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
404func TestCommitRunID(t *testing.T) {
405 ctx := context.Background()
406 cases := []struct {
407 name string
408 msg string
409 wantID string
410 wantErrIs error
411 wantErrSub []string
412 }{
413 {
414 name: "no run trailer",
415 msg: "plain commit",
416 wantID: "",
417 },
418 {
419 name: "legacy Klaus-Run only",
420 msg: "add a\n\nKlaus-Run: " + testRunA,
421 wantID: testRunA,
422 },
423 {
424 name: "new Flow-Run only",
425 msg: "add b\n\nFlow-Run: " + testRunA,
426 wantID: testRunA,
427 },
428 {
429 name: "case-insensitive keys",
430 msg: "add c\n\nflow-run: " + testRunA,
431 wantID: testRunA,
432 },
433 {
434 name: "both present and agreeing",
435 msg: "add d\n\nKlaus-Run: " + testRunA + "\nFlow-Run: " + testRunA,
436 wantID: testRunA,
437 },
438 {
439 name: "both present and disagreeing yields none with error",
440 msg: "add e\n\nKlaus-Run: " + testRunA + "\nFlow-Run: " + testRunB,
441 wantID: "",
442 wantErrIs: ErrConflictingRunTrailers,
443 wantErrSub: []string{testRunA, testRunB},
444 },
445 {
446 name: "empty Flow-Run with nonempty Klaus-Run disagrees",
447 msg: "add f\n\nKlaus-Run: " + testRunA + "\nFlow-Run:",
448 wantID: "",
449 wantErrIs: ErrConflictingRunTrailers,
450 wantErrSub: []string{testRunA},
451 },
452 }
453
454 for _, tc := range cases {
455 t.Run(tc.name, func(t *testing.T) {
456 clone := testClone(t)
457 wt := addWorktree(t, clone, "run-id-test")
458 commitFile(t, wt, "f.txt", tc.msg)
459
460 got, err := CommitRunID(ctx, wt, "HEAD")
461 if tc.wantErrIs != nil {
462 if !errors.Is(err, tc.wantErrIs) {
463 t.Fatalf("err = %v, want errors.Is(_, %v)", err, tc.wantErrIs)
464 }
465 for _, sub := range tc.wantErrSub {
466 if !strings.Contains(err.Error(), sub) {
467 t.Errorf("err %q missing %q", err.Error(), sub)
468 }
469 }
470 } else if err != nil {
471 t.Fatalf("CommitRunID error: %v", err)
472 }
473 if got != tc.wantID {
474 t.Errorf("CommitRunID = %q, want %q", got, tc.wantID)
475 }
476 })
477 }
478}