bouncer/internal/format/table/writer.go

76 lines
1.3 KiB
Go
Raw Normal View History

2023-04-24 20:52:12 +02:00
package table
import (
"io"
"forge.cadoles.com/cadoles/bouncer/internal/format"
"github.com/jedib0t/go-pretty/v6/table"
)
const Format format.Format = "table"
const DefaultCompactModeMaxColumnWidth = 30
func init() {
format.Register(Format, NewWriter(DefaultCompactModeMaxColumnWidth))
}
type Writer struct {
compactModeMaxColumnWidth int
}
// Write implements format.Writer.
func (w *Writer) Write(writer io.Writer, hints format.Hints, data ...any) error {
t := table.NewWriter()
t.SetOutputMirror(writer)
var props []format.Prop
if hints.Props != nil {
props = hints.Props
} else {
if len(data) > 0 {
props = getProps(data[0])
} else {
props = make([]format.Prop, 0)
}
}
labels := table.Row{}
for _, p := range props {
labels = append(labels, p.Label())
}
t.AppendHeader(labels)
isCompactMode := hints.OutputMode == format.OutputModeCompact
for _, d := range data {
row := table.Row{}
for _, p := range props {
value := getFieldValue(d, p.Name())
if isCompactMode && len(value) > w.compactModeMaxColumnWidth {
value = value[:w.compactModeMaxColumnWidth] + "..."
}
row = append(row, value)
}
t.AppendRow(row)
}
t.Render()
return nil
}
func NewWriter(compactModeMaxColumnWidth int) *Writer {
return &Writer{compactModeMaxColumnWidth}
}
var _ format.Writer = &Writer{}