Files
esctl/pkg/printer/table.go

231 lines
5.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"
"github.com/seeruk/go-wordwrap"
"gopkg.in/yaml.v3"
)
type Table struct {
2026-07-07 07:29:03 +02:00
Mode string // tsv, json, yaml
Headers []string
2026-07-07 07:29:03 +02:00
Entries [][]any
2026-07-07 07:29:03 +02:00
rows [][]string // representation used for printing
processed bool
lenHeaders []int
alignInts bool
maxwidth int
}
func NewTable(conf *cfg.Config, columns, rows int) *Table {
table := Table{Mode: conf.Output, maxwidth: cfg.GetTermWidth()}
table.Headers = 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
return &table
}
func NewTableEmpty(conf *cfg.Config) *Table {
table := Table{Mode: conf.Output, maxwidth: cfg.GetTermWidth()}
table.alignInts = conf.AlignInts
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)
table.Addheaders(headers...)
return table
}
func (data *Table) Print() error {
switch data.Mode {
case "json":
return data.PrintJSON()
case "yaml":
return data.PrintYAML()
default:
return data.PrintTSV()
}
}
var (
ansiCtrlSeq = regexp.MustCompile(`\033.[0-9;]+m`)
)
// needed for json and yaml output
2026-07-07 07:29:03 +02:00
func (data *Table) toMap() []map[string]any {
raw := make([]map[string]any, len(data.Entries))
for idx, entries := range data.Entries {
2026-07-07 07:29:03 +02:00
raw[idx] = make(map[string]any, len(data.Headers))
for eidx, entry := range entries {
raw[idx][data.Headers[eidx]] = entry
}
}
return raw
}
func (data *Table) PrintYAML() error {
raw := data.toMap()
body, err := yaml.Marshal(raw)
if err != nil {
2026-07-07 09:34:36 +02:00
return fmt.Errorf("failed to produce YAML output: %w", err)
}
fmt.Println(string(body))
return nil
}
func (data *Table) PrintJSON() error {
raw := data.toMap()
body, err := json.MarshalIndent(raw, "", " ")
if err != nil {
2026-07-07 09:34:36 +02:00
return fmt.Errorf("failed to produce JSON output: %w", err)
}
fmt.Println(string(body))
return nil
}
func (data *Table) PrintTSV() error {
2026-07-07 07:29:03 +02:00
// length's, convert cell types
data.preprocessRows()
// output headers
for idx, header := range data.Headers {
if idx+1 != len(data.Headers) {
fmt.Print(header, strings.Repeat(" ", data.lenHeaders[idx]-visibleLen(header)))
} else {
// no padding for last header
fmt.Print(header)
}
if idx < len(data.Headers)-1 {
fmt.Print(" ")
}
}
fmt.Println()
2026-07-07 07:29:03 +02:00
for _, entries := range data.rows {
currentWidth := 0
for idx, entry := range entries {
length := visibleLen(entry)
if length+currentWidth > data.maxwidth && data.maxwidth-currentWidth > 1 {
// text is too wide to be put into one line, wrap it
wrapper := wordwrap.Wrapper(data.maxwidth-currentWidth, false)
wrapped := wrapper(entry)
// and indent it
for idx, line := range strings.Split(wrapped, "\n") {
if idx == 0 {
entry = line
} else {
entry += "\n " + strings.Repeat(" ", currentWidth) + line
}
}
}
currentWidth += data.lenHeaders[idx]
if isInt(entry) && data.alignInts {
// align right
fmt.Print(strings.Repeat(" ", data.lenHeaders[idx]-length), entry)
} else if length < data.lenHeaders[idx] && idx+1 != len(entries) {
// pad right, if required
fmt.Print(entry, strings.Repeat(" ", data.lenHeaders[idx]-length))
} else {
// no padding for last entry
fmt.Print(entry)
}
if idx < len(data.Headers)-1 {
fmt.Print(" ")
}
}
fmt.Println()
}
return nil
}
func (data *Table) Sort() {
// sanity checks
if len(data.Entries) == 0 {
return
}
2026-07-07 07:29:03 +02:00
data.preprocessRows()
sort.Slice(data.rows, func(i, j int) bool {
return data.rows[i][0] < data.rows[j][0]
})
}
func (data *Table) Addheaders(headers ...string) {
for idx, header := range headers {
switch data.Mode {
case "json", "yaml":
data.Headers[idx] = strings.ReplaceAll(strings.ToLower(header), " ", "_")
default:
data.Headers[idx] = bold(strings.ReplaceAll(strings.ToUpper(header), " ", "-"))
}
}
}
2026-07-07 07:29:03 +02:00
func (data *Table) AddRow(fields ...any) {
data.Entries = append(data.Entries, fields)
}
// 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
}