| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- package cmd
- import (
- "encoding/json"
- "fmt"
- "io"
- "strings"
- "text/tabwriter"
- )
- // outputFormat is a rendering mode for command results.
- type outputFormat string
- const (
- formatTable outputFormat = "table"
- formatJSON outputFormat = "json"
- )
- // parseFormat validates a user-supplied format name.
- func parseFormat(s string) (outputFormat, error) {
- switch outputFormat(strings.ToLower(strings.TrimSpace(s))) {
- case formatTable, "":
- return formatTable, nil
- case formatJSON:
- return formatJSON, nil
- default:
- return "", fmt.Errorf("unknown output format %q: use table or json", s)
- }
- }
- // writeOutput renders v according to format. Table rendering uses header and
- // rows so every command lays out the same way.
- func writeOutput(w io.Writer, format outputFormat, header []string, rows [][]string, v any) error {
- if format == formatJSON {
- enc := json.NewEncoder(w)
- enc.SetIndent("", " ")
- return enc.Encode(v)
- }
- if len(header) == 0 && len(rows) == 0 {
- return nil
- }
- tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
- if len(header) > 0 {
- fmt.Fprintln(tw, strings.Join(header, "\t"))
- }
- for _, row := range rows {
- fmt.Fprintln(tw, strings.Join(row, "\t"))
- }
- return tw.Flush()
- }
|