11package cli
22
33import (
4- "encoding/json"
54 "fmt"
65 "io"
76
@@ -18,9 +17,14 @@ type RunContext struct {
1817 Args []string
1918 Writer io.Writer
2019 Printer output.Printer
21- JSON bool
20+ Format output. Format
2221}
2322
23+ // Structured reports whether output should be a machine-readable dump (JSON or
24+ // TOON) rather than the human table/detail view. Command handlers branch on
25+ // this to suppress detail views, footers, and interactive prompts.
26+ func (ctx * RunContext ) Structured () bool { return ctx .Format .Structured () }
27+
2428// runCommand creates a client and RunContext, then calls fn.
2529// It centralises setup that every API-backed command repeats.
2630func runCommand (cmd * cobra.Command , args []string , fn func (ctx * RunContext ) error ) error {
@@ -34,7 +38,7 @@ func runCommand(cmd *cobra.Command, args []string, fn func(ctx *RunContext) erro
3438 Args : args ,
3539 Writer : cmd .OutOrStdout (),
3640 Printer : newPrinter (cmd .OutOrStdout ()),
37- JSON : flagJSON ,
41+ Format : currentOutputFormat () ,
3842 }
3943 return fn (ctx )
4044}
@@ -44,7 +48,7 @@ func (ctx *RunContext) PrintList(items any, cols []output.Column, count, page, t
4448 if err := ctx .Printer .Print (items , cols ); err != nil {
4549 return err
4650 }
47- if ! ctx .JSON {
51+ if ! ctx .Structured () {
4852 _ , _ = fmt .Fprintf (ctx .Writer , "Showing %d results (page %d, total %d).\n " , count , page , total )
4953 }
5054 return nil
@@ -55,7 +59,7 @@ func (ctx *RunContext) PrintTotal(items any, cols []output.Column, total int) er
5559 if err := ctx .Printer .Print (items , cols ); err != nil {
5660 return err
5761 }
58- if ! ctx .JSON {
62+ if ! ctx .Structured () {
5963 _ , _ = fmt .Fprintf (ctx .Writer , "Total: %d\n " , total )
6064 }
6165 return nil
@@ -66,17 +70,18 @@ func (ctx *RunContext) WriteResult(message string) {
6670 writeResult (ctx .Writer , message )
6771}
6872
69- // WriteResultJSON outputs structured data as JSON in --json mode,
70- // or a human-readable message in table mode.
73+ // WriteResultJSON outputs structured data in JSON or TOON mode, or a
74+ // human-readable message in table mode. JSON stays indented (byte-compatible
75+ // with the legacy --json path); TOON routes through the SDK marshaller.
7176func (ctx * RunContext ) WriteResultJSON (data any , humanMessage string ) error {
72- if ctx .JSON {
73- out , err := json .MarshalIndent (data , "" , " " )
74- if err != nil {
75- return fmt .Errorf ("failed to marshal JSON: %w" , err )
76- }
77- _ , _ = fmt .Fprintln (ctx .Writer , string (out ))
77+ if ! ctx .Structured () {
78+ _ , _ = fmt .Fprintln (ctx .Writer , humanMessage )
7879 return nil
7980 }
80- _ , _ = fmt .Fprintln (ctx .Writer , humanMessage )
81+ out , err := marshalStructured (data )
82+ if err != nil {
83+ return fmt .Errorf ("failed to marshal output: %w" , err )
84+ }
85+ _ , _ = fmt .Fprintln (ctx .Writer , string (out ))
8186 return nil
8287}
0 commit comments