Files
esctl/pkg/printer/table.go

332 lines
7.0 KiB
Go
Raw Normal View History

/*
Copyright © 2026 Thomas von Dein
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package printer
import (
"encoding/json"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"codeberg.org/scip/esctl/pkg/cfg"
"gopkg.in/yaml.v3"
)
type Table struct {
2026-07-10 15:07:57 +02:00
Mode string // tsv, json, yaml
Headers []string
RawHeaders []string
Entries [][]any
2026-07-13 14:33:41 +02:00
rows [][]string // representation used for printing
processed bool
lenHeaders []int
alignInts bool
maxwidth int
debugGoRoutines bool
}
func NewTable(conf *cfg.Config, columns, rows int) *Table {
2026-07-13 14:33:41 +02:00
table := new(Table{
Mode: conf.Output,
maxwidth: cfg.GetTermWidth(),
debugGoRoutines: conf.DebugGoRoutines,
})
table.Headers = make([]string, columns)
2026-07-10 15:07:57 +02:00
table.RawHeaders = make([]string, columns)
2026-07-07 07:29:03 +02:00
table.Entries = make([][]any, rows)
table.lenHeaders = make([]int, columns)
table.alignInts = conf.AlignInts
2026-07-13 14:33:41 +02:00
return table
}
func NewTableEmpty(conf *cfg.Config) *Table {
2026-07-13 14:33:41 +02:00
table := new(Table{
Mode: conf.Output,
maxwidth: cfg.GetTermWidth(),
debugGoRoutines: conf.DebugGoRoutines,
})
table.alignInts = conf.AlignInts
2026-07-07 23:46:43 +02:00
2026-07-13 14:33:41 +02:00
return table
}
func (table *Table) WithHeaders(headers ...string) *Table {
count := len(headers)
2026-07-07 07:29:03 +02:00
table.Entries = [][]any{}
table.lenHeaders = make([]int, count)
table.Headers = make([]string, count)
2026-07-10 15:07:57 +02:00
table.RawHeaders = make([]string, count)
table.Addheaders(headers...)
return table
}
2026-07-07 23:46:43 +02:00
func (table *Table) Print() error {
2026-07-13 14:33:41 +02:00
var err error
2026-07-07 23:46:43 +02:00
switch table.Mode {
case "json":
2026-07-13 14:33:41 +02:00
err = table.PrintJSON()
case "yaml":
2026-07-13 14:33:41 +02:00
err = table.PrintYAML()
2026-07-10 15:07:57 +02:00
case "csv":
2026-07-13 14:33:41 +02:00
err = table.PrintCSV()
default:
2026-07-13 14:33:41 +02:00
err = table.PrintTSV()
}
2026-07-13 14:33:41 +02:00
if table.debugGoRoutines {
printGoRoutineMetrics()
}
return err
}
var (
ansiCtrlSeq = regexp.MustCompile(`\033.[0-9;]+m`)
)
2026-07-07 23:46:43 +02:00
func (table *Table) PrintYAML() error {
raw := table.toMap()
body, err := yaml.Marshal(raw)
if err != nil {
return fmt.Errorf("failed to produce YAML output: %w", err)
}
fmt.Println(string(body))
return nil
}
2026-07-07 23:46:43 +02:00
func (table *Table) PrintJSON() error {
raw := table.toMap()
body, err := json.MarshalIndent(raw, "", " ")
if err != nil {
return fmt.Errorf("failed to produce JSON output: %w", err)
}
fmt.Println(string(body))
return nil
}
2026-07-07 23:46:43 +02:00
func (table *Table) PrintTSV() error {
2026-07-07 07:29:03 +02:00
// length's, convert cell types
2026-07-07 23:46:43 +02:00
table.preprocessRows()
// output headers
2026-07-07 23:46:43 +02:00
for idx, header := range table.Headers {
if idx+1 != len(table.Headers) {
fmt.Print(header, strings.Repeat(" ", table.lenHeaders[idx]-visibleLen(header)))
} else {
// no padding for last header
fmt.Print(header)
}
2026-07-07 23:46:43 +02:00
if idx < len(table.Headers)-1 {
fmt.Print(" ")
}
}
2026-07-07 23:46:43 +02:00
fmt.Println()
2026-07-07 23:46:43 +02:00
for _, entries := range table.rows {
currentWidth := 0
2026-07-17 10:09:05 +02:00
columns := len(entries)
for idx, entry := range entries {
length := visibleLen(entry)
2026-07-17 10:09:05 +02:00
if length+currentWidth > table.maxwidth &&
table.maxwidth-currentWidth > 1 &&
idx == columns-1 {
// text is too wide to be put into one line, and
// it's the last cell, so wrap it
2026-07-17 09:52:55 +02:00
entry = wrap(table.maxwidth-currentWidth, currentWidth+2, entry)
}
2026-07-07 23:46:43 +02:00
currentWidth += table.lenHeaders[idx]
2026-07-07 23:46:43 +02:00
switch {
case isInt(entry) && table.alignInts:
// align right
2026-07-07 23:46:43 +02:00
fmt.Print(strings.Repeat(" ", table.lenHeaders[idx]-length), entry)
case length < table.lenHeaders[idx] && idx+1 != len(entries):
// pad right, if required
2026-07-07 23:46:43 +02:00
fmt.Print(entry, strings.Repeat(" ", table.lenHeaders[idx]-length))
default:
// no padding for last entry
fmt.Print(entry)
}
2026-07-07 23:46:43 +02:00
if idx < len(table.Headers)-1 {
fmt.Print(" ")
}
}
2026-07-07 23:46:43 +02:00
fmt.Println()
}
return nil
}
2026-07-17 09:52:55 +02:00
// Wrap a text into multiple lines, first line is not indented, all
// further lines will be indented. Used within Print() to print large
// cell text.
func wrap(width, indent int, text string) string {
2026-07-17 10:09:05 +02:00
if len(text) <= width {
return text
}
2026-07-17 09:52:55 +02:00
wrapped := ""
line := ""
for word := range strings.FieldsSeq(text) {
if len(line)+len(word)+1 <= width {
// appending word to current line doesn't exceed width
if line != "" {
line += " "
}
2026-07-17 10:13:32 +02:00
2026-07-17 09:52:55 +02:00
line += word
} else {
// it exceeds it, so we need to wrap
if wrapped == "" {
// beginning of output, no indenting here
wrapped = line + "\n"
} else {
// we're in the middle of the text, so add the indent
wrapped += strings.Repeat(" ", indent) + line + "\n"
}
// remember the current word for the next round
line = word
}
}
if line != "" {
// last line, no newline needed here
wrapped += strings.Repeat(" ", indent) + line
}
return wrapped
}
2026-07-10 15:07:57 +02:00
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
}
2026-07-07 23:46:43 +02:00
func (table *Table) Sort() {
// sanity checks
2026-07-07 23:46:43 +02:00
if len(table.Entries) == 0 {
return
}
2026-07-07 23:46:43 +02:00
table.preprocessRows()
2026-07-07 07:29:03 +02:00
2026-07-07 23:46:43 +02:00
sort.Slice(table.rows, func(i, j int) bool {
return table.rows[i][0] < table.rows[j][0]
})
}
2026-07-07 23:46:43 +02:00
func (table *Table) Addheaders(headers ...string) {
for idx, header := range headers {
2026-07-07 23:46:43 +02:00
switch table.Mode {
case "json", "yaml":
2026-07-07 23:46:43 +02:00
table.Headers[idx] = strings.ReplaceAll(strings.ToLower(header), " ", "_")
default:
2026-07-17 10:09:05 +02:00
table.Headers[idx] = Bold(strings.ReplaceAll(strings.ToUpper(header), " ", "-"))
}
2026-07-10 15:07:57 +02:00
table.RawHeaders[idx] = header
}
}
2026-07-07 23:46:43 +02:00
func (table *Table) AddRow(fields ...any) {
table.Entries = append(table.Entries, fields)
}
func (table *Table) AddRowLate(fields ...any) {
table.AddRow(fields)
if !table.processed {
return
}
row := make([]string, len(fields))
for idx, field := range fields {
row[idx] = any2string(field)
}
table.rows = append(table.rows, row)
}
2026-07-07 23:46:43 +02:00
// needed for json and yaml output
func (table *Table) toMap() []map[string]any {
raw := make([]map[string]any, len(table.Entries))
for idx, entries := range table.Entries {
raw[idx] = make(map[string]any, len(table.Headers))
for eidx, entry := range entries {
raw[idx][table.Headers[eidx]] = entry
}
}
return raw
}
// return the length of a string but only visible chars, w/o ansi color escapes
func visibleLen(word string) int {
return len(ansiCtrlSeq.ReplaceAllLiteralString(word, ""))
}
func isInt(num string) bool {
if _, err := strconv.Atoi(num); err == nil {
return true
}
return false
}