feat(app): make -json opt-in via App.JSON (v1.3.0)
App now registers -json only when App.JSON is true, so a CLI whose commands do not use cli.Emit never advertises a flag it cannot honor. Driven by the first real consumer (evpnc), whose commands print text directly and are not yet converted to Emit. The example opts in (JSON: true). Backward-additive: existing App users that want -json set JSON: true. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -55,6 +55,10 @@ type App[C any] struct {
|
||||
Root *Node[C]
|
||||
// Greeting, if set, is printed after the version banner in interactive mode.
|
||||
Greeting string
|
||||
// JSON, when true, registers a -json flag that switches Emit to JSON output.
|
||||
// Leave it false for CLIs whose commands do not (yet) use cli.Emit, so they
|
||||
// never advertise a flag they cannot honor.
|
||||
JSON bool
|
||||
|
||||
// DefaultServer is the -server default. If both it and ServerEnv are empty,
|
||||
// no -server flag is registered (local CLI).
|
||||
@@ -109,7 +113,10 @@ func (a *App[C]) Run(ctx context.Context, argv []string) error {
|
||||
serverFlag = fs.String("server", defaultServer, usage)
|
||||
}
|
||||
color := fs.Bool("color", true, "colorize output (default: on in the shell, off one-shot)")
|
||||
jsonOut := fs.Bool("json", false, "emit JSON instead of text")
|
||||
var jsonOut *bool
|
||||
if a.JSON {
|
||||
jsonOut = fs.Bool("json", false, "emit JSON instead of text")
|
||||
}
|
||||
showVersion := fs.Bool("version", false, "print version and exit")
|
||||
if a.RegisterFlags != nil {
|
||||
a.RegisterFlags(fs)
|
||||
@@ -125,7 +132,8 @@ func (a *App[C]) Run(ctx context.Context, argv []string) error {
|
||||
fmt.Println(a.versionLine())
|
||||
return nil
|
||||
}
|
||||
if *jsonOut {
|
||||
jsonMode := jsonOut != nil && *jsonOut
|
||||
if jsonMode {
|
||||
SetFormat(FormatJSON)
|
||||
}
|
||||
|
||||
@@ -145,7 +153,7 @@ func (a *App[C]) Run(ctx context.Context, argv []string) error {
|
||||
if colorExplicit {
|
||||
colorOn = *color
|
||||
}
|
||||
if *jsonOut {
|
||||
if jsonMode {
|
||||
colorOn = false
|
||||
}
|
||||
SetColor(colorOn)
|
||||
|
||||
Reference in New Issue
Block a user