|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | +) |
| 8 | + |
| 9 | +// CommandOutput represents the structured output format for all commands. |
| 10 | +// It provides a consistent interface for both JSON and human-readable output modes. |
| 11 | +type CommandOutput struct { |
| 12 | + // Success indicates whether the operation completed successfully |
| 13 | + Success bool `json:"success"` |
| 14 | + |
| 15 | + // Data holds generic output data (rarely used, reserved for future extensions) |
| 16 | + Data any `json:"data,omitempty"` |
| 17 | + |
| 18 | + // Claims holds the decoded JWT claims/payload |
| 19 | + Claims any `json:"claims,omitempty"` |
| 20 | + |
| 21 | + // Token holds the encoded JWT token string |
| 22 | + Token string `json:"token,omitempty"` |
| 23 | + |
| 24 | + // Error holds the error message if Success is false |
| 25 | + Error string `json:"error,omitempty"` |
| 26 | +} |
| 27 | + |
| 28 | +// output writes the command result to stdout in either JSON or human-readable format. |
| 29 | +// In JSON mode, it always outputs valid JSON regardless of success/failure. |
| 30 | +// In human-readable mode, errors are written to stderr. |
| 31 | +// Note: This function does NOT call os.Exit(). Exit handling is done by the caller |
| 32 | +// through Cobra's error return mechanism and root.Execute(). |
| 33 | +func output(out CommandOutput) { |
| 34 | + if jsonOutput { |
| 35 | + outputJSON(out) |
| 36 | + return |
| 37 | + } |
| 38 | + outputHumanReadable(out) |
| 39 | +} |
| 40 | + |
| 41 | +// outputJSON writes the output in JSON format. |
| 42 | +func outputJSON(out CommandOutput) { |
| 43 | + enc := json.NewEncoder(os.Stdout) |
| 44 | + enc.SetIndent("", " ") |
| 45 | + if err := enc.Encode(out); err != nil { |
| 46 | + // This should never happen, but if JSON encoding fails, output a minimal error |
| 47 | + fmt.Fprintf(os.Stderr, `{"success":false,"error":"failed to encode JSON output: %s"}`+"\n", err) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +// outputHumanReadable writes the output in human-readable format. |
| 52 | +func outputHumanReadable(out CommandOutput) { |
| 53 | + if out.Error != "" { |
| 54 | + fmt.Fprintln(os.Stderr, out.Error) |
| 55 | + return |
| 56 | + } |
| 57 | + if out.Token != "" { |
| 58 | + fmt.Println(out.Token) |
| 59 | + } |
| 60 | + if out.Claims != nil { |
| 61 | + enc := json.NewEncoder(os.Stdout) |
| 62 | + enc.SetIndent("", " ") |
| 63 | + if err := enc.Encode(out.Claims); err != nil { |
| 64 | + fmt.Fprintf(os.Stderr, "failed to encode claims: %s\n", err) |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments