64 lines
1013 B
Go
64 lines
1013 B
Go
package output
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"text/tabwriter"
|
|
)
|
|
|
|
type Format string
|
|
|
|
const (
|
|
FormatTable Format = "table"
|
|
FormatJSON Format = "json"
|
|
FormatYAML Format = "yaml"
|
|
)
|
|
|
|
type Printer struct {
|
|
format Format
|
|
out io.Writer
|
|
}
|
|
|
|
func NewPrinter(format Format) *Printer {
|
|
return &Printer{format: format, out: os.Stdout}
|
|
}
|
|
|
|
func (p *Printer) PrintJSON(v any) error {
|
|
enc := json.NewEncoder(p.out)
|
|
enc.SetIndent("", " ")
|
|
return enc.Encode(v)
|
|
}
|
|
|
|
func (p *Printer) PrintTable(headers []string, rows [][]string) {
|
|
w := tabwriter.NewWriter(p.out, 0, 0, 2, ' ', 0)
|
|
defer w.Flush()
|
|
|
|
for i, h := range headers {
|
|
if i > 0 {
|
|
fmt.Fprint(w, "\t")
|
|
}
|
|
fmt.Fprint(w, h)
|
|
}
|
|
fmt.Fprintln(w)
|
|
|
|
for _, row := range rows {
|
|
for i, cell := range row {
|
|
if i > 0 {
|
|
fmt.Fprint(w, "\t")
|
|
}
|
|
fmt.Fprint(w, cell)
|
|
}
|
|
fmt.Fprintln(w)
|
|
}
|
|
}
|
|
|
|
func (p *Printer) PrintLine(s string) {
|
|
fmt.Fprintln(p.out, s)
|
|
}
|
|
|
|
func PrintError(err error) {
|
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
}
|