[Feat] Add global --output json flag for structured output#60
Conversation
Signed-off-by: samzong <samzong.lu@gmail.com>
There was a problem hiding this comment.
Code Review
This pull request introduces a global --output (or -o) flag to support both text and JSON output formats across multiple commands, including config get, tag, and several worktree subcommands. The existing --json flag in the config get command has been deprecated in favor of this new unified approach. A regression was identified in the worktree prune command where the new implementation fails to display partial reports when an error occurs mid-operation, which differs from the previous behavior.
| result, err := wtClient.Prune(opts) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if outputFormat() == "json" { | ||
| action := "removed" | ||
| if opts.DryRun { | ||
| action = "would-remove" | ||
| } | ||
| items := make([]PruneJSON, len(result.Candidates)) | ||
| for i, c := range result.Candidates { | ||
| items[i] = PruneJSON{ | ||
| Name: c.Name, | ||
| Branch: c.Branch, | ||
| Status: c.Status, | ||
| Action: action, | ||
| } | ||
| } | ||
| return printJSON(outWriter(), items) | ||
| } | ||
| printWorktreeReport(result.Report) | ||
| return nil |
There was a problem hiding this comment.
This change introduces a regression in error handling. Previously, if wtClient.Prune failed mid-operation, the partial report was still printed, giving the user information about what succeeded before the failure. With the new logic, if an error occurs, the function returns immediately, and no report (neither text nor JSON) is printed.
To preserve the old behavior and provide a better user experience, the report/JSON output should be generated before returning the error from the Prune operation.
result, err := wtClient.Prune(opts)
if outputFormat() == "json" {
action := "removed"
if opts.DryRun {
action = "would-remove"
}
items := make([]PruneJSON, len(result.Candidates))
for i, c := range result.Candidates {
items[i] = PruneJSON{
Name: c.Name,
Branch: c.Branch,
Status: c.Status,
Action: action,
}
}
if printErr := printJSON(outWriter(), items); printErr != nil {
return printErr
}
} else {
printWorktreeReport(result.Report)
}
return err
What's changed?
--output(-o) persistent flag on root command withtext(default) andjsonvaluespflag.Value(noPersistentPreRunEchaining issues)gmc wt ls -o json/gmc wt -o json: emitWorktreeJSONarray with full commit hashesgmc wt prune --dry-run -o json/gmc wt prune -o json: emit structuredPruneJSONarray viaPruneResult.Candidatesgmc wt share list -o json: emitShareJSONarraygmc config get -o json: emit config as JSON object (deprecates--jsonflag)gmc tag -o json: emitTagJSONwith current tag, suggested version, and commit messages--outputflagresolveWorktreeStatusto deduplicate status logic between text and JSON pathsPruneCandidate/PruneResultto internal worktree package for structured prune dataWhy