From 4b09d2ee3d4ae288c19b55307cd0fb125b8fc5dd Mon Sep 17 00:00:00 2001 From: Willie Date: Fri, 6 Mar 2026 00:19:16 +0800 Subject: [PATCH] fix(cli): redirect JSON-mode UI to /dev/null and add status --project --json suppressUIToStderr was redirecting UI to stderr, but in environments where stdout and stderr share the same terminal (e.g. docker exec), all the spinner/progress/header output was still visible alongside the JSON. Replace with suppressUIToDevnull which opens os.DevNull for both os.Stdout and ui.ProgressWriter, producing zero visible noise in --json mode. Also add status --json support for project mode, reusing the same JSON schema as global mode (source, skill_count, tracked_repos, targets, audit, version). --- cmd/skillshare/install.go | 2 +- cmd/skillshare/json_output.go | 30 ++++++++++ cmd/skillshare/json_output_test.go | 67 ++++++++++++++++++++++ cmd/skillshare/status.go | 22 ++++---- cmd/skillshare/status_project.go | 81 +++++++++++++++++++++++++++ cmd/skillshare/update.go | 56 ++++++++++-------- tests/integration/json_output_test.go | 28 ++++++++- 7 files changed, 251 insertions(+), 35 deletions(-) create mode 100644 cmd/skillshare/json_output_test.go diff --git a/cmd/skillshare/install.go b/cmd/skillshare/install.go index b48a7084d..f29184665 100644 --- a/cmd/skillshare/install.go +++ b/cmd/skillshare/install.go @@ -307,7 +307,7 @@ func cmdInstall(args []string) error { // logo, spinner, step, and handler output don't corrupt stdout. var restoreUI func() if parsed.jsonOutput { - restoreUI = suppressUIToStderr() + restoreUI = suppressUIToDevnull() } cfg, err := config.Load() diff --git a/cmd/skillshare/json_output.go b/cmd/skillshare/json_output.go index 01ce67376..837c776f6 100644 --- a/cmd/skillshare/json_output.go +++ b/cmd/skillshare/json_output.go @@ -7,6 +7,8 @@ import ( "reflect" "slices" "time" + + "skillshare/internal/ui" ) // writeJSON pretty-prints v as JSON to stdout. @@ -39,6 +41,34 @@ func writeJSONError(err error) error { return &jsonSilentError{cause: err} } +// suppressUIToDevnull temporarily redirects os.Stdout and the progress +// writer to /dev/null so that handler functions using fmt.Printf / ui.* +// produce zero visible output. This keeps --json output clean even when +// stdout and stderr share the same terminal (e.g. docker exec). +// Returns a restore function that MUST be called before writing JSON. +func suppressUIToDevnull() func() { + devnull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) + if err != nil { + // Fallback: redirect to stderr (better than nothing) + devnull = os.Stderr + } + origStdout := os.Stdout + os.Stdout = devnull + + prevProgress := ui.ProgressWriter + ui.SetProgressWriter(devnull) + ui.SuppressProgress() + + return func() { + os.Stdout = origStdout + ui.SetProgressWriter(prevProgress) + ui.RestoreProgress() + if devnull != os.Stderr { + devnull.Close() + } + } +} + // formatDuration returns a human-readable duration string truncated to milliseconds. func formatDuration(start time.Time) string { return time.Since(start).Truncate(time.Millisecond).String() diff --git a/cmd/skillshare/json_output_test.go b/cmd/skillshare/json_output_test.go new file mode 100644 index 000000000..db689a1cb --- /dev/null +++ b/cmd/skillshare/json_output_test.go @@ -0,0 +1,67 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "testing" +) + +func TestWriteJSONError(t *testing.T) { + tmpFile, err := os.CreateTemp("", "skillshare-json-output-") + if err != nil { + t.Fatalf("creating temp file: %v", err) + } + t.Cleanup(func() { os.Remove(tmpFile.Name()) }) + defer tmpFile.Close() + + oldStdout := os.Stdout + os.Stdout = tmpFile + + outErr := writeJSONError(errors.New("sync failed")) + + tmpFile.Close() + os.Stdout = oldStdout + + data, readErr := os.ReadFile(tmpFile.Name()) + if readErr != nil { + t.Fatalf("reading captured stdout: %v", readErr) + } + + var output map[string]any + if err := json.Unmarshal(bytes.TrimSpace(data), &output); err != nil { + t.Fatalf("invalid JSON output: %v\nStdout: %s", err, string(data)) + } + if got, ok := output["error"]; !ok { + t.Fatalf("missing error field in JSON output: %v", output) + } else if got != "sync failed" { + t.Fatalf("unexpected error field: %v", got) + } + + var silent *jsonSilentError + if !errors.As(outErr, &silent) { + t.Fatalf("expected writeJSONError to return *jsonSilentError, got %T", outErr) + } + if silent.Error() != "sync failed" { + t.Fatalf("unexpected silent error message: %v", silent.Error()) + } +} + +func TestWriteJSONErrorIsWrappedWithErrorsAs(t *testing.T) { + inner := writeJSONError(errors.New("wrapped sync failed")) + if inner == nil { + t.Fatalf("unexpected nil error") + } + + outer := fmt.Errorf("command wrapper: %w", inner) + + var silent *jsonSilentError + if !errors.As(outer, &silent) { + t.Fatalf("expected wrapped error to be recognized via errors.As as *jsonSilentError") + } + if silent == nil || silent.Error() == "" { + t.Fatal("expected wrapped error unwrap chain to include jsonSilentError") + } +} diff --git a/cmd/skillshare/status.go b/cmd/skillshare/status.go index 3a84b5f49..5e8ccc977 100644 --- a/cmd/skillshare/status.go +++ b/cmd/skillshare/status.go @@ -18,17 +18,17 @@ import ( // statusJSONOutput is the JSON representation for status --json output. type statusJSONOutput struct { - Source statusJSONSource `json:"source"` - SkillCount int `json:"skill_count"` - TrackedRepos []statusJSONRepo `json:"tracked_repos"` - Targets []statusJSONTarget `json:"targets"` - Audit statusJSONAudit `json:"audit"` - Version string `json:"version"` + Source statusJSONSource `json:"source"` + SkillCount int `json:"skill_count"` + TrackedRepos []statusJSONRepo `json:"tracked_repos"` + Targets []statusJSONTarget `json:"targets"` + Audit statusJSONAudit `json:"audit"` + Version string `json:"version"` } type statusJSONSource struct { - Path string `json:"path"` - Exists bool `json:"exists"` + Path string `json:"path"` + Exists bool `json:"exists"` } type statusJSONRepo struct { @@ -78,15 +78,15 @@ func cmdStatus(args []string) error { jsonOutput := hasFlag(rest, "--json") if mode == modeProject { - if jsonOutput { - return fmt.Errorf("--json is not yet supported in project mode") - } // Reject unexpected positional arguments in project mode for _, arg := range rest { if arg != "--json" { return fmt.Errorf("unexpected arguments: %v", rest) } } + if jsonOutput { + return cmdStatusProjectJSON(cwd) + } return cmdStatusProject(cwd) } diff --git a/cmd/skillshare/status_project.go b/cmd/skillshare/status_project.go index 945c90c34..7e8198d41 100644 --- a/cmd/skillshare/status_project.go +++ b/cmd/skillshare/status_project.go @@ -6,6 +6,7 @@ import ( "path/filepath" "strings" + "skillshare/internal/audit" "skillshare/internal/sync" "skillshare/internal/ui" ) @@ -40,6 +41,86 @@ func cmdStatusProject(root string) error { return nil } +func cmdStatusProjectJSON(root string) error { + if !projectConfigExists(root) { + if err := performProjectInit(root, projectInitOptions{}); err != nil { + return writeJSONError(err) + } + } + + runtime, err := loadProjectRuntime(root) + if err != nil { + return writeJSONError(err) + } + + discovered, _ := sync.DiscoverSourceSkills(runtime.sourcePath) + trackedRepos := extractTrackedRepos(discovered) + + output := statusJSONOutput{ + Source: statusJSONSource{ + Path: runtime.sourcePath, + Exists: dirExists(runtime.sourcePath), + }, + SkillCount: len(discovered), + Version: version, + } + + // Tracked repos + for _, repoName := range trackedRepos { + repoPath := filepath.Join(runtime.sourcePath, repoName) + skillCount := 0 + for _, d := range discovered { + if d.IsInRepo && strings.HasPrefix(d.RelPath, repoName+"/") { + skillCount++ + } + } + dirty, _ := isRepoDirty(repoPath) + output.TrackedRepos = append(output.TrackedRepos, statusJSONRepo{ + Name: repoName, + SkillCount: skillCount, + Dirty: dirty, + }) + } + + // Targets + for _, entry := range runtime.config.Targets { + target, ok := runtime.targets[entry.Name] + if !ok { + continue + } + mode := target.Mode + if mode == "" { + mode = "merge" + } + res := getTargetStatusDetail(target, runtime.sourcePath, mode) + output.Targets = append(output.Targets, statusJSONTarget{ + Name: entry.Name, + Path: target.Path, + Mode: mode, + Status: res.statusStr, + SyncedCount: res.syncedCount, + Include: target.Include, + Exclude: target.Exclude, + }) + } + + // Audit + policy := audit.ResolvePolicy(audit.PolicyInputs{ + ConfigProfile: runtime.config.Audit.Profile, + ConfigThreshold: runtime.config.Audit.BlockThreshold, + ConfigDedupe: runtime.config.Audit.DedupeMode, + ConfigAnalyzers: runtime.config.Audit.EnabledAnalyzers, + }) + output.Audit = statusJSONAudit{ + Profile: string(policy.Profile), + Threshold: policy.Threshold, + Dedupe: string(policy.DedupeMode), + Analyzers: policy.EnabledAnalyzers, + } + + return writeJSON(&output) +} + func printProjectSourceStatus(sourcePath string, skillCount int) { ui.Header("Source (project)") info, err := os.Stat(sourcePath) diff --git a/cmd/skillshare/update.go b/cmd/skillshare/update.go index a9e5712f5..e60f1cebd 100644 --- a/cmd/skillshare/update.go +++ b/cmd/skillshare/update.go @@ -31,18 +31,18 @@ type updateOptions struct { // updateJSONOutput is the JSON representation for update --json output. type updateJSONOutput struct { - Updated int `json:"updated"` - Skipped int `json:"skipped"` - SecurityFailed int `json:"security_failed"` - Pruned int `json:"pruned"` - DryRun bool `json:"dry_run"` - Duration string `json:"duration"` - Items []updateJSONItem `json:"items"` + Updated int `json:"updated"` + Skipped int `json:"skipped"` + SecurityFailed int `json:"security_failed"` + Pruned int `json:"pruned"` + DryRun bool `json:"dry_run"` + Duration string `json:"duration"` + Items []updateJSONItem `json:"items"` } type updateJSONItem struct { Name string `json:"name"` - Type string `json:"type"` // "repo" or "skill" + Type string `json:"type"` // "repo" or "skill" Status string `json:"status"` // "updated", "skipped", "failed", "security_blocked" Error string `json:"error,omitempty"` } @@ -133,11 +133,15 @@ func cmdUpdate(args []string) error { if mode == modeProject { // Parse opts for logging (cmdUpdateProject parses again internally) projOpts, _, _ := parseUpdateArgs(rest) - err := cmdUpdateProject(rest, cwd) - logUpdateOp(config.ProjectConfigPath(cwd), rest, projOpts, "project", start, err, nil) if projOpts != nil && projOpts.jsonOutput { - return updateOutputJSON(nil, projOpts.dryRun, start, err) + restore := suppressUIToDevnull() + result, err := cmdUpdateProject(rest, cwd) + restore() + logUpdateOp(config.ProjectConfigPath(cwd), rest, projOpts, "project", start, err, result) + return updateOutputJSON(result, projOpts.dryRun, start, err) } + result, err := cmdUpdateProject(rest, cwd) + logUpdateOp(config.ProjectConfigPath(cwd), rest, projOpts, "project", start, err, result) return err } @@ -161,6 +165,13 @@ func cmdUpdate(args []string) error { opts.threshold = cfg.Audit.BlockThreshold } + // In JSON mode, redirect all UI output to stderr early so the + // header, step, spinner, and handler output don't corrupt stdout. + var restoreUI func() + if opts.jsonOutput { + restoreUI = suppressUIToDevnull() + } + ui.Header(ui.WithModeLabel("Updating")) ui.StepStart("Source", cfg.Source) @@ -330,11 +341,13 @@ func cmdUpdate(args []string) error { if len(targets) == 1 { // Single target: verbose path t := targets[0] + + var r updateResult var updateErr error if t.isRepo { - updateErr = updateTrackedRepo(uc, t.name) + r, updateErr = updateTrackedRepo(uc, t.name) } else { - updateErr = updateRegularSkill(uc, t.name) + r, updateErr = updateRegularSkill(uc, t.name) } var opNames []string @@ -343,15 +356,10 @@ func cmdUpdate(args []string) error { } else { opNames = opts.names } - logUpdateOp(config.ConfigPath(), opNames, opts, "global", start, updateErr, nil) + logUpdateOp(config.ConfigPath(), opNames, opts, "global", start, updateErr, &r) if opts.jsonOutput { - var r *updateResult - if updateErr == nil { - r = &updateResult{updated: 1} - } else { - r = &updateResult{skipped: 1} - } - return updateOutputJSON(r, opts.dryRun, start, updateErr) + restoreUI() + return updateOutputJSON(&r, opts.dryRun, start, updateErr) } return updateErr } @@ -376,6 +384,7 @@ func cmdUpdate(args []string) error { logUpdateOp(config.ConfigPath(), opNames, opts, "global", start, batchErr, &batchResult) if opts.jsonOutput { + restoreUI() return updateOutputJSON(&batchResult, opts.dryRun, start, batchErr) } return batchErr @@ -396,7 +405,10 @@ func updateOutputJSON(result *updateResult, dryRun bool, start time.Time, update if writeErr := writeJSON(&output); writeErr != nil { return writeErr } - return updateErr + if updateErr != nil { + return &jsonSilentError{cause: updateErr} + } + return nil } func logUpdateOp(cfgPath string, names []string, opts *updateOptions, mode string, start time.Time, cmdErr error, result *updateResult) { diff --git a/tests/integration/json_output_test.go b/tests/integration/json_output_test.go index ca3b5c8d2..ae1978793 100644 --- a/tests/integration/json_output_test.go +++ b/tests/integration/json_output_test.go @@ -585,7 +585,33 @@ func TestUninstall_JSON_PreflightEmpty_ReturnsJSONError(t *testing.T) { t.Skip("--json implies --force, cannot test preflight block in JSON mode") } -// --- update --json single target (P1: verify suppressUIToStderr works) --- +// --- status --project --json --- + +func TestStatus_Project_JSON(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + projectDir := sb.Root + "/status-project" + sb.WriteFile(projectDir+"/.skillshare/config.yaml", + "targets:\n - name: claude\n path: "+projectDir+"/.claude/commands\n") + sb.WriteFile(projectDir+"/.claude/commands/.gitkeep", "") + sb.WriteFile(projectDir+"/.skillshare/skills/alpha/SKILL.md", "# Alpha") + + result := sb.RunCLIInDir(projectDir, "status", "--project", "--json") + result.AssertSuccess(t) + + stdout := strings.TrimSpace(result.Stdout) + assertPureJSON(t, stdout) + + output := parseJSON(t, result.Stdout) + for _, field := range []string{"source", "skill_count", "targets", "audit", "version"} { + if _, ok := output[field]; !ok { + t.Errorf("missing field %q in JSON output", field) + } + } +} + +// --- update --json single target (P1: verify suppressUIToDevnull works) --- func TestUpdate_JSON_SingleTarget_PureJSON(t *testing.T) { sb := testutil.NewSandbox(t)