diff --git a/cmd/bd/close_proxied_server.go b/cmd/bd/close_proxied_server.go index 118f85bcc..ffacbad0a 100644 --- a/cmd/bd/close_proxied_server.go +++ b/cmd/bd/close_proxied_server.go @@ -142,7 +142,7 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin } if len(args) > 0 && len(outcomes) == 0 { - os.Exit(1) + return SilentExit() } return nil } diff --git a/cmd/bd/compact.go b/cmd/bd/compact.go index 27ac90357..b89bf0e51 100644 --- a/cmd/bd/compact.go +++ b/cmd/bd/compact.go @@ -95,8 +95,7 @@ Examples: // Handle compact stats first if compactStats { - runCompactStats(ctx, store) - return nil + return runCompactStats(ctx, store) } // Handle dolt GC mode @@ -118,65 +117,51 @@ Examples: // Check for exactly one mode if activeModes == 0 { - fmt.Fprintf(os.Stderr, "Error: must specify one mode: --analyze, --apply, or --auto\n") - os.Exit(1) + return HandleError("must specify one mode: --analyze, --apply, or --auto") } if activeModes > 1 { - fmt.Fprintf(os.Stderr, "Error: cannot use multiple modes together (--analyze, --apply, --auto are mutually exclusive)\n") - os.Exit(1) + return HandleError("cannot use multiple modes together (--analyze, --apply, --auto are mutually exclusive)") } // Only Tier 1 compaction is implemented. Reject other tiers up front with // a clear message rather than failing deep inside a mode. if compactTier != 1 { - fmt.Fprintf(os.Stderr, "Error: Tier %d compaction is not yet implemented; only --tier 1 is available\n", compactTier) - os.Exit(1) + return HandleError("Tier %d compaction is not yet implemented; only --tier 1 is available", compactTier) } // Handle analyze mode (requires direct database access) if compactAnalyze { if err := ensureDirectMode("compact --analyze requires direct database access"); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - fmt.Fprintf(os.Stderr, "Hint: %s\n", diagHint()) - os.Exit(1) + return HandleErrorWithHint(err.Error(), diagHint()) } - runCompactAnalyze(ctx, store) - return nil + return runCompactAnalyze(ctx, store) } // Handle apply mode (requires direct database access) if compactApply { if err := ensureDirectMode("compact --apply requires direct database access"); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - fmt.Fprintf(os.Stderr, "Hint: %s\n", diagHint()) - os.Exit(1) + return HandleErrorWithHint(err.Error(), diagHint()) } if compactID == "" { - fmt.Fprintf(os.Stderr, "Error: --apply requires --id\n") - os.Exit(1) + return HandleError("--apply requires --id") } if compactSummary == "" { - fmt.Fprintf(os.Stderr, "Error: --apply requires --summary\n") - os.Exit(1) + return HandleError("--apply requires --summary") } - runCompactApply(ctx, store) - return nil + return runCompactApply(ctx, store) } // Handle auto mode (legacy) if compactAuto { // Validation checks if compactID != "" && compactAll { - fmt.Fprintf(os.Stderr, "Error: cannot use --id and --all together\n") - os.Exit(1) + return HandleError("cannot use --id and --all together") } if compactForce && compactID == "" { - fmt.Fprintf(os.Stderr, "Error: --force requires --id\n") - os.Exit(1) + return HandleError("--force requires --id") } if compactID == "" && !compactAll && !compactDryRun { - fmt.Fprintf(os.Stderr, "Error: must specify --all, --id, or --dry-run\n") - os.Exit(1) + return HandleError("must specify --all, --id, or --dry-run") } // Direct mode @@ -185,8 +170,7 @@ Examples: apiKey = config.GetString("ai.api_key") } if apiKey == "" && !compactDryRun { - fmt.Fprintf(os.Stderr, "Error: --auto mode requires ANTHROPIC_API_KEY environment variable or ai.api_key in config\n") - os.Exit(1) + return HandleError("--auto mode requires ANTHROPIC_API_KEY environment variable or ai.api_key in config") } compactCfg := &compact.Config{ @@ -197,40 +181,35 @@ Examples: compactor, err := compact.New(store, apiKey, compactCfg) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to create compactor: %v\n", err) - os.Exit(1) + return HandleError("failed to create compactor: %v", err) } if compactID != "" { - runCompactSingle(ctx, compactor, store, compactID) - return nil + return runCompactSingle(ctx, compactor, store, compactID) } - runCompactAll(ctx, compactor, store) + return runCompactAll(ctx, compactor, store) } return nil }, } -func runCompactSingle(ctx context.Context, compactor *compact.Compactor, store storage.DoltStorage, issueID string) { +func runCompactSingle(ctx context.Context, compactor *compact.Compactor, store storage.DoltStorage, issueID string) error { start := time.Now() if !compactForce { eligible, reason, err := store.CheckEligibility(ctx, issueID, compactTier) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to check eligibility: %v\n", err) - os.Exit(1) + return HandleError("failed to check eligibility: %v", err) } if !eligible { - fmt.Fprintf(os.Stderr, "Error: %s is not eligible for Tier %d compaction: %s\n", issueID, compactTier, reason) - os.Exit(1) + return HandleError("%s is not eligible for Tier %d compaction: %s", issueID, compactTier, reason) } } issue, err := store.GetIssue(ctx, issueID) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to get issue: %v\n", err) - os.Exit(1) + return HandleError("failed to get issue: %v", err) } originalSize := len(issue.Description) + len(issue.Design) + len(issue.Notes) + len(issue.AcceptanceCriteria) @@ -264,7 +243,7 @@ func runCompactSingle(ctx context.Context, compactor *compact.Compactor, store s if err := outputJSON(output); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Printf("DRY RUN - Tier %d compaction\n\n", compactTier) @@ -275,26 +254,23 @@ func runCompactSingle(ctx context.Context, compactor *compact.Compactor, store s } fmt.Printf(" %-12s %-40s %5dd %10d B\n", issueID, title, ageDays, originalSize) fmt.Printf("\nSummary: 1 candidate, %d bytes total content\n", originalSize) - return + return nil } var compactErr error if compactTier == 1 { compactErr = compactor.CompactTier1(ctx, issueID) } else { - fmt.Fprintf(os.Stderr, "Error: Tier 2 compaction not yet implemented\n") - os.Exit(1) + return HandleError("Tier 2 compaction not yet implemented") } if compactErr != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", compactErr) - os.Exit(1) + return HandleError("%v", compactErr) } issue, err = store.GetIssue(ctx, issueID) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to get updated issue: %v\n", err) - os.Exit(1) + return HandleError("failed to get updated issue: %v", err) } compactedSize := len(issue.Description) @@ -315,7 +291,7 @@ func runCompactSingle(ctx context.Context, compactor *compact.Compactor, store s if err := outputJSON(output); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Printf("✓ Compacted %s (Tier %d)\n", issueID, compactTier) @@ -323,17 +299,17 @@ func runCompactSingle(ctx context.Context, compactor *compact.Compactor, store s originalSize, compactedSize, savingBytes, float64(savingBytes)/float64(originalSize)*100) fmt.Printf(" Time: %v\n", elapsed) + return nil } -func runCompactAll(ctx context.Context, compactor *compact.Compactor, store storage.DoltStorage) { +func runCompactAll(ctx context.Context, compactor *compact.Compactor, store storage.DoltStorage) error { start := time.Now() var candidates []string if compactTier == 1 { tier1, err := store.GetTier1Candidates(ctx) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to get candidates: %v\n", err) - os.Exit(1) + return HandleError("failed to get candidates: %v", err) } for _, c := range tier1 { candidates = append(candidates, c.IssueID) @@ -341,8 +317,7 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor } else { tier2, err := store.GetTier2Candidates(ctx) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to get candidates: %v\n", err) - os.Exit(1) + return HandleError("failed to get candidates: %v", err) } for _, c := range tier2 { candidates = append(candidates, c.IssueID) @@ -358,10 +333,10 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor }); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Println("No eligible candidates for compaction") - return + return nil } if compactDryRun { @@ -412,7 +387,7 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor if err := outputJSON(output); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Printf("DRY RUN - Tier %d compaction\n\n", compactTier) @@ -425,7 +400,7 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor fmt.Printf(" %-12s %-40s %5dd %10d B\n", c.ID, title, c.AgeDays, c.ContentSize) } fmt.Printf("\nSummary: %d candidates, %d bytes total content\n", len(dryCandidates), totalSize) - return + return nil } if !jsonOutput { @@ -434,8 +409,7 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor results, err := compactor.CompactTier1Batch(ctx, candidates) if err != nil { - fmt.Fprintf(os.Stderr, "Error: batch compaction failed: %v\n", err) - os.Exit(1) + return HandleError("batch compaction failed: %v", err) } successCount := 0 @@ -473,7 +447,7 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor if err := outputJSON(output); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Printf("\n\nCompleted in %v\n\n", elapsed) @@ -483,19 +457,18 @@ func runCompactAll(ctx context.Context, compactor *compact.Compactor, store stor if totalOriginal > 0 { fmt.Printf(" Saved: %d bytes (%.1f%%)\n", totalSaved, float64(totalSaved)/float64(totalOriginal)*100) } + return nil } -func runCompactStats(ctx context.Context, store storage.DoltStorage) { +func runCompactStats(ctx context.Context, store storage.DoltStorage) error { tier1, err := store.GetTier1Candidates(ctx) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to get Tier 1 candidates: %v\n", err) - os.Exit(1) + return HandleError("failed to get Tier 1 candidates: %v", err) } tier2, err := store.GetTier2Candidates(ctx) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to get Tier 2 candidates: %v\n", err) - os.Exit(1) + return HandleError("failed to get Tier 2 candidates: %v", err) } tier1Size := 0 @@ -523,7 +496,7 @@ func runCompactStats(ctx context.Context, store storage.DoltStorage) { if err := outputJSON(output); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Println("Compaction Statistics") @@ -537,9 +510,10 @@ func runCompactStats(ctx context.Context, store storage.DoltStorage) { fmt.Printf("Tier 2 (90+ days closed, Tier 1 compacted): not yet implemented\n") fmt.Printf(" Candidates: %d\n", len(tier2)) fmt.Printf(" Total size: %d bytes\n", tier2Size) + return nil } -func runCompactAnalyze(ctx context.Context, store storage.DoltStorage) { +func runCompactAnalyze(ctx context.Context, store storage.DoltStorage) error { type Candidate struct { ID string `json:"id"` Title string `json:"title"` @@ -559,8 +533,7 @@ func runCompactAnalyze(ctx context.Context, store storage.DoltStorage) { if compactID != "" { issue, err := store.GetIssue(ctx, compactID) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to get issue: %v\n", err) - os.Exit(1) + return HandleError("failed to get issue: %v", err) } sizeBytes := len(issue.Description) + len(issue.Design) + len(issue.Notes) + len(issue.AcceptanceCriteria) @@ -591,8 +564,7 @@ func runCompactAnalyze(ctx context.Context, store storage.DoltStorage) { tierCandidates, err = store.GetTier2Candidates(ctx) } if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to get candidates: %v\n", err) - os.Exit(1) + return HandleError("failed to get candidates: %v", err) } // Apply limit if specified @@ -639,7 +611,7 @@ func runCompactAnalyze(ctx context.Context, store storage.DoltStorage) { if err := outputJSON(output); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } // Human-readable output @@ -659,9 +631,10 @@ func runCompactAnalyze(ctx context.Context, store storage.DoltStorage) { totalSize += c.SizeBytes } fmt.Printf("\nSummary: %d candidates, %d bytes total content\n", len(candidates), totalSize) + return nil } -func runCompactApply(ctx context.Context, store storage.DoltStorage) { +func runCompactApply(ctx context.Context, store storage.DoltStorage) error { start := time.Now() // Read summary @@ -671,15 +644,13 @@ func runCompactApply(ctx context.Context, store storage.DoltStorage) { // Read from stdin summaryBytes, err = io.ReadAll(os.Stdin) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to read summary from stdin: %v\n", err) - os.Exit(1) + return HandleError("failed to read summary from stdin: %v", err) } } else { // #nosec G304 -- summary file path provided explicitly by operator summaryBytes, err = os.ReadFile(compactSummary) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to read summary file: %v\n", err) - os.Exit(1) + return HandleError("failed to read summary file: %v", err) } } summary := string(summaryBytes) @@ -687,8 +658,7 @@ func runCompactApply(ctx context.Context, store storage.DoltStorage) { // Get issue issue, err := store.GetIssue(ctx, compactID) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to get issue: %v\n", err) - os.Exit(1) + return HandleError("failed to get issue: %v", err) } // Calculate sizes @@ -699,20 +669,15 @@ func runCompactApply(ctx context.Context, store storage.DoltStorage) { if !compactForce { eligible, reason, err := store.CheckEligibility(ctx, compactID, compactTier) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to check eligibility: %v\n", err) - os.Exit(1) + return HandleError("failed to check eligibility: %v", err) } if !eligible { - fmt.Fprintf(os.Stderr, "Error: %s is not eligible for Tier %d compaction: %s\n", compactID, compactTier, reason) - fmt.Fprintf(os.Stderr, "Hint: use --force to bypass eligibility checks\n") - os.Exit(1) + return HandleErrorWithHint(fmt.Sprintf("%s is not eligible for Tier %d compaction: %s", compactID, compactTier, reason), "use --force to bypass eligibility checks") } // Enforce size reduction unless --force if compactedSize >= originalSize { - fmt.Fprintf(os.Stderr, "Error: summary (%d bytes) is not shorter than original (%d bytes)\n", compactedSize, originalSize) - fmt.Fprintf(os.Stderr, "Hint: use --force to bypass size validation\n") - os.Exit(1) + return HandleErrorWithHint(fmt.Sprintf("summary (%d bytes) is not shorter than original (%d bytes)", compactedSize, originalSize), "use --force to bypass size validation") } } @@ -730,22 +695,19 @@ func runCompactApply(ctx context.Context, store storage.DoltStorage) { } if err := store.UpdateIssue(ctx, compactID, updates, actor); err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to update issue: %v\n", err) - os.Exit(1) + return HandleError("failed to update issue: %v", err) } commitHash := compact.GetCurrentCommitHash() if err := store.ApplyCompaction(ctx, compactID, compactTier, originalSize, compactedSize, commitHash); err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to apply compaction: %v\n", err) - os.Exit(1) + return HandleError("failed to apply compaction: %v", err) } savingBytes := originalSize - compactedSize reductionPct := float64(savingBytes) / float64(originalSize) * 100 eventData := fmt.Sprintf("Tier %d compaction: %d → %d bytes (saved %d, %.1f%%)", compactTier, originalSize, compactedSize, savingBytes, reductionPct) if err := store.AddComment(ctx, compactID, actor, eventData); err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to record event: %v\n", err) - os.Exit(1) + return HandleError("failed to record event: %v", err) } elapsed := time.Since(start) @@ -764,12 +726,13 @@ func runCompactApply(ctx context.Context, store storage.DoltStorage) { if err := outputJSON(output); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Printf("✓ Compacted %s (Tier %d)\n", compactID, compactTier) fmt.Printf(" %d → %d bytes (saved %d, %.1f%%)\n", originalSize, compactedSize, savingBytes, reductionPct) fmt.Printf(" Time: %v\n", elapsed) + return nil } // runCompactDolt runs Dolt garbage collection on the .beads/dolt directory @@ -802,9 +765,7 @@ func runCompactDolt() error { fmt.Printf("No local Dolt directory found; nothing to collect.\n") return nil } - fmt.Fprintf(os.Stderr, "Error: Dolt directory not found at %s\n", doltPath) - fmt.Fprintf(os.Stderr, "Hint: --dolt flag is only for repositories using the Dolt backend\n") - os.Exit(1) + return HandleErrorWithHint(fmt.Sprintf("Dolt directory not found at %s", doltPath), "--dolt flag is only for repositories using the Dolt backend") } // Get size before GC @@ -836,9 +797,7 @@ func runCompactDolt() error { // Check if dolt command is available if _, err := exec.LookPath("dolt"); err != nil { - fmt.Fprintf(os.Stderr, "Error: dolt command not found in PATH\n") - fmt.Fprintf(os.Stderr, "Hint: install Dolt from https://github.com/dolthub/dolt\n") - os.Exit(1) + return HandleErrorWithHint("dolt command not found in PATH", "install Dolt from https://github.com/dolthub/dolt") } if !jsonOutput { @@ -854,7 +813,7 @@ func runCompactDolt() error { if len(output) > 0 { fmt.Fprintf(os.Stderr, "Output: %s\n", string(output)) } - os.Exit(1) + return SilentExit() } // Get size after GC diff --git a/cmd/bd/db_proxy_child.go b/cmd/bd/db_proxy_child.go index a2194ad54..40ba930a6 100644 --- a/cmd/bd/db_proxy_child.go +++ b/cmd/bd/db_proxy_child.go @@ -3,7 +3,6 @@ package main import ( "errors" "fmt" - "os" "strings" "time" @@ -71,7 +70,7 @@ not intended to be invoked directly by users.`, }) if err := p.ListenAndServe(cmd.Context()); err != nil { if errors.Is(err, proxy.ErrLockHeld) { - os.Exit(proxy.LockHeldExitCode) + return &exitError{Code: proxy.LockHeldExitCode} } return err } diff --git a/cmd/bd/dolt.go b/cmd/bd/dolt.go index b7998fdca..cddc14b8b 100644 --- a/cmd/bd/dolt.go +++ b/cmd/bd/dolt.go @@ -106,8 +106,7 @@ Examples: Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { if !usesSQLServer() { - fmt.Fprintln(os.Stderr, "Error: 'bd dolt set' is not supported in embedded mode (no Dolt server)") - os.Exit(1) + return HandleError("'bd dolt set' is not supported in embedded mode (no Dolt server)") } key := args[0] value := args[1] @@ -130,8 +129,7 @@ This verifies that: Use this before switching to server mode to ensure the server is running.`, RunE: func(cmd *cobra.Command, args []string) error { if !usesSQLServer() { - fmt.Fprintln(os.Stderr, "Error: 'bd dolt test' is not supported in embedded mode (no Dolt server)") - os.Exit(1) + return HandleError("'bd dolt test' is not supported in embedded mode (no Dolt server)") } return testDoltConnection() }, @@ -328,8 +326,10 @@ func printDivergedHistoryGuidance(operation string) { } var doltPushCmd = &cobra.Command{ - Use: "push", - Short: "Push commits to Dolt remote", + Use: "push", + SilenceUsage: true, + SilenceErrors: true, + Short: "Push commits to Dolt remote", Long: `Push local Dolt commits to the configured remote. Requires a Dolt remote to be configured in the database directory. @@ -341,28 +341,27 @@ uncommitted changes in its working set). Use --remote to push to a specific named remote instead of the default. The remote must already exist (see 'bd dolt remote add').`, - Run: func(cmd *cobra.Command, args []string) { + RunE: func(cmd *cobra.Command, args []string) error { if config.GetBool("no-push") { fmt.Println("skipping push: rig is local-only (no-push: true)") - return + return nil } if isDoltLocalOnly() { if jsonOutput { if err := outputJSONRaw(map[string]string{"status": "disabled", "reason": "dolt.local-only=true"}); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Println("Remote sync is disabled for this project (dolt.local-only=true).") fmt.Println("Your issues are stored locally in .beads/.") fmt.Println("To re-enable remote sync: bd config unset dolt.local-only") - return + return nil } ctx := context.Background() st := getStore() if st == nil { - fmt.Fprintf(os.Stderr, "Error: no store available\n") - os.Exit(1) + return HandleError("no store available") } force, _ := cmd.Flags().GetBool("force") remote, _ := cmd.Flags().GetString("remote") @@ -379,14 +378,13 @@ The remote must already exist (see 'bd dolt remote add').`, } else if isDivergedHistoryErr(err) { printDivergedHistoryGuidance("push --force") } - os.Exit(1) + return SilentExit() } fmt.Println("Push complete.") - return + return nil } if adopted, err := adoptGitOriginRemoteForPush(ctx, st); err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to adopt git origin as Dolt remote: %v\n", err) - os.Exit(1) + return HandleError("failed to adopt git origin as Dolt remote: %v", err) } else if adopted { fmt.Println("Configured Dolt remote origin from git origin.") } @@ -401,7 +399,7 @@ The remote must already exist (see 'bd dolt remote add').`, if pushErr != nil { if isConfirmedNoRemote(ctx, st, pushErr) { printNoRemoteGuidance() - return + return nil } fmt.Fprintf(os.Stderr, "Error: %v\n", pushErr) if isAncestorPKMismatchErr(pushErr) { @@ -413,15 +411,18 @@ The remote must already exist (see 'bd dolt remote add').`, } printDivergedHistoryGuidance(op) } - os.Exit(1) + return SilentExit() } fmt.Println("Push complete.") + return nil }, } var doltPullCmd = &cobra.Command{ - Use: "pull", - Short: "Pull commits from Dolt remote", + Use: "pull", + SilenceUsage: true, + SilenceErrors: true, + Short: "Pull commits from Dolt remote", Long: `Pull commits from the configured Dolt remote into the local database. Requires a Dolt remote to be configured in the database directory. @@ -430,24 +431,23 @@ variables for authentication. Use --remote to pull from a specific named remote instead of the default. The remote must already exist (see 'bd dolt remote add').`, - Run: func(cmd *cobra.Command, args []string) { + RunE: func(cmd *cobra.Command, args []string) error { if isDoltLocalOnly() { if jsonOutput { if err := outputJSONRaw(map[string]string{"status": "disabled", "reason": "dolt.local-only=true"}); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Println("Remote sync is disabled for this project (dolt.local-only=true).") fmt.Println("Nothing to pull.") fmt.Println("To re-enable remote sync: bd config unset dolt.local-only") - return + return nil } ctx := context.Background() st := getStore() if st == nil { - fmt.Fprintf(os.Stderr, "Error: no store available\n") - os.Exit(1) + return HandleError("no store available") } remote, _ := cmd.Flags().GetString("remote") if remote != "" { @@ -463,16 +463,16 @@ The remote must already exist (see 'bd dolt remote add').`, } else if isDivergedHistoryErr(err) { printDivergedHistoryGuidance("pull") } - os.Exit(1) + return SilentExit() } fmt.Println("Pull complete.") - return + return nil } fmt.Println("Pulling from Dolt remote...") if err := st.Pull(ctx); err != nil { if isConfirmedNoRemote(ctx, st, err) { printNoRemoteGuidance() - return + return nil } fmt.Fprintf(os.Stderr, "Error: %v\n", err) if isAncestorPKMismatchErr(err) { @@ -480,9 +480,10 @@ The remote must already exist (see 'bd dolt remote add').`, } else if isDivergedHistoryErr(err) { printDivergedHistoryGuidance("pull") } - os.Exit(1) + return SilentExit() } fmt.Println("Pull complete.") + return nil }, } @@ -499,12 +500,13 @@ Also useful before push operations that require a clean working set, or when auto-commit was off or changes were made externally. For more options (--stdin, custom messages), see: bd vc commit`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { ctx := context.Background() st := getStore() if st == nil { - fmt.Fprintf(os.Stderr, "Error: no store available\n") - os.Exit(1) + return HandleError("no store available") } msg, _ := cmd.Flags().GetString("message") if msg == "" { @@ -513,13 +515,13 @@ For more options (--stdin, custom messages), see: bd vc commit`, if err := st.Commit(ctx, msg); err != nil { if isDoltNothingToCommit(err) { fmt.Println("Nothing to commit.") - return + return nil } - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } commandDidExplicitDoltCommit = true fmt.Println("Committed.") + return nil }, } @@ -537,8 +539,7 @@ The server auto-starts transparently when needed, so manual start is rarely required. Use this command for explicit control or diagnostics.`, RunE: func(cmd *cobra.Command, args []string) error { if !usesSQLServer() { - fmt.Fprintln(os.Stderr, "Error: 'bd dolt start' is not supported in embedded mode (no Dolt server)") - os.Exit(1) + return HandleError("'bd dolt start' is not supported in embedded mode (no Dolt server)") } beadsDir := selectedDoltBeadsDir() if beadsDir == "" { @@ -552,8 +553,7 @@ required. Use this command for explicit control or diagnostics.`, fmt.Println(err) return nil } - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } fmt.Printf("Dolt server started (PID %d, port %d)\n", state.PID, state.Port) @@ -582,8 +582,7 @@ This sends a graceful shutdown signal. The server will restart automatically on the next bd command unless auto-start is disabled.`, RunE: func(cmd *cobra.Command, args []string) error { if !usesSQLServer() { - fmt.Fprintln(os.Stderr, "Error: 'bd dolt stop' is not supported in embedded mode (no Dolt server)") - os.Exit(1) + return HandleError("'bd dolt stop' is not supported in embedded mode (no Dolt server)") } beadsDir := selectedDoltBeadsDir() if beadsDir == "" { @@ -593,8 +592,7 @@ on the next bd command unless auto-start is disabled.`, force, _ := cmd.Flags().GetBool("force") if err := doltserver.StopWithForce(serverDir, force); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } fmt.Println("Dolt server stopped.") return nil @@ -655,8 +653,7 @@ endpoint via SQL and reports reachability, server version, and database.`, state, err := doltserver.IsRunning(serverDir) if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } renderLocalDoltStatus(state, serverDir) return nil @@ -894,10 +891,11 @@ orphans and will be killed. In standalone mode, only dolt sql-server processes using the current project's Dolt data directory are eligible for cleanup. Other projects' servers are preserved.`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { if !usesSQLServer() { - fmt.Fprintln(os.Stderr, "Error: 'bd dolt killall' is not supported in embedded mode (no Dolt server)") - os.Exit(1) + return HandleError("'bd dolt killall' is not supported in embedded mode (no Dolt server)") } beadsDir := selectedDoltBeadsDir() if beadsDir == "" { @@ -906,8 +904,7 @@ servers are preserved.`, killed, err := doltserver.KillStaleServers(beadsDir) if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } if len(killed) == 0 { @@ -915,6 +912,7 @@ servers are preserved.`, } else { fmt.Printf("Killed %d orphan dolt server(s): %v\n", len(killed), killed) } + return nil }, } @@ -962,8 +960,7 @@ These waste server memory and can degrade performance under concurrent load. Use --dry-run to see what would be dropped without actually dropping.`, RunE: func(cmd *cobra.Command, args []string) error { if !usesSQLServer() { - fmt.Fprintln(os.Stderr, "Error: 'bd dolt clean-databases' is not supported in embedded mode (no Dolt server)") - os.Exit(1) + return HandleError("'bd dolt clean-databases' is not supported in embedded mode (no Dolt server)") } dryRun, _ := cmd.Flags().GetBool("dry-run") @@ -980,8 +977,7 @@ Use --dry-run to see what would be dropped without actually dropping.`, rows, err := db.QueryContext(listCtx, "SHOW DATABASES") if err != nil { - fmt.Fprintf(os.Stderr, "Error listing databases: %v\n", err) - os.Exit(1) + return HandleError("listing databases: %v", err) } defer rows.Close() @@ -1040,7 +1036,7 @@ Use --dry-run to see what would be dropped without actually dropping.`, if failures >= maxConsecFailures { fmt.Fprintf(os.Stderr, "\n✗ Aborting: %d consecutive failures suggest server is unhealthy.\n", failures) fmt.Fprintf(os.Stderr, " Dropped %d/%d before stopping.\n", dropped, len(stale)) - os.Exit(1) + return SilentExit() } // Per-operation timeout: DROP DATABASE can be slow on Dolt @@ -1163,7 +1159,7 @@ var doltRemoteAddCmd = &cobra.Command{ if isDoltLocalOnly() { fmt.Fprintln(os.Stderr, "Error: cannot add Dolt remote: remote sync is disabled (dolt.local-only=true).") fmt.Fprintln(os.Stderr, "To re-enable remote sync: bd config unset dolt.local-only") - os.Exit(1) + return SilentExit() } allowGitOrigin, _ := cmd.Flags().GetBool("allow-git-origin") if doltRemoteMatchesGitOrigin(args[1]) { @@ -1171,15 +1167,14 @@ var doltRemoteAddCmd = &cobra.Command{ fmt.Fprintf(os.Stderr, "Error: refusing to add %q as a Dolt remote — this URL matches the git origin.\n", args[1]) fmt.Fprintln(os.Stderr, " Hint: use --allow-git-origin to proceed anyway (e.g. monorepo layout).") fmt.Fprintln(os.Stderr, " Hint: or set dolt.local-only=true to disable remote sync entirely.") - os.Exit(1) + return SilentExit() } fmt.Fprintf(os.Stderr, "Warning: %q matches the git origin — proceeding because --allow-git-origin is set.\n", args[1]) } ctx := context.Background() st := getStore() if st == nil { - fmt.Fprintf(os.Stderr, "Error: no store available\n") - os.Exit(1) + return HandleError("no store available") } name, url := args[0], args[1] @@ -1190,7 +1185,7 @@ var doltRemoteAddCmd = &cobra.Command{ } else { fmt.Fprintf(os.Stderr, "Error adding remote: %v\n", err) } - os.Exit(1) + return SilentExit() } if result.Canceled { fmt.Println("Canceled.") @@ -1221,14 +1216,15 @@ var doltRemoteAddCmd = &cobra.Command{ } var doltRemoteListCmd = &cobra.Command{ - Use: "list", - Short: "List configured Dolt remotes", - Run: func(cmd *cobra.Command, args []string) { + Use: "list", + SilenceUsage: true, + SilenceErrors: true, + Short: "List configured Dolt remotes", + RunE: func(cmd *cobra.Command, args []string) error { ctx := context.Background() st := getStore() if st == nil { - fmt.Fprintf(os.Stderr, "Error: no store available\n") - os.Exit(1) + return HandleError("no store available") } remotes, err := st.ListRemotes(ctx) @@ -1238,24 +1234,25 @@ var doltRemoteListCmd = &cobra.Command{ } else { fmt.Fprintf(os.Stderr, "Error listing remotes: %v\n", err) } - os.Exit(1) + return SilentExit() } if jsonOutput { if err := outputJSON(formatDoltRemoteListJSON(remotes)); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } if len(remotes) == 0 { fmt.Println("No remotes configured.") - return + return nil } for _, r := range remotes { fmt.Printf("%-20s %s\n", r.Name, r.URL) } + return nil }, } @@ -1296,8 +1293,7 @@ var doltRemoteRemoveCmd = &cobra.Command{ st := getStore() if st == nil { - fmt.Fprintf(os.Stderr, "Error: no store available\n") - os.Exit(1) + return HandleError("no store available") } if err := st.RemoveRemote(ctx, name); err != nil { @@ -1306,7 +1302,7 @@ var doltRemoteRemoveCmd = &cobra.Command{ } else { fmt.Fprintf(os.Stderr, "Error removing remote: %v\n", err) } - os.Exit(1) + return SilentExit() } if name == "origin" { @@ -1401,8 +1397,7 @@ func showDoltConfig(testConnection bool) error { cfg, err := configfile.Load(beadsDir) if err != nil { - fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err) - os.Exit(1) + return HandleError("loading config: %v", err) } if cfg == nil { cfg = configfile.DefaultConfig() @@ -1507,16 +1502,14 @@ func setDoltConfig(key, value string, updateConfig bool) error { cfg, err := configfile.Load(beadsDir) if err != nil { - fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err) - os.Exit(1) + return HandleError("loading config: %v", err) } if cfg == nil { cfg = configfile.DefaultConfig() } if cfg.GetBackend() != configfile.BackendDolt { - fmt.Fprintf(os.Stderr, "Error: not using Dolt backend\n") - os.Exit(1) + return HandleError("not using Dolt backend") } var yamlKey string @@ -1525,21 +1518,18 @@ func setDoltConfig(key, value string, updateConfig bool) error { case "mode": // Mode will be configurable again when embedded Dolt support returns. // For now, server mode is required (embedded driver not yet re-integrated). - fmt.Fprintf(os.Stderr, "Error: mode is not yet configurable; embedded mode is coming soon\n") - os.Exit(1) + return HandleError("mode is not yet configurable; embedded mode is coming soon") case "database": if value == "" { - fmt.Fprintf(os.Stderr, "Error: database name cannot be empty\n") - os.Exit(1) + return HandleError("database name cannot be empty") } cfg.DoltDatabase = value yamlKey = "dolt.database" case "host": if value == "" { - fmt.Fprintf(os.Stderr, "Error: host cannot be empty\n") - os.Exit(1) + return HandleError("host cannot be empty") } cfg.DoltServerHost = value yamlKey = "dolt.host" @@ -1547,8 +1537,7 @@ func setDoltConfig(key, value string, updateConfig bool) error { case "port": port, err := strconv.Atoi(value) if err != nil || port <= 0 || port > 65535 { - fmt.Fprintf(os.Stderr, "Error: port must be a valid port number (1-65535)\n") - os.Exit(1) + return HandleError("port must be a valid port number (1-65535)") } cfg.DoltServerPort = port yamlKey = "dolt.port" @@ -1560,8 +1549,7 @@ func setDoltConfig(key, value string, updateConfig bool) error { case "user": if value == "" { - fmt.Fprintf(os.Stderr, "Error: user cannot be empty\n") - os.Exit(1) + return HandleError("user cannot be empty") } cfg.DoltServerUser = value yamlKey = "dolt.user" @@ -1578,15 +1566,14 @@ func setDoltConfig(key, value string, updateConfig bool) error { fmt.Fprintf(os.Stderr, "from the configured database '%s'.\n", cfg.GetDoltDatabase()) fmt.Fprintf(os.Stderr, "\nTo change which database to use:\n") fmt.Fprintf(os.Stderr, " bd dolt set database \n") - os.Exit(1) + return SilentExit() } if value == "" { // Allow clearing the custom data dir (revert to default .beads/dolt) cfg.DoltDataDir = "" } else { if !filepath.IsAbs(value) { - fmt.Fprintf(os.Stderr, "Error: data-dir must be an absolute path\n") - os.Exit(1) + return HandleError("data-dir must be an absolute path") } cfg.DoltDataDir = value // Absolute paths are machine-specific and won't be persisted to @@ -1601,13 +1588,11 @@ func setDoltConfig(key, value string, updateConfig bool) error { case "shared-server": lower := strings.ToLower(value) if lower != "true" && lower != "false" { - fmt.Fprintf(os.Stderr, "Error: shared-server must be 'true' or 'false'\n") - os.Exit(1) + return HandleError("shared-server must be 'true' or 'false'") } // shared-server is yaml-only (not stored in metadata.json) if err := config.SetYamlConfig("dolt.shared-server", lower); err != nil { - fmt.Fprintf(os.Stderr, "Error setting shared-server: %v\n", err) - os.Exit(1) + return HandleError("setting shared-server: %v", err) } if jsonOutput { if err := outputJSON(map[string]interface{}{ @@ -1631,7 +1616,7 @@ func setDoltConfig(key, value string, updateConfig bool) error { default: fmt.Fprintf(os.Stderr, "Error: unknown key '%s'\n", key) fmt.Fprintf(os.Stderr, "Valid keys: database, host, port, socket, user, data-dir, shared-server\n") - os.Exit(1) + return SilentExit() } // Audit log: record who changed what @@ -1639,8 +1624,7 @@ func setDoltConfig(key, value string, updateConfig bool) error { // Save to metadata.json if err := cfg.Save(beadsDir); err != nil { - fmt.Fprintf(os.Stderr, "Error saving config: %v\n", err) - os.Exit(1) + return HandleError("saving config: %v", err) } if jsonOutput { @@ -1679,16 +1663,14 @@ func testDoltConnection() error { cfg, err := configfile.Load(beadsDir) if err != nil { - fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err) - os.Exit(1) + return HandleError("loading config: %v", err) } if cfg == nil { cfg = configfile.DefaultConfig() } if cfg.GetBackend() != configfile.BackendDolt { - fmt.Fprintf(os.Stderr, "Error: not using Dolt backend\n") - os.Exit(1) + return HandleError("not using Dolt backend") } host := cfg.GetDoltServerHost() @@ -1705,7 +1687,7 @@ func testDoltConnection() error { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } if !ok { - os.Exit(1) + return SilentExit() } return nil } @@ -1717,7 +1699,7 @@ func testDoltConnection() error { } else { fmt.Printf("%s\n", ui.RenderWarn("✗ Connection failed")) fmt.Println("\nStart the server with: bd dolt start") - os.Exit(1) + return SilentExit() } // Test remote connectivity @@ -1850,8 +1832,7 @@ func openDoltServerConnection() (*sql.DB, func(), error) { cfg, err := configfile.Load(beadsDir) if err != nil { - fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err) - os.Exit(1) + return nil, nil, HandleError("loading config: %v", err) } if cfg == nil { cfg = configfile.DefaultConfig() @@ -1872,8 +1853,7 @@ func openDoltServerConnection() (*sql.DB, func(), error) { db, err := sql.Open("mysql", connStr) if err != nil { - fmt.Fprintf(os.Stderr, "Error connecting to Dolt server: %v\n", err) - os.Exit(1) + return nil, nil, HandleError("connecting to Dolt server: %v", err) } db.SetMaxOpenConns(2) @@ -1887,7 +1867,7 @@ func openDoltServerConnection() (*sql.DB, func(), error) { _ = db.Close() fmt.Fprintf(os.Stderr, "Error: cannot reach Dolt server at %s:%d: %v\n", host, port, err) fmt.Fprintln(os.Stderr, "Start the server with: bd dolt start") - os.Exit(1) + return nil, nil, SilentExit() } return db, func() { _ = db.Close() }, nil diff --git a/cmd/bd/dolt_remote_proxied_server.go b/cmd/bd/dolt_remote_proxied_server.go index 93da2935d..84796c7c8 100644 --- a/cmd/bd/dolt_remote_proxied_server.go +++ b/cmd/bd/dolt_remote_proxied_server.go @@ -24,7 +24,7 @@ func runDoltRemoteRemoveProxied(ctx context.Context, name string) error { } else { fmt.Fprintf(os.Stderr, "Error removing remote: %v\n", err) } - os.Exit(1) + return SilentExit() } if err := uw.Commit(ctx, fmt.Sprintf("bd: remove remote %s", name)); err != nil && !isDoltNothingToCommit(err) { diff --git a/cmd/bd/dolt_test.go b/cmd/bd/dolt_test.go index 20fa221fa..5073ba179 100644 --- a/cmd/bd/dolt_test.go +++ b/cmd/bd/dolt_test.go @@ -1732,8 +1732,7 @@ func TestNoPushSkipsDoltPush(t *testing.T) { } out := captureStdout(t, func() error { - doltPushCmd.Run(doltPushCmd, nil) - return nil + return doltPushCmd.RunE(doltPushCmd, nil) }) if fake.pushCalled { @@ -1770,8 +1769,7 @@ func TestNoPushDoesNotSkipDoltPull(t *testing.T) { } out := captureStdout(t, func() error { - doltPullCmd.Run(doltPullCmd, nil) - return nil + return doltPullCmd.RunE(doltPullCmd, nil) }) if !fake.pullCalled { diff --git a/cmd/bd/errors.go b/cmd/bd/errors.go index 0ca3a981c..c3684f018 100644 --- a/cmd/bd/errors.go +++ b/cmd/bd/errors.go @@ -100,8 +100,8 @@ func HandleErrorWithHint(message, hint string) error { if jsonOutput { jsonStderrError(message, hint) } else { - fmt.Fprintf(os.Stderr, "Error: %s\n", message) - fmt.Fprintf(os.Stderr, "Hint: %s\n", hint) + fmt.Fprintf(os.Stderr, "Error: %s\n", message) //nolint:gosec // G705: stderr, not a browser context + fmt.Fprintf(os.Stderr, "Hint: %s\n", hint) //nolint:gosec // G705: stderr, not a browser context } return &exitError{Code: 1} } diff --git a/cmd/bd/formula_schema.go b/cmd/bd/formula_schema.go index ec9b81180..0f993b61f 100644 --- a/cmd/bd/formula_schema.go +++ b/cmd/bd/formula_schema.go @@ -29,25 +29,25 @@ Examples: Curated smoke-tested fixtures for wired primitives live in examples/formulas/primitives/ (with a smoke harness that proves they work).`, - Args: cobra.MaximumNArgs(1), - Run: runFormulaSchema, + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runFormulaSchema, } -func runFormulaSchema(cmd *cobra.Command, args []string) { +func runFormulaSchema(cmd *cobra.Command, args []string) error { if len(args) == 0 { - runFormulaSchemaList() - return + return runFormulaSchemaList() } - runFormulaSchemaShow(args[0]) + return runFormulaSchemaShow(args[0]) } -func runFormulaSchemaList() { +func runFormulaSchemaList() error { if jsonOutput { if err := outputJSON(formula.Primitives); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } - return + return nil } fmt.Printf("Formula schema structs (%d):\n\n", len(formula.Primitives)) @@ -57,9 +57,10 @@ func runFormulaSchemaList() { fmt.Printf("\n%s\n", ui.RenderMuted("Show fields: bd formula schema ")) fmt.Printf("%s\n", ui.RenderMuted("Wired examples: examples/formulas/primitives/")) fmt.Printf("%s\n", ui.RenderMuted("Note: schema output is structural; smoke-tested examples are the verified authoring surface.")) + return nil } -func runFormulaSchemaShow(name string) { +func runFormulaSchemaShow(name string) error { p := formula.PrimitiveByName(name) if p == nil { fmt.Fprintf(os.Stderr, "Error: unknown primitive %q\n\n", name) @@ -67,15 +68,14 @@ func runFormulaSchemaShow(name string) { for _, prim := range formula.Primitives { fmt.Fprintf(os.Stderr, " %s\n", prim.Name) } - os.Exit(1) + return SilentExit() } if jsonOutput { if err := outputJSON(p); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } - return + return nil } fmt.Printf("%s\n", ui.RenderAccent(p.Name)) @@ -87,7 +87,7 @@ func runFormulaSchemaShow(name string) { if len(p.Fields) == 0 { fmt.Printf("\n %s\n", ui.RenderMuted("(no exposed fields)")) - return + return nil } fmt.Printf("\nFields:\n") @@ -123,6 +123,7 @@ func runFormulaSchemaShow(name string) { } fmt.Println() } + return nil } func firstDocLine(doc string) string { diff --git a/cmd/bd/formula_schema_test.go b/cmd/bd/formula_schema_test.go index 517cbcc6f..1a913685d 100644 --- a/cmd/bd/formula_schema_test.go +++ b/cmd/bd/formula_schema_test.go @@ -14,8 +14,7 @@ func TestFormulaSchemaList_HumanOutput(t *testing.T) { defer func() { jsonOutput = prevJSON }() out := captureStdout(t, func() error { - runFormulaSchemaList() - return nil + return runFormulaSchemaList() }) for _, prim := range formula.Primitives { @@ -34,8 +33,7 @@ func TestFormulaSchemaList_JSON(t *testing.T) { defer func() { jsonOutput = prevJSON }() out := captureStdout(t, func() error { - runFormulaSchemaList() - return nil + return runFormulaSchemaList() }) // outputJSON injects a schema_version on objects but passes arrays @@ -55,8 +53,7 @@ func TestFormulaSchemaShow_RendersFields(t *testing.T) { defer func() { jsonOutput = prevJSON }() out := captureStdout(t, func() error { - runFormulaSchemaShow("loop") - return nil + return runFormulaSchemaShow("loop") }) for _, want := range []string{"LoopSpec", "count", "until", "max", "range", "var", "body", "[]*Step"} { @@ -73,8 +70,7 @@ func TestFormulaSchemaShow_AliasResolution(t *testing.T) { for _, input := range []string{"on_complete", "OnComplete", "OnCompleteSpec"} { out := captureStdout(t, func() error { - runFormulaSchemaShow(input) - return nil + return runFormulaSchemaShow(input) }) if !strings.Contains(out, "OnCompleteSpec") { t.Errorf("%q did not resolve to OnCompleteSpec; output:\n%s", input, out) @@ -105,8 +101,7 @@ func TestFormulaSchemaShow_JSON(t *testing.T) { defer func() { jsonOutput = prevJSON }() out := captureStdout(t, func() error { - runFormulaSchemaShow("loop") - return nil + return runFormulaSchemaShow("loop") }) // Single-primitive output goes through outputJSON which injects diff --git a/cmd/bd/help_all.go b/cmd/bd/help_all.go index 467674186..b65d88586 100644 --- a/cmd/bd/help_all.go +++ b/cmd/bd/help_all.go @@ -47,18 +47,21 @@ func registerHelpAllFlag() { // Wrap the existing Run to check --all, --doc, and --list first originalRun := cmd.Run - cmd.Run = func(cmd *cobra.Command, args []string) { + cmd.Run = nil + cmd.SilenceUsage = true + cmd.SilenceErrors = true + cmd.RunE = func(cmd *cobra.Command, args []string) error { if helpDocsRootFlag != "" { if err := writeGeneratedCLIDocs(rootCmd, helpDocsRootFlag, helpDocsVersionFlag); err != nil { fmt.Fprintln(os.Stderr, err) - os.Exit(1) + return SilentExit() } - return + return nil } if helpListFlag { // Handle --list flag: list all available commands listAllCommands(os.Stdout, rootCmd) - return + return nil } if helpDocFlag != "" { // Handle --doc flag: generate single command docs @@ -69,17 +72,18 @@ func registerHelpAllFlag() { if err := writeSingleCommandDoc(os.Stdout, rootCmd, cmdPath); err != nil { fmt.Fprintln(os.Stderr, err) fmt.Fprintf(os.Stderr, "Available commands: %s\n", strings.Join(availableCommandNames(rootCmd), " ")) - os.Exit(1) + return SilentExit() } - return + return nil } if helpAllFlag { writeAllHelp(os.Stdout, rootCmd) - return + return nil } if originalRun != nil { originalRun(cmd, args) } + return nil } return } diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 990ed04ef..f60c5183d 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -987,8 +987,7 @@ var rootCmd = &cobra.Command{ fmt.Fprintf(os.Stderr, "Error: no beads database found\n") fmt.Fprintf(os.Stderr, "Hint: %s\n", diagHint()) fmt.Fprintf(os.Stderr, " or set BEADS_DIR to point to your .beads directory\n") - metrics.CloseAndFlush() - os.Exit(1) + return SilentExit() } if dbPath == "" { @@ -1189,8 +1188,7 @@ var rootCmd = &cobra.Command{ if err != nil { // Check for fresh clone scenario if handleFreshCloneError(err) { - metrics.CloseAndFlush() - os.Exit(1) + return SilentExit() } // Schema skew gets dedicated UX with actionable rebuild instructions. var skewErr *schema.SchemaSkewError @@ -1200,8 +1198,7 @@ var rootCmd = &cobra.Command{ } else { fmt.Fprint(os.Stderr, skewErr.UserMessage()) } - metrics.CloseAndFlush() - os.Exit(1) + return SilentExit() } // #4259: the remote-migrate gate blocks silent in-place migration of a // remote-backed database and tells the operator to migrate-or-adopt. @@ -1212,8 +1209,7 @@ var rootCmd = &cobra.Command{ } else { fmt.Fprint(os.Stderr, gateErr.UserMessage()) } - metrics.CloseAndFlush() - os.Exit(1) + return SilentExit() } return HandleError("failed to open database: %v", err) } @@ -1240,7 +1236,9 @@ var rootCmd = &cobra.Command{ // Skip for --global: the global database uses a sentinel project ID // that won't match any project's metadata.json. if !useReadOnly && !globalFlag && os.Getenv("BEADS_SKIP_IDENTITY_CHECK") != "1" { - validateWorkspaceIdentity(rootCtx, beadsDir) + if err := validateWorkspaceIdentity(rootCtx, beadsDir); err != nil { + return err + } } // Initialize hook runner @@ -1525,25 +1523,25 @@ func flushBatchCommitOnShutdown() { // 1. Read commands are safe even against wrong databases (no data mutation) // 2. The check requires an open store connection // 3. New databases won't have _project_id yet (bootstrap case) -func validateWorkspaceIdentity(ctx context.Context, beadsDir string) { +func validateWorkspaceIdentity(ctx context.Context, beadsDir string) error { if store == nil { - return // No store connection, nothing to validate + return nil // No store connection, nothing to validate } // Load project_id from metadata.json cfg, err := configfile.Load(beadsDir) if err != nil || cfg == nil { - return // No config, skip validation (fresh init) + return nil // No config, skip validation (fresh init) } configProjectID := cfg.ProjectID if configProjectID == "" { - return // No project_id in config (pre-identity era) + return nil // No project_id in config (pre-identity era) } // Get project_id from database dbProjectID, err := store.GetMetadata(ctx, "_project_id") if err != nil || dbProjectID == "" { - return // No project_id in DB (new or pre-identity database) + return nil // No project_id in DB (new or pre-identity database) } // Compare: mismatch means drift @@ -1559,9 +1557,9 @@ func validateWorkspaceIdentity(ctx context.Context, beadsDir string) { fmt.Fprintf(os.Stderr, "Recovery: run 'bd doctor --fix' or 'bd bootstrap' to reconcile workspace metadata with the authoritative database when shared-server metadata drifted.\n") fmt.Fprintf(os.Stderr, "To diagnose: bd context --json\n") fmt.Fprintf(os.Stderr, "To override: set BEADS_SKIP_IDENTITY_CHECK=1\n") - metrics.CloseAndFlush() - os.Exit(1) + return SilentExit() } + return nil } func main() { diff --git a/cmd/bd/preflight.go b/cmd/bd/preflight.go index 8f32c358d..a813fd161 100644 --- a/cmd/bd/preflight.go +++ b/cmd/bd/preflight.go @@ -83,8 +83,7 @@ func runPreflight(cmd *cobra.Command, args []string) error { skipLint, _ := cmd.Flags().GetBool("skip-lint") if fix { - runFixes(jsonOutput) - return nil + return runFixes(jsonOutput) } if check { @@ -577,7 +576,7 @@ type fixResult struct { } // runFixes executes auto-fix operations for fixable preflight checks. -func runFixes(jsonOutput bool) { +func runFixes(jsonOutput bool) error { var results []fixResult hasError := false @@ -614,9 +613,9 @@ func runFixes(jsonOutput bool) { fmt.Fprintf(os.Stderr, "Error encoding fix results: %v\n", err) } if hasError { - os.Exit(1) + return SilentExit() } - return + return nil } for _, r := range results { @@ -635,8 +634,9 @@ func runFixes(jsonOutput bool) { } if hasError { - os.Exit(1) + return SilentExit() } + return nil } // fixNixHash computes and updates the vendorHash in default.nix. diff --git a/cmd/bd/ready_input.go b/cmd/bd/ready_input.go index ca5a625e9..d6f5cccae 100644 --- a/cmd/bd/ready_input.go +++ b/cmd/bd/ready_input.go @@ -1,8 +1,6 @@ package main import ( - "fmt" - "os" "strings" "github.com/spf13/cobra" @@ -148,12 +146,10 @@ func gatherReadyInput(cmd *cobra.Command) (readyInput, error) { for _, mf := range metadataFieldFlags { k, v, ok := strings.Cut(mf, "=") if !ok || k == "" { - fmt.Fprintf(os.Stderr, "Error: invalid --metadata-field: expected key=value, got %q\n", mf) - os.Exit(1) + return in, HandleError("invalid --metadata-field: expected key=value, got %q", mf) } if err := storage.ValidateMetadataKey(k); err != nil { - fmt.Fprintf(os.Stderr, "Error: invalid --metadata-field key: %v\n", err) - os.Exit(1) + return in, HandleError("invalid --metadata-field key: %v", err) } in.filter.MetadataFields[k] = v } @@ -161,8 +157,7 @@ func gatherReadyInput(cmd *cobra.Command) (readyInput, error) { hasMetadataKey, _ := cmd.Flags().GetString("has-metadata-key") if hasMetadataKey != "" { if err := storage.ValidateMetadataKey(hasMetadataKey); err != nil { - fmt.Fprintf(os.Stderr, "Error: invalid --has-metadata-key: %v\n", err) - os.Exit(1) + return in, HandleError("invalid --has-metadata-key: %v", err) } in.filter.HasMetadataKey = hasMetadataKey } diff --git a/cmd/bd/reopen_proxied_server.go b/cmd/bd/reopen_proxied_server.go index f577a9783..7b0a6cd90 100644 --- a/cmd/bd/reopen_proxied_server.go +++ b/cmd/bd/reopen_proxied_server.go @@ -80,7 +80,7 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri _ = outputJSON(reopenedIssues) } if hasError { - os.Exit(1) + return SilentExit() } return nil } diff --git a/cmd/bd/restore.go b/cmd/bd/restore.go index da0cc71cb..56f5289a8 100644 --- a/cmd/bd/restore.go +++ b/cmd/bd/restore.go @@ -15,9 +15,11 @@ import ( var restoreApply bool var restoreCmd = &cobra.Command{ - Use: "restore ", - GroupID: "sync", - Short: "Restore the pre-compaction content of a compacted issue", + Use: "restore ", + GroupID: "sync", + SilenceUsage: true, + SilenceErrors: true, + Short: "Restore the pre-compaction content of a compacted issue", Long: `Restore the pre-compaction content of a compacted issue. When an issue is compacted, its description/design/notes/acceptance criteria @@ -32,7 +34,7 @@ If no archived snapshot exists (e.g. the issue was compacted by an older bd before snapshot archiving), restore falls back to a best-effort reconstruction from Dolt version history, which can only be displayed, not applied.`, Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + RunE: func(cmd *cobra.Command, args []string) error { issueID := args[0] ctx := rootCtx @@ -44,22 +46,21 @@ from Dolt version history, which can only be displayed, not applied.`, } else { fmt.Fprintf(os.Stderr, "Error: issue '%s' not found: %v\n", issueID, err) } - os.Exit(1) + return SilentExit() } // Check if issue is compacted if issue.CompactionLevel == 0 { fmt.Fprintf(os.Stderr, "Error: issue %s is not compacted\n", issueID) fmt.Fprintf(os.Stderr, "Hint: only compacted issues need restoration\n") - os.Exit(1) + return SilentExit() } // Prefer the archived snapshot: it is the authoritative pre-compaction // copy and the only source that can be safely written back. snap, err := store.GetCompactionSnapshot(ctx, issueID) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to read compaction snapshot: %v\n", err) - os.Exit(1) + return HandleError("failed to read compaction snapshot: %v", err) } if restoreApply { @@ -68,31 +69,28 @@ from Dolt version history, which can only be displayed, not applied.`, fmt.Fprintf(os.Stderr, "Hint: this issue was compacted before snapshot archiving existed.\n") fmt.Fprintf(os.Stderr, " Run 'bd restore %s' (without --apply) to view the best-effort\n", issueID) fmt.Fprintf(os.Stderr, " version reconstructed from Dolt history.\n") - os.Exit(1) + return SilentExit() } applied, err := store.RestoreFromSnapshot(ctx, issueID) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to restore issue: %v\n", err) - os.Exit(1) + return HandleError("failed to restore issue: %v", err) } if applied == nil { - fmt.Fprintf(os.Stderr, "Error: no archived snapshot for %s\n", issueID) - os.Exit(1) + return HandleError("no archived snapshot for %s", issueID) } restored, err := store.GetIssue(ctx, issueID) if err != nil { - fmt.Fprintf(os.Stderr, "Error: restored, but failed to re-read issue: %v\n", err) - os.Exit(1) + return HandleError("restored, but failed to re-read issue: %v", err) } if jsonOutput { if err := outputJSON(restored); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) } - return + return nil } fmt.Printf("%s Restored %s from archived snapshot (compaction level %d → %d)\n", ui.RenderPass("✓"), issueID, issue.CompactionLevel, restored.CompactionLevel) - return + return nil } // Read-only display path. Prefer the archived snapshot; fall back to the @@ -107,20 +105,19 @@ from Dolt version history, which can only be displayed, not applied.`, displayRestoredIssue(view, "archived snapshot") fmt.Printf("%s\n", ui.RenderMuted("Run 'bd restore "+issueID+" --apply' to write this content back.")) } - return + return nil } // Query Dolt history for the pre-compaction version history, err := store.History(ctx, issueID) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to query history: %v\n", err) - os.Exit(1) + return HandleError("failed to query history: %v", err) } if len(history) == 0 { fmt.Fprintf(os.Stderr, "Error: no history found for issue %s\n", issueID) fmt.Fprintf(os.Stderr, "Hint: issue may have been compacted before Dolt history was available\n") - os.Exit(1) + return SilentExit() } // Find the pre-compaction version: the history entry with the most content. @@ -138,7 +135,7 @@ from Dolt version history, which can only be displayed, not applied.`, if best == nil || bestSize <= issueContentSize(issue) { fmt.Fprintf(os.Stderr, "Error: no pre-compaction version found in Dolt history\n") fmt.Fprintf(os.Stderr, "Hint: issue may have been compacted before Dolt history was available\n") - os.Exit(1) + return SilentExit() } if jsonOutput { @@ -152,6 +149,7 @@ from Dolt version history, which can only be displayed, not applied.`, } displayRestoredIssue(best.Issue, "Dolt commit "+hashDisplay) } + return nil }, } diff --git a/cmd/bd/show_proxied_server.go b/cmd/bd/show_proxied_server.go index a30cc5f49..9f1cb5dc9 100644 --- a/cmd/bd/show_proxied_server.go +++ b/cmd/bd/show_proxied_server.go @@ -470,7 +470,7 @@ func runShowProxiedDefault(ctx context.Context, uw uow.UnitOfWork, in *showProxi return HandleErrorRespectJSON("no issues found matching the provided IDs") } } else if foundCount == 0 { - os.Exit(1) + return SilentExit() } return nil } diff --git a/cmd/bd/unclaim.go b/cmd/bd/unclaim.go index a07c41e34..d972b6815 100644 --- a/cmd/bd/unclaim.go +++ b/cmd/bd/unclaim.go @@ -79,13 +79,12 @@ Examples: if jsonOutput && len(unclaimedIssues) > 0 { if err := outputJSON(unclaimedIssues); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } } if hasError { - os.Exit(1) + return SilentExit() } return nil }, diff --git a/cmd/bd/update_proxied_server.go b/cmd/bd/update_proxied_server.go index 233e4fcfc..71fc631d5 100644 --- a/cmd/bd/update_proxied_server.go +++ b/cmd/bd/update_proxied_server.go @@ -55,7 +55,7 @@ func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri _ = outputJSON(updated) } if !anyUpdated { - os.Exit(1) + return SilentExit() } return nil }