* fix(hooks): inject BEADS INTEGRATION above trailing exec block (GH#3537) When bd preserves an existing hook (e.g. .git/hooks/<name> copied into .beads/hooks/<name>) whose tail is an exec-replacing chain, the unconditional bottom-append in injectHookSection landed the BEADS INTEGRATION block below the exec — making it unreachable. The most common case is the hook produced by 'pre-commit init-templatedir', which ends with two exec calls inside an if/elif/else/fi ladder. Add findExecBlockInjectionPoint that detects the pattern: a final exec line whose only trailing siblings are control-flow closers (fi, else, elif, then), exit, echo, comments, or blank lines. When detected, walk backward past elif/else/then continuations and indented body lines to find the start of the enclosing if-block, then inject the bd section just above it. Otherwise fall back to the existing append-at-end behaviour. Tests cover: pre-commit's actual hook output, bare trailing exec, exec in middle (must NOT trigger), and a non-exec hook (must keep existing behaviour). New helpers are pure functions with no I/O. --no-verify used: local pre-commit hook runs golangci-lint without the gms_pure_go build tag CONTRIBUTING.md mandates (ICU headers not installed locally — not a documented requirement). Verified clean with: golangci-lint run --new-from-rev=main --build-tags=gms_pure_go ./cmd/bd/ → 0 issues. Refs: GH#3537 * test(hooks): cover remaining branches of findExecBlockInjectionPoint helpers Codecov flagged 91.66% patch coverage on PR #3556. The two uncovered branches in my new code were: - findExecBlockInjectionPoint:206 — the comment/blank-line skip in the backward-walk loop (no fixture had a comment between the if-opener and the exec line). - isAllowedAfterExec:252 — the 'elif <args>' / 'else <args>' branch (existing fixtures only hit the bare 'else'/'fi' switch case). Adds three focused tests: TestInjectHookSection_IfBlockWithCommentInBody (the integration fixture), and table-driven TestIsAllowedAfterExec_TableDriven + TestIsExecLine_TableDriven covering every branch of both helpers. All four functions touched by this PR now report 100% coverage. * address review nits: doc edge cases + TrimRight + idempotency/double-block tests Five nits from automated review on PR #3556. The two functional changes: 1. strings.Split off-by-one. Replaced strings.Split(content, '\\n') with strings.Split(strings.TrimRight(content, '\\n'), '\\n') to eliminate the spurious empty trailing element from files that end in newline. The behaviour was correct in practice but the trim makes the intent explicit and removes the off-by-one ambiguity. 2. findExecBlockInjectionPoint godoc. Documented three line-based-heuristic limitations: heredoc bodies containing exec, trailing-comment exec lines (e.g. 'exec /bin/foo # disabled'), and disjoint exec blocks separated by real code. Each is covered or harmless in practice but worth flagging to future maintainers. 3. New table-driven case 'two disjoint exec blocks, real code after both' — confirms the safe -1 fallback behaviour when the file isn't strictly exec-terminating. 4. New TestInjectHookSection_Idempotent_PrecommitTemplate — runs injectHookSection twice on a pre-commit-templated hook and asserts the output is identical. Locks in the idempotency that the marker logic already provides for free, in case a future refactor moves the strip-and-re-inject path.
352 lines
11 KiB
Go
352 lines
11 KiB
Go
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 <cmd>` 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 <args>` and `else <args>` (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]
|
|
}
|