beads/cmd/bd/preflight_test.go
Julian Knutsen 555b01d789
fix(release): name the version-drift remedies that work (#7083)
Post-merge review follow-up to #5614.

#5614 replaced the shell checker's three-way drift remedy with a bare
"Run: scripts/update-versions.sh <canonical>" in both the Go checker
(status 1) and bd preflight's Version sync output, and the release-tag
pre-push hook kept answering status 1 with "Fix with:
scripts/update-versions.sh <version>". update-versions.sh derives the old
version from cmd/bd/version.go and anchors its substitutions on it, so
with version.go already at the canonical version that re-run rewrites
only the .githooks markers and uv.lock and leaves any other drifted file
as it was.

Restore the remedy as versioncheck.Report.MismatchRemedy, shared by the
checker and preflight:
- one file drifted: edit it to the expected value
- several drifted: set version.go to the previous version, then replay
  scripts/update-versions.sh <canonical>
- version.go is wrong: scripts/update-versions.sh <intended-version>

The hook's status-1 text now points at the checker output instead of
prescribing update-versions.sh; status 3 is unchanged. The text is sized
so one drifted file shows in full within preflight's 500-byte human
output, with the several-files case ahead of the version.go one.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:34:06 -07:00

843 lines
28 KiB
Go

package main
import (
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/testutil/bazeltest"
"github.com/steveyegge/beads/internal/versioncheck"
)
func TestCheckResult_Passed(t *testing.T) {
r := CheckResult{
Name: "Tests pass",
Passed: true,
Command: "go test ./...",
Output: "",
}
if !r.Passed {
t.Error("Expected result to be passed")
}
if r.Name != "Tests pass" {
t.Errorf("Expected name 'Tests pass', got %q", r.Name)
}
}
func TestPrintCheckResult_Failed(t *testing.T) {
r := CheckResult{
Name: "tests",
Passed: false,
Command: "go test ./...",
Output: "--- FAIL: TestSomething\nexpected X got Y",
}
if r.Passed {
t.Error("Expected result to be failed")
}
if !strings.Contains(r.Output, "FAIL") {
t.Error("Expected output to contain FAIL")
}
}
func TestCheckResult_JSONFields(t *testing.T) {
r := CheckResult{
Name: "tests",
Passed: true,
Command: "go test -short ./...",
Output: "ok github.com/example/pkg 0.123s",
}
// Verify JSON struct tags are correct by checking field names
if r.Name == "" {
t.Error("Name should not be empty")
}
if r.Command == "" {
t.Error("Command should not be empty")
}
}
func TestPreflightResult_AllPassed(t *testing.T) {
results := PreflightResult{
Checks: []CheckResult{
{Name: "Tests pass", Passed: true, Command: "go test ./..."},
{Name: "Lint passes", Passed: true, Command: "golangci-lint run"},
},
Passed: true,
Summary: "2/2 checks passed",
}
if !results.Passed {
t.Error("Expected all checks to pass")
}
if len(results.Checks) != 2 {
t.Errorf("Expected 2 checks, got %d", len(results.Checks))
}
}
func TestPreflightResult_SomeFailed(t *testing.T) {
results := PreflightResult{
Checks: []CheckResult{
{Name: "Tests pass", Passed: true, Command: "go test ./..."},
{Name: "Lint passes", Passed: false, Command: "golangci-lint run", Output: "linting errors"},
},
Passed: false,
Summary: "1/2 checks passed",
}
if results.Passed {
t.Error("Expected some checks to fail")
}
passCount := 0
failCount := 0
for _, c := range results.Checks {
if c.Passed {
passCount++
} else {
failCount++
}
}
if passCount != 1 || failCount != 1 {
t.Errorf("Expected 1 pass and 1 fail, got %d pass and %d fail", passCount, failCount)
}
}
func TestPreflightResult_WithSkipped(t *testing.T) {
results := PreflightResult{
Checks: []CheckResult{
{Name: "Tests pass", Passed: true, Command: "go test ./..."},
{Name: "Lint passes", Passed: false, Skipped: true, Command: "golangci-lint run", Output: "not installed"},
},
Passed: true,
Summary: "1/1 checks passed (1 skipped)",
}
// Skipped checks don't count as failures
if !results.Passed {
t.Error("Expected result to pass (skipped doesn't count as failure)")
}
skipCount := 0
for _, c := range results.Checks {
if c.Skipped {
skipCount++
}
}
if skipCount != 1 {
t.Errorf("Expected 1 skipped, got %d", skipCount)
}
}
func TestPreflightResult_WithWarning(t *testing.T) {
results := PreflightResult{
Checks: []CheckResult{
{Name: "Tests pass", Passed: true, Command: "go test ./..."},
{Name: "Nix hash current", Passed: false, Warning: true, Command: "git diff HEAD -- go.sum", Output: "go.sum changed"},
},
Passed: true, // Warnings don't fail the overall result
Summary: "1/2 checks passed, 1 warning(s)",
}
// Warnings don't count as failures
if !results.Passed {
t.Error("Expected result to pass (warning doesn't count as failure)")
}
warnCount := 0
for _, c := range results.Checks {
if c.Warning {
warnCount++
}
}
if warnCount != 1 {
t.Errorf("Expected 1 warning, got %d", warnCount)
}
}
func TestTruncateOutput(t *testing.T) {
tests := []struct {
name string
input string
maxLen int
wantTrunc bool
}{
{"short string", "hello world", 500, false},
{"exact length", strings.Repeat("x", 500), 500, false},
{"over length", strings.Repeat("x", 600), 500, true},
{"empty string", "", 500, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := truncateOutput(tt.input, tt.maxLen)
if tt.wantTrunc {
if !strings.Contains(result, "truncated") {
t.Error("Expected truncation marker in output")
}
if len(result) > tt.maxLen+20 { // allow some slack for marker
t.Errorf("Result too long: got %d chars", len(result))
}
} else {
if strings.Contains(result, "truncated") {
t.Error("Did not expect truncation marker")
}
}
})
}
}
func TestRunLintCheck_MissingCommandFailsByDefault(t *testing.T) {
t.Setenv("PATH", "")
result := runLintCheck(false)
if result.Passed {
t.Fatalf("expected lint check to fail when golangci-lint is missing")
}
if result.Skipped {
t.Fatalf("expected missing lint to be a hard failure, not skipped")
}
if !strings.Contains(result.Output, "not found in PATH") {
t.Fatalf("expected missing command message, got: %q", result.Output)
}
if !strings.Contains(result.Output, "--skip-lint") {
t.Fatalf("expected explicit skip guidance in message, got: %q", result.Output)
}
}
func TestRunLintCheck_SkipLintFlag(t *testing.T) {
result := runLintCheck(true)
if result.Passed {
t.Fatalf("expected skipped lint check to remain non-passing")
}
if !result.Skipped {
t.Fatalf("expected skipped lint check to be marked skipped")
}
if !result.Warning {
t.Fatalf("expected skipped lint check to be warning")
}
if !strings.Contains(result.Output, "--skip-lint") {
t.Fatalf("expected output to mention --skip-lint, got: %q", result.Output)
}
}
func TestLintInvocationForRootMatchesChecklistAndProjectType(t *testing.T) {
beads := writeMarkerDir(t, map[string]string{"go.mod": "module github.com/steveyegge/beads\n"})
beadsInvocation := lintInvocationForRoot(beads)
if beadsInvocation.display != beadsPRLintDriverCommand {
t.Fatalf("Beads command = %q, want %q", beadsInvocation.display, beadsPRLintDriverCommand)
}
if beadsInvocation.executable != "go" {
t.Fatalf("Beads executable = %q, want go", beadsInvocation.executable)
}
wantBeadsArgs := []string{"run", "-mod=readonly", "-tags=gms_pure_go", "./scripts/pr-lint"}
if !reflect.DeepEqual(beadsInvocation.args, wantBeadsArgs) {
t.Fatalf("Beads args = %#v, want %#v", beadsInvocation.args, wantBeadsArgs)
}
if beadsInvocation.dir != beads {
t.Fatalf("Beads command dir = %q, want %q", beadsInvocation.dir, beads)
}
if checklist := strings.Join(buildPreflightChecklist(beads), "\n"); !strings.Contains(checklist, "make ci-pr-lint") {
t.Fatalf("Beads checklist does not report supported lint entrypoint:\n%s", checklist)
}
generic := writeMarkerDir(t, map[string]string{"go.mod": "module example.com/generic\n"})
genericInvocation := lintInvocationForRoot(generic)
if genericInvocation.display != "golangci-lint run ./..." {
t.Fatalf("generic command = %q, want direct lint contract", genericInvocation.display)
}
if genericInvocation.executable != "golangci-lint" {
t.Fatalf("generic executable = %q, want golangci-lint", genericInvocation.executable)
}
if want := []string{"run", "./..."}; !reflect.DeepEqual(genericInvocation.args, want) {
t.Fatalf("generic args = %#v, want %#v", genericInvocation.args, want)
}
if checklist := strings.Join(buildPreflightChecklist(generic), "\n"); !strings.Contains(checklist, genericInvocation.display) {
t.Fatalf("generic checklist does not report executable lint command %q:\n%s", genericInvocation.display, checklist)
}
}
func TestRunLintCheckAtBeadsExecutesCheckoutDriverAndReportsJSONCommand(t *testing.T) {
helperDir := t.TempDir()
helperName := "go"
if runtime.GOOS == "windows" {
helperName += ".exe"
}
helperPath := filepath.Join(helperDir, helperName)
if bazeltest.IsBazel() {
fixture, err := bazeltest.RunfileEnv("BEADS_TEST_PREFLIGHT_GO")
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(fixture)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(helperPath, data, 0o755); err != nil {
t.Fatal(err)
}
} else {
realGo, err := exec.LookPath("go")
if err != nil {
t.Fatalf("locate Go toolchain for subprocess fixture: %v", err)
}
build := exec.Command(realGo, "build", "-o", helperPath, "testdata/preflight-go.go")
if output, err := build.CombinedOutput(); err != nil {
t.Fatalf("build fake Go executable: %v\n%s", err, output)
}
}
beads := writeMarkerDir(t, map[string]string{"go.mod": "module github.com/steveyegge/beads\n"})
marker := filepath.Join(t.TempDir(), "invocation.json")
t.Setenv("PATH", helperDir)
t.Setenv("PREFLIGHT_LINT_MARKER", marker)
result := runLintCheckAt(beads, false)
if !result.Passed {
t.Fatalf("checkout lint invocation failed: %s", result.Output)
}
if result.Command != beadsPRLintDriverCommand {
t.Fatalf("reported command = %q, want %q", result.Command, beadsPRLintDriverCommand)
}
if !strings.Contains(result.Output, "synthetic checkout lint success") {
t.Fatalf("missing subprocess output: %q", result.Output)
}
var invocation struct {
Args []string `json:"args"`
Dir string `json:"dir"`
}
markerData, err := os.ReadFile(marker)
if err != nil {
t.Fatalf("read invocation marker: %v", err)
}
if err := json.Unmarshal(markerData, &invocation); err != nil {
t.Fatalf("decode invocation marker: %v", err)
}
wantArgs := []string{"run", "-mod=readonly", "-tags=gms_pure_go", "./scripts/pr-lint"}
if !reflect.DeepEqual(invocation.Args, wantArgs) {
t.Fatalf("subprocess args = %#v, want %#v", invocation.Args, wantArgs)
}
if invocation.Dir != beads {
t.Fatalf("subprocess dir = %q, want checkout root %q", invocation.Dir, beads)
}
encoded, err := json.Marshal(result)
if err != nil {
t.Fatalf("marshal CheckResult: %v", err)
}
var reported CheckResult
if err := json.Unmarshal(encoded, &reported); err != nil {
t.Fatalf("unmarshal CheckResult: %v", err)
}
if reported.Command != beadsPRLintDriverCommand || !reported.Passed {
t.Fatalf("JSON evidence = %#v, want passing checkout driver command", reported)
}
}
// usePreflightGofmt preserves the SDK executable declared by the Bazel target
// while exercising the production PATH lookup in runFmtCheckAt.
func usePreflightGofmt(t *testing.T) {
t.Helper()
if !bazeltest.IsBazel() {
return
}
path, err := bazeltest.RunfileEnv("BEADS_TEST_GOFMT")
if err != nil {
t.Fatal(err)
}
t.Setenv("PATH", filepath.Dir(path)+string(os.PathListSeparator)+os.Getenv("PATH"))
}
func TestRunFmtCheckAtFormattedRoot(t *testing.T) {
usePreflightGofmt(t)
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n\nfunc main() {}\n"), 0o644); err != nil {
t.Fatal(err)
}
result := runFmtCheckAt(dir)
if !result.Passed {
t.Fatalf("formatted root failed: %s", result.Output)
}
}
func TestRunFmtCheckAtFindsUnformattedFileOutsideCallerSubtree(t *testing.T) {
usePreflightGofmt(t)
root := t.TempDir()
callerDir := filepath.Join(root, "nested", "caller")
outsideCaller := filepath.Join(root, "sibling", "bad.go")
if err := os.MkdirAll(callerDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(outsideCaller), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(outsideCaller, []byte("package sibling\nfunc bad( ) { }\n"), 0o644); err != nil {
t.Fatal(err)
}
originalDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir(callerDir); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := os.Chdir(originalDir); err != nil {
t.Errorf("restore working directory: %v", err)
}
})
result := runFmtCheckAt(root)
if result.Passed {
t.Fatal("root formatting check passed despite unformatted sibling file")
}
if !strings.Contains(result.Output, "bad.go") {
t.Fatalf("root formatting check missed sibling file: %s", result.Output)
}
}
func TestRunBeadsPollutionCheck_Clean(t *testing.T) {
// In a clean repo state (no uncommitted .beads changes), the check should pass.
result := runBeadsPollutionCheck()
if !result.Passed {
// If this fails, it means the test environment itself has .beads changes,
// which is valid — skip rather than fail.
if strings.Contains(result.Output, "modified") {
t.Skip("test environment has .beads changes, skipping")
}
if result.Skipped {
t.Skip("cannot determine branch in test environment")
}
t.Fatalf("expected beads pollution check to pass in clean state, got: %q", result.Output)
}
}
func TestRunVersionSyncCheck_GenericFallback(t *testing.T) {
// An unrelated directory retains the generic inline Go/Nix behavior.
origDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "cmd", "bd"), 0o755); err != nil {
t.Fatal(err)
}
for path, content := range map[string]string{
"go.mod": "module example.com/unrelated\n\ngo 1.26.5\n",
"cmd/bd/version.go": "package main\n\nvar Version = \"2.3.4\"\n",
"default.nix": "{ version = \"2.3.4\"; }\n",
} {
if err := os.WriteFile(
filepath.Join(dir, filepath.FromSlash(path)),
[]byte(content),
0o644,
); err != nil {
t.Fatal(err)
}
}
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
defer os.Chdir(origDir)
result := runVersionSyncCheck()
if !result.Passed || result.Skipped {
t.Fatalf("generic version fallback failed: %+v", result)
}
if result.Command != "Compare cmd/bd/version.go and default.nix" {
t.Fatalf("command = %q, want generic fallback", result.Command)
}
if err := os.WriteFile(
filepath.Join(dir, "default.nix"),
[]byte("{ version = \"9.9.9\"; }\n"),
0o644,
); err != nil {
t.Fatal(err)
}
result = runVersionSyncCheck()
if result.Passed || !strings.Contains(result.Output, "version.go=2.3.4, default.nix=9.9.9") {
t.Fatalf("generic mismatch was not preserved: %+v", result)
}
}
func TestRunVersionSyncCheck_BeadsUsesBuiltInAuthority(t *testing.T) {
root := writeBeadsVersionFixture(t, "1.1.0")
// The historical entrypoint is intentionally hostile: production preflight
// must use the Go package directly, not execute this file or ambient bash.
if err := os.WriteFile(
filepath.Join(root, "scripts", "check-versions.sh"),
[]byte("#!/bin/sh\nexit 86\n"),
0o755,
); err != nil {
t.Fatal(err)
}
originalDirectory, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir(root); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(originalDirectory) })
t.Setenv("PATH", "")
result := runVersionSyncCheck()
if !result.Passed {
t.Fatalf("built-in Beads version check failed: %s", result.Output)
}
if result.Command != "built-in Beads release version check" {
t.Fatalf("command = %q, want built-in authority", result.Command)
}
if err := os.WriteFile(
filepath.Join(root, "npm-package", "package.json"),
[]byte(`{"version":"9.9.9"}`),
0o644,
); err != nil {
t.Fatal(err)
}
result = runVersionSyncCheck()
if result.Passed {
t.Fatal("mismatched released metadata unexpectedly passed")
}
if !strings.Contains(result.Output, "npm package.json: 9.9.9 (expected 1.1.0)") {
t.Fatalf("unexpected mismatch output: %q", result.Output)
}
// A bare update-versions.sh re-run no-ops on a drifted file, so the check
// carries the remedies that work, and the human view (which prints the
// first 500 bytes of a failed check) shows all of them for one drift.
remedy := versioncheck.Report{CanonicalVersion: "1.1.0"}.MismatchRemedy()
if !strings.HasSuffix(result.Output, "\n"+remedy) {
t.Fatalf("mismatch output lacks the drift remedy: %q", result.Output)
}
if strings.Contains(result.Output, "Run: scripts/update-versions.sh") {
t.Fatalf("mismatch output prescribes a bare update-versions.sh run: %q", result.Output)
}
if shown := truncateOutput(result.Output, 500); strings.HasSuffix(shown, "(truncated)") {
t.Fatalf("human output cuts the remedy for one drifted file: %q", shown)
}
if err := os.WriteFile(
filepath.Join(root, "npm-package", "package.json"),
[]byte(`{"version":"1.1.0"}`),
0o644,
); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(
filepath.Join(root, ".githooks", "pre-push"),
[]byte(
"# --- BEGIN BEADS INTEGRATION v9.9.9 ---\n"+
"body\n# --- END BEADS INTEGRATION v1.1.0 ---\n",
),
0o755,
); err != nil {
t.Fatal(err)
}
result = runVersionSyncCheck()
if result.Passed {
t.Fatal("mismatched tracked hook marker unexpectedly passed")
}
if !strings.Contains(
result.Output,
".githooks/pre-push BEGIN marker: 9.9.9 (expected 1.1.0)",
) {
t.Fatalf("unexpected tracked-hook mismatch output: %q", result.Output)
}
}
func TestRunBeadsVersionSyncCheck_UVLockFreshness(t *testing.T) {
root := writeBeadsVersionFixture(t, "1.1.0")
tests := []struct {
name string
check versioncheck.UVLockChecker
wantPassed bool
wantContain string
wantAbsent string
}{
{
name: "uv unavailable is a soft skip",
check: func(string) (bool, error) { return false, nil },
wantPassed: true,
wantAbsent: "uv lock --check",
},
{
name: "fresh lock passes",
check: func(string) (bool, error) { return true, nil },
wantPassed: true,
wantContain: "MCP uv.lock: fresh (uv lock --check)",
},
{
name: "stale lock fails",
check: func(string) (bool, error) {
return true, errors.New("lockfile needs regeneration")
},
wantPassed: false,
wantContain: "MCP uv.lock: stale — run: uv lock --directory integrations/beads-mcp",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
result := runBeadsVersionSyncCheckWithUV(root, test.check)
if result.Passed != test.wantPassed {
t.Fatalf("Passed = %v, want %v; result: %+v", result.Passed, test.wantPassed, result)
}
if !strings.Contains(result.Output, test.wantContain) {
t.Fatalf("Output = %q, want substring %q", result.Output, test.wantContain)
}
if test.wantAbsent != "" && strings.Contains(result.Output, test.wantAbsent) {
t.Fatalf("Output = %q, want %q absent", result.Output, test.wantAbsent)
}
})
}
}
func writeBeadsVersionFixture(t *testing.T, version string) string {
t.Helper()
root := t.TempDir()
// The Windows PE numeric fields must be purely numeric, so they carry the
// prerelease-stripped form.
base, _, _ := strings.Cut(version, "-")
files := map[string]string{
"go.mod": "module github.com/steveyegge/beads\n\ngo 1.26.5\n",
"cmd/bd/version.go": "package main\n\nvar Version = \"" + version + "\"\n",
"scripts/update-versions.sh": "#!/bin/sh\n",
"integrations/beads-mcp/pyproject.toml": "[project]\nversion = \"" + version + "\"\n",
"integrations/beads-mcp/src/beads_mcp/__init__.py": "__version__ = \"" + version + "\"\n",
"integrations/beads-mcp/uv.lock": "[[package]]\nname = \"beads-mcp\"\nversion = \"" + version + "\"\n",
"plugins/beads/.claude-plugin/plugin.json": `{"version":"` + version + `"}`,
"plugins/beads/.codex-plugin/plugin.json": `{"version":"` + version + `"}`,
".claude-plugin/marketplace.json": `{"plugins":[{"version":"` + version + `"}]}`,
"npm-package/package.json": `{"version":"` + version + `"}`,
"plugins/beads/.copilot-plugin/plugin.json": `{"version":"` + version + `"}`,
"cmd/bd/winres/winres.json": `{"RT_VERSION":{"#1":{"0000":{` +
`"fixed":{"file_version":"` + base + `","product_version":"` + base + `"},` +
`"info":{"0409":{"FileVersion":"` + version +
`","ProductVersion":"` + version + `"}}}}}}`,
"cmd/bd/winres/manifest.xml": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<assembly>\n <assemblyIdentity\n type=\"win32\"\n" +
" version=\"" + base + ".0\"\n processorArchitecture=\"*\"/>\n</assembly>\n",
".githooks/pre-push": "# --- BEGIN BEADS INTEGRATION v" + version + " ---\n" +
"body\n# --- END BEADS INTEGRATION v" + version + " ---\n",
}
for relativePath, content := range files {
path := filepath.Join(root, filepath.FromSlash(relativePath))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("create parent for %s: %v", relativePath, err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("write %s: %v", relativePath, err)
}
}
return root
}
// writeMarkerDir creates a temp dir containing the given marker files (each
// with trivial content) and returns its path. Used to exercise project-type
// detection in the preflight checklist (GH#4364).
func writeMarkerDir(t *testing.T, files map[string]string) string {
t.Helper()
dir := t.TempDir()
for name, content := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
return dir
}
func TestBuildPreflightChecklist(t *testing.T) {
beadsGoMod := "module github.com/steveyegge/beads\n\ngo 1.22\n"
otherGoMod := "module example.com/foo\n\ngo 1.22\n"
cases := []struct {
name string
files map[string]string
wantContain []string // substring present in at least one item
wantAbsent []string // substring present in no item
}{
{
name: "beads repo keeps rich Go+Nix checklist",
files: map[string]string{"go.mod": beadsGoMod, "default.nix": "{}", ".beads": ""},
wantContain: []string{"gms_pure_go", "Version sync", "Nix hash", "No beads pollution"},
},
{
name: "generic Go project gets plain go commands",
files: map[string]string{"go.mod": otherGoMod},
wantContain: []string{"go test ./...", "golangci-lint run ./...", "gofmt -l ."},
wantAbsent: []string{"gms_pure_go", "Version sync", "Nix hash"},
},
{
name: "node project",
files: map[string]string{"package.json": "{}"},
wantContain: []string{"npm test", "tsc --noEmit"},
wantAbsent: []string{"go test", "gofmt"},
},
{
name: "rust project",
files: map[string]string{"Cargo.toml": "[package]\n"},
wantContain: []string{"cargo test", "cargo clippy"},
wantAbsent: []string{"go test ./...", "npm test"},
},
{
name: "python pyproject",
files: map[string]string{"pyproject.toml": "[project]\n"},
wantContain: []string{"pytest", "ruff check"},
},
{
name: "python setup.py",
files: map[string]string{"setup.py": "", ".beads": ""},
wantContain: []string{"pytest", "No beads pollution"},
},
{
name: "unknown stack gets generic reminder",
files: map[string]string{"README.md": "hi"},
wantContain: []string{"run your project's test suite"},
wantAbsent: []string{"go test", "npm test", "cargo test", "pytest"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
dir := writeMarkerDir(t, tc.files)
joined := strings.Join(buildPreflightChecklist(dir), "\n")
for _, want := range tc.wantContain {
if !strings.Contains(joined, want) {
t.Errorf("checklist missing %q\ngot:\n%s", want, joined)
}
}
for _, absent := range tc.wantAbsent {
if strings.Contains(joined, absent) {
t.Errorf("checklist unexpectedly contains %q\ngot:\n%s", absent, joined)
}
}
})
}
}
func TestIsBeadsRepo(t *testing.T) {
beads := writeMarkerDir(t, map[string]string{"go.mod": "module github.com/steveyegge/beads\n"})
if !isBeadsRepo(beads) {
t.Error("expected beads module to be detected as the beads repo")
}
other := writeMarkerDir(t, map[string]string{"go.mod": "module example.com/foo\n"})
if isBeadsRepo(other) {
t.Error("non-beads module should not be detected as the beads repo")
}
empty := t.TempDir()
if isBeadsRepo(empty) {
t.Error("dir without go.mod should not be detected as the beads repo")
}
}
// TestPreflightJSONInheritsRootFlag pins preflight's --json contract now that
// the command inherits the root persistent flag instead of registering a local
// copy. A local copy would shadow the inherited one and is what
// TestNoSubcommandShadowsRootJSONFlag forbids, so the first check rejects a
// local flag rather than requiring one.
//
// The binding this pins is unchanged, only re-keyed: the root flag is
// BoolVar'd to the same package global (main.go), so setting it must write
// jsonOutput, or every jsonOutput reader (including the front-door refusal
// renderers) stays in text mode while the user asked for JSON. Leaving it
// unset must report unchanged to commandJSONFlagChanged, which is what lets a
// config-file `json: true` reach preflight the way it reaches its siblings.
//
// The last two subtests drive that config half rather than only asserting the
// negative direction. flag.Value.Set never sets Changed (only FlagSet.Set
// does), so the Changed==true branch of commandJSONFlagChanged needs its own
// case — driven through the root flag, which is the one an inheriting command
// now has — and the configured `json: true` with no flag flipping jsonOutput
// only happens inside refreshBoundCommandConfig, so it has to be driven
// through that function.
func TestPreflightJSONInheritsRootFlag(t *testing.T) {
rootJSON := preflightCmd.Root().PersistentFlags().Lookup("json")
if rootJSON == nil {
t.Fatal("root has no persistent --json flag")
}
// --json is inherited from rootCmd as a persistent flag; a local copy
// would shadow it (see TestNoSubcommandShadowsRootJSONFlag). Comparing
// against the root flag rather than requiring nil tolerates a sibling test
// having already merged the root persistent flags into this command's set.
if f := preflightCmd.Flags().Lookup("json"); f != nil && f != rootJSON {
t.Error("preflight must not register a local --json; it inherits the root flag")
}
// refreshBoundCommandConfig consults config only when neither --json nor
// its hidden --format alias was given, so this test owns that flag's
// Changed bit too.
rootFormat := preflightCmd.Root().PersistentFlags().Lookup("format")
if rootFormat == nil {
t.Fatal("root has no persistent --format flag")
}
oldGlobal := jsonOutput
oldValue, oldRootChanged := rootJSON.Value.String(), rootJSON.Changed
oldFormatChanged := rootFormat.Changed
// refreshBoundCommandConfig reapplies every config-backed default, not
// just json; restore the rest so this test cannot leak into siblings.
oldReadonly, oldActor, oldAutoCommit := readonlyMode, actor, doltAutoCommit
t.Cleanup(func() {
_ = rootJSON.Value.Set(oldValue)
rootJSON.Changed = oldRootChanged
rootFormat.Changed = oldFormatChanged
jsonOutput = oldGlobal
readonlyMode, actor, doltAutoCommit = oldReadonly, oldActor, oldAutoCommit
config.ResetForTesting()
})
t.Run("inherited flag writes the package global", func(t *testing.T) {
jsonOutput = false
if err := rootJSON.Value.Set("true"); err != nil {
t.Fatal(err)
}
if !jsonOutput {
t.Fatal("preflight --json did not write jsonOutput; an unbound shadow leaves every reader of the global in text mode")
}
})
t.Run("neither flag set reports unchanged", func(t *testing.T) {
rootJSON.Changed = false
if commandJSONFlagChanged(preflightCmd) {
t.Fatal("preflight reported an explicit --json with neither flag set; the config-file json default would never apply")
}
})
t.Run("explicit --json reports changed", func(t *testing.T) {
rootJSON.Changed = false
if err := preflightCmd.Root().PersistentFlags().Set("json", "true"); err != nil {
t.Fatal(err)
}
if !commandJSONFlagChanged(preflightCmd) {
t.Fatal("an explicitly set --json reported unchanged; the config default would override the flag the user typed")
}
})
t.Run("configured json default applies with no flag", func(t *testing.T) {
config.ResetForTesting()
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
config.Set("json", true)
rootJSON.Changed = false
rootFormat.Changed = false
jsonOutput = false
refreshBoundCommandConfig(preflightCmd)
if !jsonOutput {
t.Fatal("config json:true with no --json flag left jsonOutput false; preflight would render text while the repo config asks for JSON")
}
})
}