output.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package cmd
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "text/tabwriter"
  8. )
  9. // outputFormat is a rendering mode for command results.
  10. type outputFormat string
  11. const (
  12. formatTable outputFormat = "table"
  13. formatJSON outputFormat = "json"
  14. )
  15. // parseFormat validates a user-supplied format name.
  16. func parseFormat(s string) (outputFormat, error) {
  17. switch outputFormat(strings.ToLower(strings.TrimSpace(s))) {
  18. case formatTable, "":
  19. return formatTable, nil
  20. case formatJSON:
  21. return formatJSON, nil
  22. default:
  23. return "", fmt.Errorf("unknown output format %q: use table or json", s)
  24. }
  25. }
  26. // writeOutput renders v according to format. Table rendering uses header and
  27. // rows so every command lays out the same way.
  28. func writeOutput(w io.Writer, format outputFormat, header []string, rows [][]string, v any) error {
  29. if format == formatJSON {
  30. enc := json.NewEncoder(w)
  31. enc.SetIndent("", " ")
  32. return enc.Encode(v)
  33. }
  34. if len(header) == 0 && len(rows) == 0 {
  35. return nil
  36. }
  37. tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
  38. if len(header) > 0 {
  39. fmt.Fprintln(tw, strings.Join(header, "\t"))
  40. }
  41. for _, row := range rows {
  42. fmt.Fprintln(tw, strings.Join(row, "\t"))
  43. }
  44. return tw.Flush()
  45. }