// Package render formats command output: aligned tables on a terminal, // tab-separated lines in a pipe, and --json/--jq/--template output. package render import ( "bytes" "encoding/json" "errors" "fmt" "io" "os" "sort" "strings" "text/template" "time" "github.com/itchyny/gojq" "github.com/mattn/go-runewidth" "github.com/spf13/cobra" ) // Printer writes command output. type Printer struct { Out io.Writer IsTTY bool Width int // Color enables ANSI colour (TTY and NO_COLOR unset). Color bool // JSONFields is non-nil when --json was given. JSONFields []string JQ string Template string // Now is used for relative dates; zero means time.Now. Now time.Time } const fieldsAnnotation = "tangled.org/matilde.at/km/json-fields" // AddOutputFlags registers --json, --jq and --template on cmd. fields are // the names --json accepts (the JSON keys of the emitted objects). func AddOutputFlags(cmd *cobra.Command, fields []string) { cmd.Flags().StringSlice("json", nil, "Output JSON with the specified `fields`") cmd.Flags().StringP("jq", "q", "", "Filter JSON output using a jq `expression`") cmd.Flags().StringP("template", "t", "", "Format JSON output using a Go template") if cmd.Annotations == nil { cmd.Annotations = map[string]string{} } sorted := append([]string(nil), fields...) sort.Strings(sorted) cmd.Annotations[fieldsAnnotation] = strings.Join(sorted, ",") prev := cmd.FlagErrorFunc() cmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error { if strings.Contains(err.Error(), "flag needs an argument: --json") { return &FieldsError{Fields: sorted} } return prev(c, err) }) } // FieldsError is returned for a bare --json; it lists the available fields. type FieldsError struct{ Fields []string } func (e *FieldsError) Error() string { return "Specify one or more comma-separated fields for `--json`:\n " + strings.Join(e.Fields, "\n ") } // Fields returns the fields registered by AddOutputFlags. func Fields(cmd *cobra.Command) []string { s := cmd.Annotations[fieldsAnnotation] if s == "" { return nil } return strings.Split(s, ",") } // ConfigureFromFlags fills JSONFields/JQ/Template from cmd's flags and // validates them. func (p *Printer) ConfigureFromFlags(cmd *cobra.Command) error { if cmd.Flags().Lookup("json") == nil { return nil } fields, _ := cmd.Flags().GetStringSlice("json") p.JQ, _ = cmd.Flags().GetString("jq") p.Template, _ = cmd.Flags().GetString("template") if cmd.Flags().Changed("json") { valid := map[string]bool{} for _, f := range Fields(cmd) { valid[f] = true } for _, f := range fields { if !valid[f] { return fmt.Errorf("unknown JSON field %q\n%s", f, (&FieldsError{Fields: Fields(cmd)}).Error()) } } p.JSONFields = fields if p.JSONFields == nil { p.JSONFields = []string{} } } if (p.JQ != "" || p.Template != "") && p.JSONFields == nil { return errors.New("--jq and --template require --json") } if p.JQ != "" && p.Template != "" { return errors.New("--jq and --template cannot be combined") } return nil } // JSONMode reports whether --json was given. func (p *Printer) JSONMode() bool { return p.JSONFields != nil } // Emit writes v as JSON (filtered to JSONFields, then --jq/--template) when // --json was given, else calls human. func (p *Printer) Emit(v any, human func() error) error { if !p.JSONMode() { return human() } data, err := toGeneric(v) if err != nil { return err } data = selectFields(data, p.JSONFields) switch { case p.JQ != "": return p.runJQ(data) case p.Template != "": return p.runTemplate(data) } enc := json.NewEncoder(p.Out) enc.SetEscapeHTML(false) if p.IsTTY { enc.SetIndent("", " ") } return enc.Encode(data) } func toGeneric(v any) (any, error) { b, err := json.Marshal(v) if err != nil { return nil, err } var out any d := json.NewDecoder(bytes.NewReader(b)) d.UseNumber() if err := d.Decode(&out); err != nil { return nil, err } return numbersToNative(out), nil } // numbersToNative converts json.Number into int or float64 so gojq accepts them. func numbersToNative(v any) any { switch x := v.(type) { case json.Number: if i, err := x.Int64(); err == nil { return int(i) } f, _ := x.Float64() return f case map[string]any: for k, e := range x { x[k] = numbersToNative(e) } case []any: for i, e := range x { x[i] = numbersToNative(e) } } return v } func selectFields(v any, fields []string) any { if len(fields) == 0 { return v } switch x := v.(type) { case []any: for i, e := range x { x[i] = selectFields(e, fields) } return x case map[string]any: out := map[string]any{} for _, f := range fields { if val, ok := x[f]; ok { out[f] = val } else { out[f] = nil } } return out } return v } func (p *Printer) runJQ(data any) error { q, err := gojq.Parse(p.JQ) if err != nil { return fmt.Errorf("--jq: %w", err) } iter := q.Run(data) for { v, ok := iter.Next() if !ok { return nil } if err, ok := v.(error); ok { return fmt.Errorf("--jq: %w", err) } if s, ok := v.(string); ok { fmt.Fprintln(p.Out, s) continue } b, err := gojq.Marshal(v) if err != nil { return err } fmt.Fprintln(p.Out, string(b)) } } func (p *Printer) runTemplate(data any) error { t, err := template.New("t").Funcs(template.FuncMap{ "json": func(v any) (string, error) { b, err := json.Marshal(v); return string(b), err }, "join": func(sep string, v []any) string { s := make([]string, len(v)) for i, e := range v { s[i] = fmt.Sprint(e) } return strings.Join(s, sep) }, }).Parse(p.Template) if err != nil { return fmt.Errorf("--template: %w", err) } return t.Execute(p.Out, data) } // Table prints rows. On a TTY: header (bold), aligned columns truncated to // the terminal width. In a pipe: tab-separated, no header, nothing truncated. // Cells may contain ANSI colour codes from the Printer's colour helpers. func (p *Printer) Table(headers []string, rows [][]string) { if !p.IsTTY { for _, r := range rows { fmt.Fprintln(p.Out, strings.Join(r, "\t")) } return } ncol := len(headers) for _, r := range rows { if len(r) > ncol { ncol = len(r) } } widths := make([]int, ncol) measure := func(r []string) { for i, c := range r { if w := VisibleWidth(c); w > widths[i] { widths[i] = w } } } if headers != nil { measure(headers) } for _, r := range rows { measure(r) } fitWidths(widths, p.Width, 2) write := func(r []string, style func(string) string) { var b strings.Builder for i := 0; i < ncol; i++ { c := "" if i < len(r) { c = r[i] } c = Truncate(c, widths[i]) if style != nil { c = style(c) } b.WriteString(c) if i < ncol-1 { b.WriteString(strings.Repeat(" ", widths[i]-VisibleWidth(c)+2)) } } fmt.Fprintln(p.Out, strings.TrimRight(b.String(), " ")) } if headers != nil { write(headers, p.Bold) } for _, r := range rows { write(r, nil) } } // fitWidths shrinks the widest columns until the row fits in total. func fitWidths(widths []int, total, gap int) { if total <= 0 { return } sum := func() int { s := gap * (len(widths) - 1) for _, w := range widths { s += w } return s } for sum() > total { maxI := 0 for i, w := range widths { if w > widths[maxI] { maxI = i } } if widths[maxI] <= 8 { return } widths[maxI]-- } } // VisibleWidth is the display width of s, ignoring ANSI escapes. func VisibleWidth(s string) int { return runewidth.StringWidth(StripANSI(s)) } // StripANSI removes CSI escape sequences. func StripANSI(s string) string { if !strings.Contains(s, "\x1b") { return s } var b strings.Builder for i := 0; i < len(s); i++ { if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '[' { j := i + 2 for j < len(s) && (s[j] < 0x40 || s[j] > 0x7e) { j++ } i = j continue } b.WriteByte(s[i]) } return b.String() } // Truncate cuts s to width display columns, ending with "…". ANSI codes are // dropped from truncated strings. func Truncate(s string, width int) string { if VisibleWidth(s) <= width { return s } return runewidth.Truncate(StripANSI(s), width, "…") } func (p *Printer) sgr(code, s string) string { if !p.Color || s == "" { return s } return "\x1b[" + code + "m" + s + "\x1b[0m" } func (p *Printer) Bold(s string) string { return p.sgr("1", s) } func (p *Printer) Dim(s string) string { return p.sgr("2", s) } func (p *Printer) Red(s string) string { return p.sgr("31", s) } func (p *Printer) Green(s string) string { return p.sgr("32", s) } func (p *Printer) Yellow(s string) string { return p.sgr("33", s) } func (p *Printer) Cyan(s string) string { return p.sgr("36", s) } func (p *Printer) now() time.Time { if !p.Now.IsZero() { return p.Now } return time.Now() } // Date formats t: relative on a TTY, RFC 3339 UTC in a pipe. func (p *Printer) Date(t time.Time) string { if !p.IsTTY { return t.UTC().Format(time.RFC3339) } return RelTime(t, p.now()) } // RelTime gives a compact relative time: "now", "5m", "3h", "Tue", "Nov 2", "2024-03-01". func RelTime(t, now time.Time) string { d := now.Sub(t) switch { case d < time.Minute && d > -time.Minute: return "now" case d < 0: return t.Local().Format("2006-01-02") case d < time.Hour: return fmt.Sprintf("%dm", int(d.Minutes())) case d < 24*time.Hour: return fmt.Sprintf("%dh", int(d.Hours())) case d < 6*24*time.Hour: return t.Local().Format("Mon") case t.Year() == now.Year(): return t.Local().Format("Jan 2") } return t.Local().Format("2006-01-02") } // Size formats a byte count: 512B, 12K, 3.4M. func Size(n int64) string { switch { case n < 1024: return fmt.Sprintf("%dB", n) case n < 1024*1024: return fmt.Sprintf("%dK", (n+512)/1024) case n < 10*1024*1024: return fmt.Sprintf("%.1fM", float64(n)/(1024*1024)) } return fmt.Sprintf("%dM", (n+512*1024)/(1024*1024)) } // ColorEnabled is the default colour decision for a TTY. func ColorEnabled(isTTY bool) bool { return isTTY && os.Getenv("NO_COLOR") == "" && os.Getenv("TERM") != "dumb" }