From bc613d8aaa0aa2ea38c8491e9cee1506a33bf778 Mon Sep 17 00:00:00 2001 From: matt wilkie Date: Sun, 12 Apr 2026 14:45:43 -0700 Subject: [PATCH] fix(hooks): sanitize husky hooks when copied into beads-managed dir (GH#3132) (#3208) When `bd init` chains existing husky hooks into `.beads/hooks/`, it blindly copied per-hook files whose `. "$(dirname "$0")/_/husky.sh"` (v8) or `. "$(dirname "$0")/h"` (v9) source line dangles in the new location. Result: v8 commits fail loudly with `husky.sh: No such file or directory`; v9 commits silently no-op because husky's dispatcher resolves to `.beads/` (does not exist) and exits 0, skipping all of the user's lint-staged / formatter / etc. commands. Detect husky source dirs and rewrite hook bodies to drop the helper source line, injecting `node_modules/.bin` on PATH so `npx` and project-local binaries continue to resolve. Skip copying husky's `h` and `husky.sh` dispatchers, which are no longer needed once hooks are inlined. --- cmd/bd/hooks.go | 130 ++++++++++++++++++++++++++- cmd/bd/hooks_husky_test.go | 178 +++++++++++++++++++++++++++++++++++++ 2 files changed, 307 insertions(+), 1 deletion(-) create mode 100644 cmd/bd/hooks_husky_test.go diff --git a/cmd/bd/hooks.go b/cmd/bd/hooks.go index 46ad9c925..16644be7a 100644 --- a/cmd/bd/hooks.go +++ b/cmd/bd/hooks.go @@ -681,6 +681,15 @@ func preservePreexistingHooks(targetDir string) { } } + // Detect whether the source hooks live inside a husky directory. Husky v8 + // hooks source `.husky/_/husky.sh`; husky v9 hooks source `.husky/_/h`. + // When the copy target is a beads-managed directory (e.g. .beads/hooks/), + // those sourced helpers are not present relative to the copied hook, so + // we must either also copy the helpers or rewrite the hooks to not need + // them. We choose the latter: inline-sanitize the hook body and skip the + // dispatcher files entirely. (GH#3132) + fromHusky := isHuskyDir(currentDir) + // Copy all hooks from the source directory, not just managed ones. entries, err := os.ReadDir(currentDir) if err != nil { @@ -692,6 +701,18 @@ func preservePreexistingHooks(targetDir string) { continue } + // Husky v9 installs a dispatcher named `h` alongside per-hook files; + // it relies on husky's `.husky/_/` path layout to locate the + // "real" hook. Once we inline the hook bodies below the dispatcher + // is no longer needed (and would silently no-op if copied). Skip it. + if fromHusky && entry.Name() == "h" { + continue + } + // husky.sh (v8 helper) is similarly useless once hooks are inlined. + if fromHusky && entry.Name() == "husky.sh" { + continue + } + srcPath := filepath.Join(currentDir, entry.Name()) // #nosec G304 -- hook path constrained to known hooks directories content, err := os.ReadFile(srcPath) @@ -706,6 +727,13 @@ func preservePreexistingHooks(targetDir string) { continue } + // If this came from a husky directory, rewrite the hook so it no + // longer depends on husky's helper layout being mirrored into the + // target directory. See sanitizeHuskyHook below for details. + if fromHusky { + contentStr = sanitizeHuskyHook(contentStr) + } + // Don't overwrite existing files in target dstPath := filepath.Join(targetDir, entry.Name()) if _, err := os.Stat(dstPath); err == nil { @@ -713,7 +741,7 @@ func preservePreexistingHooks(targetDir string) { } // #nosec G306 -- git hooks must be executable - if err := os.WriteFile(dstPath, content, 0755); err != nil { + if err := os.WriteFile(dstPath, []byte(contentStr), 0755); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to preserve %s hook from %s: %v\n", entry.Name(), currentDir, err) continue } @@ -721,6 +749,106 @@ func preservePreexistingHooks(targetDir string) { } } +// isHuskyDir reports whether dir looks like a husky-managed hooks directory +// (either `.husky` itself or `.husky/_`, the helper dir used by v9). +func isHuskyDir(dir string) bool { + if dir == "" { + return false + } + base := filepath.Base(dir) + parent := filepath.Base(filepath.Dir(dir)) + if base == ".husky" { + return true + } + // .husky/_ (husky v9 helper directory that is sometimes set as + // core.hooksPath directly). + if base == "_" && parent == ".husky" { + return true + } + return false +} + +// sanitizeHuskyHook rewrites a husky hook body so it can run standalone +// without the `.husky/_/husky.sh` (v8) or `.husky/_/h` (v9) helper being +// reachable relative to $0. It removes the helper-source line and prepends +// `node_modules/.bin` to PATH so that tools like `npx`, `lint-staged`, and +// project-local binaries continue to resolve — which is what husky v9's `h` +// normally does for the user. (GH#3132) +// +// Hooks that don't look like husky hooks are returned unchanged. +func sanitizeHuskyHook(content string) string { + // Normalize CRLF first so our line-by-line rewrite works on + // Windows-authored hooks too. + normalized := strings.ReplaceAll(content, "\r\n", "\n") + + lines := strings.Split(normalized, "\n") + out := make([]string, 0, len(lines)+2) + sourcedHelper := false + + for _, line := range lines { + trimmed := strings.TrimSpace(line) + // Match husky v8 helper: `. "$(dirname -- "$0")/_/husky.sh"` and + // common variants (single-quoted, no `--`, `source` instead of `.`). + if isHuskyHelperSourceLine(trimmed) { + sourcedHelper = true + // Drop the line entirely. + continue + } + out = append(out, line) + } + + if !sourcedHelper { + // Not recognizably a husky-sourcing hook — leave it alone. + return content + } + + // Rebuild, injecting a PATH export right after the shebang (if any) so + // that `npx`, `lint-staged`, etc. keep working. Husky v9's `h` normally + // does this for the user. + result := make([]string, 0, len(out)+2) + injected := false + pathLine := `export PATH="$PWD/node_modules/.bin:$PATH"` + + for i, line := range out { + result = append(result, line) + if !injected && i == 0 && strings.HasPrefix(strings.TrimSpace(line), "#!") { + result = append(result, "# Injected by beads (GH#3132): husky helper layout not mirrored into this dir.") + result = append(result, pathLine) + injected = true + } + } + if !injected { + // No shebang — inject at the top. + result = append([]string{pathLine}, result...) + } + + return strings.Join(result, "\n") +} + +// isHuskyHelperSourceLine reports whether line (already trimmed) sources one +// of the husky helper scripts. Matches husky v8 (`_/husky.sh`) and husky v9 +// (`/h`) dispatchers, tolerating quoting and `source` vs `.` variants. +func isHuskyHelperSourceLine(line string) bool { + if line == "" { + return false + } + // Must start with POSIX source (`. `) or bash `source `. + if !strings.HasPrefix(line, ". ") && !strings.HasPrefix(line, "source ") { + return false + } + // v8: references `/_/husky.sh` + if strings.Contains(line, "/_/husky.sh") || strings.Contains(line, `\_\husky.sh`) { + return true + } + // v9: `. "$(dirname "$0")/h"` (or with `--` / single quotes). + // Require both `dirname` and a trailing `/h"` or `/h'` to avoid matching + // unrelated sourcing of files that happen to end in "h". + if strings.Contains(line, "dirname") && (strings.HasSuffix(line, `/h"`) || strings.HasSuffix(line, `/h'`) || strings.HasSuffix(line, "/h")) { + return true + } + return false +} + func configureSharedHooksPath() error { // Set git config core.hooksPath to an absolute path pointing to .beads-hooks. // Using an absolute path is critical for git worktrees (GH#2414): diff --git a/cmd/bd/hooks_husky_test.go b/cmd/bd/hooks_husky_test.go new file mode 100644 index 000000000..39b78c46d --- /dev/null +++ b/cmd/bd/hooks_husky_test.go @@ -0,0 +1,178 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// TestSanitizeHuskyHook_V8 verifies that husky v8's `_/husky.sh` source line +// is stripped and replaced with a PATH export, so the hook runs standalone +// without needing `.beads/hooks/_/husky.sh` to exist. (GH#3132) +func TestSanitizeHuskyHook_V8(t *testing.T) { + in := `#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npx lint-staged +` + out := sanitizeHuskyHook(in) + + if strings.Contains(out, "_/husky.sh") { + t.Errorf("expected husky.sh source line stripped, got:\n%s", out) + } + if !strings.Contains(out, "npx lint-staged") { + t.Errorf("expected user commands preserved, got:\n%s", out) + } + if !strings.Contains(out, `export PATH="$PWD/node_modules/.bin:$PATH"`) { + t.Errorf("expected PATH export injected, got:\n%s", out) + } + if !strings.HasPrefix(out, "#!/usr/bin/env sh") { + t.Errorf("expected shebang preserved at top, got:\n%s", out) + } +} + +// TestSanitizeHuskyHook_V9 verifies that husky v9's `. "$(dirname "$0")/h"` +// dispatcher-source line is stripped. (GH#3132) +func TestSanitizeHuskyHook_V9(t *testing.T) { + in := `#!/usr/bin/env sh +. "$(dirname "$0")/h" + +npm run minify-templates +npx lint-staged --allow-empty +` + out := sanitizeHuskyHook(in) + + if strings.Contains(out, `/h"`) && strings.Contains(out, "dirname") { + // Both markers present on the same line would mean we didn't strip. + for _, line := range strings.Split(out, "\n") { + if strings.Contains(line, "dirname") && strings.Contains(line, `/h"`) { + t.Errorf("expected v9 dispatcher source line stripped, found: %q", line) + } + } + } + if !strings.Contains(out, "npm run minify-templates") { + t.Errorf("expected user commands preserved, got:\n%s", out) + } + if !strings.Contains(out, "npx lint-staged --allow-empty") { + t.Errorf("expected user commands preserved, got:\n%s", out) + } + if !strings.Contains(out, `export PATH="$PWD/node_modules/.bin:$PATH"`) { + t.Errorf("expected PATH export injected for v9, got:\n%s", out) + } +} + +// TestSanitizeHuskyHook_NonHusky verifies we don't mangle hooks that don't +// look like husky hooks. +func TestSanitizeHuskyHook_NonHusky(t *testing.T) { + in := `#!/bin/sh +echo "hello" +make test +` + out := sanitizeHuskyHook(in) + if out != in { + t.Errorf("non-husky hook should be returned unchanged.\ninput:\n%s\noutput:\n%s", in, out) + } +} + +// TestIsHuskyHelperSourceLine checks the matcher for both husky versions. +func TestIsHuskyHelperSourceLine(t *testing.T) { + tests := []struct { + line string + want bool + }{ + {`. "$(dirname -- "$0")/_/husky.sh"`, true}, + {`. "$(dirname "$0")/_/husky.sh"`, true}, + {`source "$(dirname "$0")/_/husky.sh"`, true}, + {`. "$(dirname "$0")/h"`, true}, + {`. "$(dirname -- "$0")/h"`, true}, + // Shouldn't match: + {`echo hello`, false}, + {`. ./config.sh`, false}, + {`# . "$(dirname "$0")/h"`, false}, // commented out (doesn't start with `. `) + {``, false}, + } + for _, tc := range tests { + got := isHuskyHelperSourceLine(strings.TrimSpace(tc.line)) + if got != tc.want { + t.Errorf("isHuskyHelperSourceLine(%q) = %v, want %v", tc.line, got, tc.want) + } + } +} + +// TestIsHuskyDir verifies .husky and .husky/_ detection. +func TestIsHuskyDir(t *testing.T) { + tests := []struct { + path string + want bool + }{ + {"/repo/.husky", true}, + {"/repo/.husky/_", true}, + {".husky", true}, + {"/repo/.git/hooks", false}, + {"/repo/.beads/hooks", false}, + {"", false}, + } + for _, tc := range tests { + got := isHuskyDir(tc.path) + if got != tc.want { + t.Errorf("isHuskyDir(%q) = %v, want %v", tc.path, got, tc.want) + } + } +} + +// TestSanitizeHuskyHook_EndToEnd simulates the file write path: write a +// husky-style hook, sanitize it, write the result, and verify the written +// file would execute standalone. (We don't actually exec — just assert the +// content no longer references the husky helpers.) +func TestSanitizeHuskyHook_EndToEnd(t *testing.T) { + tmp := t.TempDir() + huskyDir := filepath.Join(tmp, ".husky") + if err := os.MkdirAll(huskyDir, 0755); err != nil { + t.Fatal(err) + } + + huskyHook := `#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npx --no-install lint-staged +` + srcPath := filepath.Join(huskyDir, "pre-commit") + // #nosec G306 - test file + if err := os.WriteFile(srcPath, []byte(huskyHook), 0755); err != nil { + t.Fatal(err) + } + + // Simulate what preservePreexistingHooks does: read, sanitize, write. + content, err := os.ReadFile(srcPath) // #nosec G304 - test path + if err != nil { + t.Fatal(err) + } + sanitized := content + if isHuskyDir(huskyDir) { + sanitized = []byte(sanitizeHuskyHook(string(content))) + } + + targetDir := filepath.Join(tmp, ".beads", "hooks") + if err := os.MkdirAll(targetDir, 0755); err != nil { + t.Fatal(err) + } + dstPath := filepath.Join(targetDir, "pre-commit") + // #nosec G306 - test file + if err := os.WriteFile(dstPath, sanitized, 0755); err != nil { + t.Fatal(err) + } + + // Verify written content. + written, err := os.ReadFile(dstPath) // #nosec G304 - test path + if err != nil { + t.Fatal(err) + } + got := string(written) + if strings.Contains(got, "_/husky.sh") { + t.Errorf("preserved hook still references _/husky.sh; would break commits.\n%s", got) + } + if !strings.Contains(got, "lint-staged") { + t.Errorf("preserved hook lost user command.\n%s", got) + } +}