From 3486bc03705dbce8dd4147aa57104df9b5443748 Mon Sep 17 00:00:00 2001 From: Thomas von Dein Date: Fri, 10 Jul 2026 15:04:55 +0200 Subject: [PATCH] add CSV output support --- pkg/printer/table.go | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/pkg/printer/table.go b/pkg/printer/table.go index cf412d4..55b62d0 100644 --- a/pkg/printer/table.go +++ b/pkg/printer/table.go @@ -30,9 +30,10 @@ import ( ) type Table struct { - Mode string // tsv, json, yaml - Headers []string - Entries [][]any + Mode string // tsv, json, yaml + Headers []string + RawHeaders []string + Entries [][]any rows [][]string // representation used for printing processed bool @@ -45,6 +46,7 @@ func NewTable(conf *cfg.Config, columns, rows int) *Table { table := Table{Mode: conf.Output, maxwidth: cfg.GetTermWidth()} table.Headers = make([]string, columns) + table.RawHeaders = make([]string, columns) table.Entries = make([][]any, rows) table.lenHeaders = make([]int, columns) table.alignInts = conf.AlignInts @@ -65,6 +67,7 @@ func (table *Table) WithHeaders(headers ...string) *Table { table.Entries = [][]any{} table.lenHeaders = make([]int, count) table.Headers = make([]string, count) + table.RawHeaders = make([]string, count) table.Addheaders(headers...) @@ -77,6 +80,8 @@ func (table *Table) Print() error { return table.PrintJSON() case "yaml": return table.PrintYAML() + case "csv": + return table.PrintCSV() default: return table.PrintTSV() } @@ -178,6 +183,28 @@ func (table *Table) PrintTSV() error { return nil } +func (table *Table) PrintCSV() error { + table.preprocessRows() + + fmt.Println(strings.Join(table.RawHeaders, ",")) + + for _, entries := range table.rows { + row := make([]string, len(entries)) + + for idx, entry := range entries { + if strings.Contains(entry, " ") || strings.Contains(entry, ",") { + row[idx] = `"` + entry + `"` + } else { + row[idx] = entry + } + } + + fmt.Println(strings.Join(row, ",")) + } + + return nil +} + func (table *Table) Sort() { // sanity checks if len(table.Entries) == 0 { @@ -199,6 +226,8 @@ func (table *Table) Addheaders(headers ...string) { default: table.Headers[idx] = bold(strings.ReplaceAll(strings.ToUpper(header), " ", "-")) } + + table.RawHeaders[idx] = header } }