add CSV output support

This commit is contained in:
2026-07-10 15:04:55 +02:00
parent 374ff99916
commit 3486bc0370

View File

@@ -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
}
}