fix(audit): show spinner/progress on stderr for structured output formats

Previously --format json/sarif completely suppressed spinner and progress
bar, making the CLI appear frozen during long scans.

Now spinner/progress output is redirected to stderr via ProgressWriter,
so progress indicators remain visible while structured data stays clean
on stdout. This follows the Unix convention: data → stdout, diagnostics
→ stderr.

Also:
- Extract fileTTY() shared helper (DRY IsTTY + isProgressTTY)
- Add format constants (formatText/JSON/SARIF) and isStructured()
- Capture/restore previous ProgressWriter in defer (defensive)
This commit is contained in:
Willie
2026-03-02 23:01:30 +08:00
parent 3bc9ad7574
commit afb8951359
3 changed files with 80 additions and 67 deletions
+39 -45
View File
@@ -19,18 +19,30 @@ import (
const largeAuditThreshold = 1000
// Output format constants for --format flag.
const (
formatText = "text"
formatJSON = "json"
formatSARIF = "sarif"
)
type auditOptions struct {
Targets []string
Groups []string
InitRules bool
JSON bool // deprecated: use Format
Format string // "text", "json", "sarif" (default: "text")
Format string // formatText, formatJSON, or formatSARIF (default: formatText)
Quiet bool
Yes bool
NoTUI bool
Threshold string
}
// isStructured returns true if the output format is machine-readable (json/sarif).
func (o auditOptions) isStructured() bool {
return o.Format == formatJSON || o.Format == formatSARIF
}
type auditRunSummary struct {
Scope string `json:"scope,omitempty"`
Skill string `json:"skill,omitempty"`
@@ -95,11 +107,18 @@ func cmdAudit(args []string) error {
if opts.JSON {
fmt.Fprintln(os.Stderr, "warning: --json is deprecated, use --format json")
if opts.Format == "" {
opts.Format = "json"
opts.Format = formatJSON
}
}
if opts.Format == "" {
opts.Format = "text"
opts.Format = formatText
}
// Redirect spinner/progress output to stderr for structured formats
// so progress indicators don't corrupt JSON/SARIF on stdout.
if opts.isStructured() {
prev := ui.ProgressWriter
ui.SetProgressWriter(os.Stderr)
defer ui.SetProgressWriter(prev)
}
if opts.InitRules {
if mode == modeProject {
@@ -179,7 +198,7 @@ func cmdAudit(args []string) error {
logAuditOp(cfgPath, rest, summary, start, nil, blocked)
switch opts.Format {
case "sarif":
case formatSARIF:
log := audit.ToSARIF(results, audit.SARIFOptions{ToolVersion: versionpkg.Version})
out, _ := json.MarshalIndent(log, "", " ")
fmt.Println(string(out))
@@ -187,7 +206,7 @@ func cmdAudit(args []string) error {
os.Exit(1)
}
return nil
case "json":
case formatJSON:
out, _ := json.MarshalIndent(auditJSONOutput{
Results: results,
Summary: summary,
@@ -230,7 +249,7 @@ func parseAuditArgs(args []string) (auditOptions, bool, error) {
}
i++
switch args[i] {
case "text", "json", "sarif":
case formatText, formatJSON, formatSARIF:
opts.Format = args[i]
default:
return opts, false, fmt.Errorf("unknown format: %s (supported: text, json, sarif)", args[i])
@@ -374,7 +393,7 @@ func scanPathTarget(targetPath, projectRoot string) (*audit.Result, error) {
}
func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditOptions) ([]*audit.Result, auditRunSummary, error) {
jsonOutput := opts.Format == "json" || opts.Format == "sarif"
jsonOutput := opts.isStructured()
base := auditRunSummary{
Scope: "all",
Mode: mode,
@@ -382,28 +401,17 @@ func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditO
}
// Phase 0: discover skills (with spinner).
var spinner *ui.Spinner
if !jsonOutput {
spinner = ui.StartSpinner("Discovering skills...")
}
spinner := ui.StartSpinner("Discovering skills...")
skillPaths, err := collectInstalledSkillPaths(sourcePath)
if err != nil {
if spinner != nil {
spinner.Fail("Discovery failed")
}
spinner.Fail("Discovery failed")
return nil, base, err
}
if len(skillPaths) == 0 {
if spinner != nil {
spinner.Success("No skills found")
} else {
ui.Info("No skills found in source directory")
}
spinner.Success("No skills found")
return []*audit.Result{}, base, nil
}
if spinner != nil {
spinner.Success(fmt.Sprintf("Found %d skill(s)", len(skillPaths)))
}
spinner.Success(fmt.Sprintf("Found %d skill(s)", len(skillPaths)))
// Phase 0.5: large audit confirmation prompt.
if len(skillPaths) > largeAuditThreshold && !jsonOutput && !opts.Yes && ui.IsTTY() {
@@ -426,19 +434,12 @@ func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditO
}
// Phase 1: parallel scan with progress bar.
var progressBar *ui.ProgressBar
if !jsonOutput {
progressBar = ui.StartProgress("Scanning skills", len(skillPaths))
}
progressBar := ui.StartProgress("Scanning skills", len(skillPaths))
onDone := func() {
if progressBar != nil {
progressBar.Increment()
}
progressBar.Increment()
}
scanResults := audit.ParallelScan(toAuditInputs(skillPaths), projectRoot, onDone)
if progressBar != nil {
progressBar.Stop()
}
progressBar.Stop()
// Collect results and their elapsed times together.
results := make([]*audit.Result, 0, len(skillPaths))
@@ -476,7 +477,7 @@ func auditInstalled(sourcePath, mode, projectRoot, threshold string, opts auditO
}
func auditFiltered(sourcePath string, names, groups []string, mode, projectRoot, threshold string, opts auditOptions) ([]*audit.Result, auditRunSummary, error) {
jsonOutput := opts.Format == "json" || opts.Format == "sarif"
jsonOutput := opts.isStructured()
base := auditRunSummary{
Scope: "filtered",
Mode: mode,
@@ -552,19 +553,12 @@ func auditFiltered(sourcePath string, names, groups []string, mode, projectRoot,
}
// Phase 1: parallel scan with progress bar.
var progressBar *ui.ProgressBar
if !jsonOutput {
progressBar = ui.StartProgress("Scanning skills", len(matched))
}
progressBar := ui.StartProgress("Scanning skills", len(matched))
onDone := func() {
if progressBar != nil {
progressBar.Increment()
}
progressBar.Increment()
}
scanResults := audit.ParallelScan(toAuditInputs(matched), projectRoot, onDone)
if progressBar != nil {
progressBar.Stop()
}
progressBar.Stop()
// Collect results and their elapsed times together.
results := make([]*audit.Result, 0, len(matched))
@@ -634,7 +628,7 @@ func auditSkillByName(sourcePath, name, mode, projectRoot, threshold, format str
summary.Scope = "single"
summary.Skill = name
summary.Mode = mode
if format == "text" {
if format == formatText {
subtitle := auditHeaderSubtitle(fmt.Sprintf("Scanning skill: %s", name), mode, sourcePath, threshold)
summaryLines := buildAuditSummaryLines(summary)
minWidth := auditHeaderMinWidth(subtitle)
@@ -673,7 +667,7 @@ func auditPath(rawPath, mode, projectRoot, threshold, format string) ([]*audit.R
summary.Scope = "path"
summary.Path = absPath
summary.Mode = mode
if format == "text" {
if format == formatText {
subtitle := fmt.Sprintf("Scanning path target\nmode: %s\npath: %s\nblock rule: finding severity >= %s", mode, absPath, threshold)
summaryLines := buildAuditSummaryLines(summary)
minWidth := auditHeaderMinWidth(subtitle)
+1 -1
View File
@@ -22,7 +22,7 @@ func cmdAuditProject(root, specificSkill string) (auditRunSummary, bool, error)
}
if specificSkill != "" {
_, summary, err := auditSkillByName(rt.sourcePath, specificSkill, "project", root, threshold, "text")
_, summary, err := auditSkillByName(rt.sourcePath, specificSkill, "project", root, threshold, formatText)
return summary, summary.Failed > 0, err
}
+40 -21
View File
@@ -37,12 +37,31 @@ func DisplayWidth(s string) int {
return runewidth.StringWidth(clean)
}
// IsTTY returns true if stdout is a terminal
func IsTTY() bool {
fi, _ := os.Stdout.Stat()
// fileTTY returns true if the given file descriptor is a terminal.
func fileTTY(f *os.File) bool {
fi, err := f.Stat()
if err != nil {
return false
}
return (fi.Mode() & os.ModeCharDevice) != 0
}
// IsTTY returns true if stdout is a terminal.
func IsTTY() bool { return fileTTY(os.Stdout) }
// ProgressWriter is the destination for spinner and progress bar output.
// Defaults to os.Stdout; set to os.Stderr for structured output modes
// (e.g. --format json/sarif) so progress indicators don't corrupt data.
var ProgressWriter *os.File = os.Stdout
// SetProgressWriter redirects spinner and progress bar output.
func SetProgressWriter(w *os.File) {
ProgressWriter = w
}
// isProgressTTY returns true if ProgressWriter is a terminal.
func isProgressTTY() bool { return fileTTY(ProgressWriter) }
// Box prints content in a styled box
func Box(title string, lines ...string) {
BoxWithMinWidth(title, 0, lines...)
@@ -139,27 +158,29 @@ type Spinner struct {
// StartSpinner starts a spinner with message
func StartSpinner(message string) *Spinner {
if !IsTTY() {
fmt.Printf("... %s\n", message)
if !isProgressTTY() {
fmt.Fprintf(ProgressWriter, "... %s\n", message)
return &Spinner{start: time.Now()}
}
s, _ := pterm.DefaultSpinner.
WithRemoveWhenDone(true).
WithWriter(ProgressWriter).
Start(message)
return &Spinner{spinner: s, start: time.Now()}
}
// StartSpinnerWithSteps starts a spinner that shows step progress
func StartSpinnerWithSteps(message string, totalSteps int) *Spinner {
if !IsTTY() {
fmt.Printf("... [1/%d] %s\n", totalSteps, message)
if !isProgressTTY() {
fmt.Fprintf(ProgressWriter, "... [1/%d] %s\n", totalSteps, message)
return &Spinner{start: time.Now(), currentStep: 1, totalSteps: totalSteps}
}
stepPrefix := fmt.Sprintf("[1/%d] ", totalSteps)
s, _ := pterm.DefaultSpinner.
WithRemoveWhenDone(true).
WithWriter(ProgressWriter).
Start(stepPrefix + message)
return &Spinner{
spinner: s,
@@ -183,9 +204,9 @@ func (s *Spinner) Update(message string) {
s.spinner.UpdateText(s.stepPrefix + message)
} else {
if s.totalSteps > 0 {
fmt.Printf("... [%d/%d] %s\n", s.currentStep, s.totalSteps, message)
fmt.Fprintf(ProgressWriter, "... [%d/%d] %s\n", s.currentStep, s.totalSteps, message)
} else {
fmt.Printf("... %s\n", message)
fmt.Fprintf(ProgressWriter, "... %s\n", message)
}
}
}
@@ -207,13 +228,10 @@ func (s *Spinner) Success(message string) {
msg = fmt.Sprintf("%s (%.1fs)", message, elapsed.Seconds())
}
if s.spinner != nil {
// Stop first (clears animation via RemoveWhenDone), then print.
// pterm's spinner.Success() loses the message because Stop() clears
// the line after printing. We print a lightweight ✓ instead.
s.spinner.Stop() //nolint:errcheck
fmt.Printf("%s %s\n", pterm.Green("✓"), msg)
fmt.Fprintf(ProgressWriter, "%s %s\n", pterm.Green("✓"), msg)
} else {
fmt.Printf("✓ %s\n", msg)
fmt.Fprintf(ProgressWriter, "✓ %s\n", msg)
}
}
@@ -221,9 +239,9 @@ func (s *Spinner) Success(message string) {
func (s *Spinner) Fail(message string) {
if s.spinner != nil {
s.spinner.Stop() //nolint:errcheck
fmt.Printf("%s %s\n", pterm.Red("✗"), message)
fmt.Fprintf(ProgressWriter, "%s %s\n", pterm.Red("✗"), message)
} else {
fmt.Printf("✗ %s\n", message)
fmt.Fprintf(ProgressWriter, "✗ %s\n", message)
}
}
@@ -236,9 +254,9 @@ func (s *Spinner) Warn(message string) {
}
if s.spinner != nil {
s.spinner.Stop() //nolint:errcheck
fmt.Printf("%s %s\n", pterm.Yellow("!"), msg)
fmt.Fprintf(ProgressWriter, "%s %s\n", pterm.Yellow("!"), msg)
} else {
fmt.Printf("! %s\n", msg)
fmt.Fprintf(ProgressWriter, "! %s\n", msg)
}
}
@@ -358,14 +376,15 @@ type ProgressBar struct {
// StartProgress starts a progress bar
func StartProgress(title string, total int) *ProgressBar {
if !IsTTY() {
fmt.Printf("%s (0/%d)\n", title, total)
if !isProgressTTY() {
fmt.Fprintf(ProgressWriter, "%s (0/%d)\n", title, total)
return &ProgressBar{total: total}
}
bar, _ := pterm.DefaultProgressbar.
WithTotal(total).
WithTitle(title).
WithWriter(ProgressWriter).
Start()
return &ProgressBar{bar: bar, total: total}
}
@@ -406,7 +425,7 @@ func (p *ProgressBar) UpdateTitle(title string) {
if p.bar != nil {
p.bar.UpdateTitle(display)
} else {
fmt.Printf(" %s\n", strings.TrimRight(display, " "))
fmt.Fprintf(ProgressWriter, " %s\n", strings.TrimRight(display, " "))
}
}