| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- // Package output renders command results as a table or as JSON.
- package output
- import (
- "encoding/json"
- "fmt"
- "io"
- "strings"
- "text/tabwriter"
- )
- // Format is a rendering mode for command output.
- type Format string
- // Supported formats.
- const (
- Table Format = "table"
- JSON Format = "json"
- )
- // Parse validates a user-supplied format name.
- func Parse(s string) (Format, error) {
- switch Format(strings.ToLower(strings.TrimSpace(s))) {
- case Table, "":
- return Table, nil
- case JSON:
- return JSON, nil
- default:
- return "", fmt.Errorf("unknown output format %q: use table or json", s)
- }
- }
- // Write renders v according to format. Table rendering uses header and rows so
- // every command lays out the same way.
- func Write(w io.Writer, format Format, header []string, rows [][]string, v any) error {
- if format == JSON {
- 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()
- }
|