diff --git a/cmd/bd/hooks.go b/cmd/bd/hooks.go index c8c17e8ee..b295078ca 100644 --- a/cmd/bd/hooks.go +++ b/cmd/bd/hooks.go @@ -143,7 +143,16 @@ func injectHookSectionWithDepth(existing, section string, depth int) string { return injectHookSectionWithDepth(cleaned, section, depth+1) } - // Case 3: no markers — append + // Case 3: no markers. If the existing hook ends in an exec-replacing + // block (e.g. the templated hook produced by `pre-commit init-templatedir`, + // which ends with `exec "$INSTALL_PYTHON" -mpre_commit ...`), appending + // at the bottom would make the bd section unreachable. Detect that + // pattern and inject above the exec block instead. (GH#3537) + if injectAt := findExecBlockInjectionPoint(existing); injectAt >= 0 { + return existing[:injectAt] + section + "\n" + existing[injectAt:] + } + + // Case 3 fallback: no markers, no trailing exec — append at end. result := existing if !strings.HasSuffix(result, "\n") { result += "\n" @@ -152,6 +161,122 @@ func injectHookSectionWithDepth(existing, section string, depth int) string { return result } +// findExecBlockInjectionPoint inspects the tail of a hook file. If it ends in +// an exec-replacing chain (a final `exec ` reachable from the bottom of +// the file, possibly inside an `if`/`elif`/`else`/`fi` ladder whose other +// branches only `echo`/`exit`), returns the byte offset where the bd section +// should be injected — i.e. just above the start of the enclosing control +// structure (or above the bare `exec` line if there is none). Returns -1 when +// the file does not end in such a pattern; callers should fall back to +// appending at the bottom. +// +// Motivation: appending below a terminating `exec` makes the appended content +// unreachable, because `exec` replaces the running shell process. (GH#3537) +// +// Limitations (the function uses line-based heuristics, not a shell parser): +// - A heredoc body containing a literal line that starts with `exec` is +// treated as code, not data. In practice this is harmless because the +// terminator line (e.g. `EOF`) is then classified as non-filler and the +// scan returns -1, but a contrived terminator name could fool it. +// - A trailing comment on an `exec` line (e.g. `exec /bin/foo # disabled`) +// is treated as a live `exec` statement. Use a separate comment line if +// intent is to disable it. +// - Two disjoint `if/exec` blocks separated by real code: the scan only +// considers the LAST one; the real code in the middle correctly causes +// the scan to return -1 and the caller falls back to append. +func findExecBlockInjectionPoint(content string) int { + // Trim a trailing newline so strings.Split doesn't produce an empty + // sentinel as the last element. The scan then sees lines exactly as + // they appear in the file with no off-by-one ambiguity. + lines := strings.Split(strings.TrimRight(content, "\n"), "\n") + + // 1. Find the last line that is an effective `exec ...` statement. + // Skip blank lines, comments, and the standard tail patterns + // (`fi`, `else`, `elif`, `exit N`, `echo ...`) when scanning back. + lastExecLine := -1 + for i := len(lines) - 1; i >= 0; i-- { + trimmed := strings.TrimSpace(lines[i]) + if isExecLine(trimmed) { + lastExecLine = i + break + } + if !isAllowedAfterExec(trimmed) { + // Found non-trivial code at the tail that isn't part of an + // exec-terminated chain — not a pattern we should rewrite. + return -1 + } + } + if lastExecLine == -1 { + return -1 + } + + // 2. Walk backward from lastExecLine to find the start of the enclosing + // control structure (an `if ...` at column 0, possibly preceded by + // elif/else/then continuations of the same block). If we don't find + // one, treat the exec line itself as the injection target. + blockStartLine := lastExecLine + for i := lastExecLine - 1; i >= 0; i-- { + line := lines[i] + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "#") { + continue + } + // Skip continuations of the if-block we're inside: elif/else/then, + // and any indented body line (they belong to the surrounding block). + if strings.HasPrefix(trimmed, "elif ") || trimmed == "else" || + strings.HasPrefix(trimmed, "else ") || trimmed == "then" { + continue + } + if line != trimmed { // indented body of an enclosing block + continue + } + // Column-0 line that isn't a continuation. If it opens an if-block, + // that's the start of our construct. + if strings.HasPrefix(trimmed, "if ") { + blockStartLine = i + } + break + } + + // 3. Convert blockStartLine -> byte offset. + offset := 0 + for i := 0; i < blockStartLine; i++ { + offset += len(lines[i]) + 1 // +1 for the '\n' that strings.Split removed + } + return offset +} + +// isExecLine reports whether trimmed is an effective `exec ` statement. +func isExecLine(trimmed string) bool { + return trimmed == "exec" || strings.HasPrefix(trimmed, "exec ") || + strings.HasPrefix(trimmed, "exec\t") +} + +// isAllowedAfterExec reports whether a trailing line in an exec-terminated +// chain is harmless filler — control-flow closers, alternative branches, +// fallback exits, comments, and blanks. Anything else means the file does +// not strictly terminate via exec, so we should not rewrite it. +func isAllowedAfterExec(trimmed string) bool { + if trimmed == "" || strings.HasPrefix(trimmed, "#") { + return true + } + switch trimmed { + case "fi", "else", "done", "esac", "}", ";;": + return true + } + if strings.HasPrefix(trimmed, "elif ") || strings.HasPrefix(trimmed, "else ") { + return true + } + if strings.HasPrefix(trimmed, "exit") { + return true + } + if strings.HasPrefix(trimmed, "echo ") || strings.HasPrefix(trimmed, "echo\t") { + // pre-commit's else branch prints a hint before exit 1. + return true + } + return false +} + // removeOrphanedBeginBlock removes an orphaned BEGIN block starting at beginIdx. // Scans forward from the BEGIN line to the next blank line, next BEGIN marker, or EOF. func removeOrphanedBeginBlock(content string, beginIdx int) string { diff --git a/cmd/bd/hooks_exec_composition_test.go b/cmd/bd/hooks_exec_composition_test.go new file mode 100644 index 000000000..5737f2215 --- /dev/null +++ b/cmd/bd/hooks_exec_composition_test.go @@ -0,0 +1,352 @@ +package main + +import ( + "strings" + "testing" +) + +// section is a stand-in BEADS INTEGRATION block used in these tests; the +// real generator is generateHookSection but the injection logic doesn't care +// about the contents — it only cares about marker presence and placement. +const testBeadsSection = `# --- BEGIN BEADS INTEGRATION v1.2.3 --- +if command -v bd >/dev/null 2>&1; then + bd hooks run pre-commit "$@" +fi +# --- END BEADS INTEGRATION v1.2.3 --- +` + +// TestInjectHookSection_PrecommitTemplatedHook reproduces GH#3537: bd's +// section must NOT be appended below pre-commit's templated hook (which ends +// in `exec`), because exec replaces the running shell — anything below it +// is unreachable. The bd section must be injected ABOVE the exec block so +// it actually runs on every commit. +func TestInjectHookSection_PrecommitTemplatedHook(t *testing.T) { + // Faithful reproduction of pre-commit init-templatedir's hook output. + existing := `#!/usr/bin/env bash +# File generated by pre-commit: https://pre-commit.com +# ID: 138fd403232d2ddd5efb44317e38bf03 + +# start templated +INSTALL_PYTHON='/opt/homebrew/Cellar/pre-commit/4.6.0/libexec/bin/python' +ARGS=(hook-impl --config=.pre-commit-config.yaml --hook-type=pre-commit) +# end templated + +HERE="$(cd "$(dirname "$0")" && pwd)" +ARGS+=(--hook-dir "$HERE" -- "$@") + +if [ -x "$INSTALL_PYTHON" ]; then + exec "$INSTALL_PYTHON" -mpre_commit "${ARGS[@]}" +elif command -v pre-commit > /dev/null; then + exec pre-commit "${ARGS[@]}" +else + echo '` + "`pre-commit`" + ` not found. Did you forget to activate your virtualenv?' 1>&2 + exit 1 +fi +` + + out := injectHookSection(existing, testBeadsSection) + + beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION") + if beadsIdx == -1 { + t.Fatalf("bd section not present in result:\n%s", out) + } + + ifIdx := strings.Index(out, `if [ -x "$INSTALL_PYTHON" ]`) + if ifIdx == -1 { + t.Fatalf("expected pre-commit's `if` block to remain, got:\n%s", out) + } + + if beadsIdx >= ifIdx { + t.Errorf("bd section was injected BELOW the exec block (unreachable). "+ + "beads at byte %d, if-block at byte %d. Full output:\n%s", + beadsIdx, ifIdx, out) + } + + if !strings.Contains(out, `exec "$INSTALL_PYTHON" -mpre_commit`) || + !strings.Contains(out, `exec pre-commit "${ARGS[@]}"`) { + t.Errorf("expected both exec lines to be preserved, got:\n%s", out) + } +} + +// TestInjectHookSection_StandaloneTrailingExec covers a hook that simply ends +// in a bare `exec ` with no enclosing if/case. The section should be +// injected directly above the exec line. +func TestInjectHookSection_StandaloneTrailingExec(t *testing.T) { + existing := `#!/bin/sh +echo "user setup" +exec /usr/local/bin/some-tool "$@" +` + out := injectHookSection(existing, testBeadsSection) + + beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION") + execIdx := strings.Index(out, "exec /usr/local/bin/some-tool") + if beadsIdx == -1 || execIdx == -1 { + t.Fatalf("missing markers in output:\n%s", out) + } + if beadsIdx >= execIdx { + t.Errorf("bd section was injected BELOW exec (unreachable):\n%s", out) + } + if !strings.Contains(out, `echo "user setup"`) { + t.Errorf("expected user setup line preserved, got:\n%s", out) + } +} + +// TestInjectHookSection_NonExecHookAppendsAtEnd is the regression guard: +// hooks that don't end in exec must keep the existing append-at-bottom +// behaviour so we don't change semantics for the common case. +func TestInjectHookSection_NonExecHookAppendsAtEnd(t *testing.T) { + existing := `#!/bin/sh +echo "user hook" +some-other-command +` + out := injectHookSection(existing, testBeadsSection) + + // User content must come before the bd section. + userIdx := strings.Index(out, "some-other-command") + beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION") + if userIdx == -1 || beadsIdx == -1 { + t.Fatalf("missing markers:\n%s", out) + } + if userIdx >= beadsIdx { + t.Errorf("expected bd section appended after user content, got:\n%s", out) + } +} + +// TestInjectHookSection_ExecInMiddleStillAppends covers the case where a hook +// has an exec call somewhere in the middle but real code follows. We should +// NOT rewrite that — falling back to append is correct. +func TestInjectHookSection_ExecInMiddleStillAppends(t *testing.T) { + existing := `#!/bin/sh +if [ "$1" = "--reload" ]; then + exec "$0" +fi +echo "running normal commit checks" +some-other-command "$@" +` + out := injectHookSection(existing, testBeadsSection) + + beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION") + echoIdx := strings.Index(out, `echo "running normal commit checks"`) + if beadsIdx == -1 || echoIdx == -1 { + t.Fatalf("missing markers:\n%s", out) + } + if beadsIdx <= echoIdx { + t.Errorf("bd section should be appended after non-trivial trailing code, got:\n%s", out) + } +} + +// TestFindExecBlockInjectionPoint_TableDriven exercises the helper directly +// with a small set of representative inputs. +func TestFindExecBlockInjectionPoint_TableDriven(t *testing.T) { + tests := []struct { + name string + content string + // wantInject is the substring expected at (or just after) the returned + // byte offset; -1 sentinel via wantNegative=true. + wantPrefix string + wantNegative bool + }{ + { + name: "empty file", + // no exec at all + content: "", + wantNegative: true, + }, + { + name: "just shebang and echo", + content: "#!/bin/sh\necho hi\n", + wantNegative: true, + }, + { + name: "bare trailing exec", + content: "#!/bin/sh\necho before\nexec /bin/something\n", + wantPrefix: "exec /bin/something", + }, + { + name: "if-elif-else-exec ladder", + content: `#!/usr/bin/env bash +echo top +if [ -x /a ]; then + exec /a +elif command -v b > /dev/null; then + exec b +else + echo missing 1>&2 + exit 1 +fi +`, + wantPrefix: "if [ -x /a ]", + }, + { + name: "exec in middle, normal code follows", + content: `#!/bin/sh +if [ "$1" = "x" ]; then exec "$0"; fi +echo continues +do-stuff +`, + wantNegative: true, + }, + { + // Two disjoint exec blocks with real code after both. The scan + // walks back from EOF, hits `do-stuff` (real code), bails with -1 + // and the caller appends as normal. (review nit on PR #3556) + name: "two disjoint exec blocks, real code after both", + content: `#!/bin/sh +if [ -x /a ]; then exec /a; fi +echo middle +if [ -x /b ]; then exec /b; fi +do-stuff +`, + wantNegative: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := findExecBlockInjectionPoint(tt.content) + if tt.wantNegative { + if got != -1 { + t.Fatalf("want -1, got %d (content slice from offset: %q)", + got, snippet(tt.content, got, 60)) + } + return + } + if got < 0 || got > len(tt.content) { + t.Fatalf("offset %d out of bounds (len %d)", got, len(tt.content)) + } + tail := tt.content[got:] + if !strings.HasPrefix(tail, tt.wantPrefix) { + t.Errorf("want offset at prefix %q, got offset %d → %q", + tt.wantPrefix, got, snippet(tt.content, got, 80)) + } + }) + } +} + +// TestInjectHookSection_IfBlockWithCommentInBody covers the backward-walk +// branch in findExecBlockInjectionPoint where the if-body contains a blank +// line or a comment between the `if ...` opener and the `exec` line. Without +// this fixture the comment/blank skip-and-continue branch is unexercised. +func TestInjectHookSection_IfBlockWithCommentInBody(t *testing.T) { + existing := `#!/bin/sh +echo "before" +if [ -x /usr/local/bin/foo ]; then + # Why we use foo: documented elsewhere. + + exec /usr/local/bin/foo "$@" +fi +` + out := injectHookSection(existing, testBeadsSection) + + beadsIdx := strings.Index(out, "BEGIN BEADS INTEGRATION") + ifIdx := strings.Index(out, "if [ -x /usr/local/bin/foo ]") + if beadsIdx == -1 || ifIdx == -1 { + t.Fatalf("missing markers:\n%s", out) + } + if beadsIdx >= ifIdx { + t.Errorf("bd section should be injected above the if-block (not between if and exec); got:\n%s", out) + } + if !strings.Contains(out, "# Why we use foo") { + t.Errorf("body comment was lost:\n%s", out) + } +} + +// TestInjectHookSection_Idempotent_PrecommitTemplate confirms that running +// injectHookSection twice on a pre-commit-templated hook is idempotent: the +// first run takes Case 3 (no markers → inject above the exec block); the +// second run takes Case 1 (markers present → replace between markers) and +// reuses the same injection point. The output of run 2 must equal run 1. +// (review nit on PR #3556 — guards against a future refactor regressing +// the idempotency that the marker logic currently provides for free.) +func TestInjectHookSection_Idempotent_PrecommitTemplate(t *testing.T) { + existing := `#!/usr/bin/env bash +HERE="$(cd "$(dirname "$0")" && pwd)" +if [ -x "$INSTALL_PYTHON" ]; then + exec "$INSTALL_PYTHON" -mpre_commit "$@" +elif command -v pre-commit > /dev/null; then + exec pre-commit "$@" +else + echo 'not found' 1>&2 + exit 1 +fi +` + once := injectHookSection(existing, testBeadsSection) + twice := injectHookSection(once, testBeadsSection) + if once != twice { + t.Errorf("injectHookSection is not idempotent.\nrun 1:\n%s\nrun 2:\n%s", once, twice) + } + // Sanity: the bd block must still be above the exec block after both runs. + beadsIdx := strings.Index(twice, "BEGIN BEADS INTEGRATION") + ifIdx := strings.Index(twice, `if [ -x "$INSTALL_PYTHON" ]`) + if beadsIdx == -1 || ifIdx == -1 || beadsIdx >= ifIdx { + t.Errorf("after two runs the bd block should still sit above the if-block:\n%s", twice) + } +} + +// TestIsAllowedAfterExec_TableDriven directly exercises every branch of the +// helper, including `elif ` and `else ` (with arguments rather +// than the bare keyword which is handled by the switch above). +func TestIsAllowedAfterExec_TableDriven(t *testing.T) { + tests := []struct { + name string + trimmed string + want bool + }{ + {name: "empty", trimmed: "", want: true}, + {name: "comment", trimmed: "# a comment", want: true}, + {name: "fi", trimmed: "fi", want: true}, + {name: "bare else", trimmed: "else", want: true}, + {name: "done", trimmed: "done", want: true}, + {name: "esac", trimmed: "esac", want: true}, + {name: "close brace", trimmed: "}", want: true}, + {name: "case fallthrough", trimmed: ";;", want: true}, + {name: "elif with cond", trimmed: "elif command -v foo > /dev/null; then", want: true}, + {name: "else with stuff", trimmed: "else stuff-on-same-line", want: true}, + {name: "exit 0", trimmed: "exit 0", want: true}, + {name: "exit no arg", trimmed: "exit", want: true}, + {name: "echo space", trimmed: "echo 'msg'", want: true}, + {name: "real code", trimmed: "do-real-thing arg", want: false}, + {name: "assignment", trimmed: "FOO=bar", want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isAllowedAfterExec(tt.trimmed); got != tt.want { + t.Errorf("isAllowedAfterExec(%q) = %v, want %v", tt.trimmed, got, tt.want) + } + }) + } +} + +// TestIsExecLine_TableDriven covers the helper's tab-prefix branch and a +// few negatives for completeness. +func TestIsExecLine_TableDriven(t *testing.T) { + tests := []struct { + trimmed string + want bool + }{ + {trimmed: "exec /bin/foo", want: true}, + {trimmed: "exec", want: true}, + {trimmed: "exec\t/bin/foo", want: true}, + {trimmed: "execute foo", want: false}, + {trimmed: "echo exec", want: false}, + {trimmed: "", want: false}, + } + for _, tt := range tests { + t.Run(tt.trimmed, func(t *testing.T) { + if got := isExecLine(tt.trimmed); got != tt.want { + t.Errorf("isExecLine(%q) = %v, want %v", tt.trimmed, got, tt.want) + } + }) + } +} + +func snippet(s string, from, n int) string { + if from < 0 || from >= len(s) { + return "" + } + end := from + n + if end > len(s) { + end = len(s) + } + return s[from:end] +}