51 lines
973 B
Go
51 lines
973 B
Go
|
package table
|
||
|
|
||
|
import (
|
||
|
"io"
|
||
|
"os"
|
||
|
"text/tabwriter"
|
||
|
)
|
||
|
|
||
|
// TabulatedPrinter defines an interface we can use for a common way to print tabulated data
|
||
|
//
|
||
|
// ie we canb use the same interface to display results as table, csv, json, etc
|
||
|
type TabulatedPrinter interface {
|
||
|
// Headers defines the headers for the values
|
||
|
Headers(...string) error
|
||
|
|
||
|
//Fields appends fields to the printer
|
||
|
Fields(...interface{}) error
|
||
|
StringFields(...string) error
|
||
|
|
||
|
// Flush outputs the tabulated data
|
||
|
Flush() error
|
||
|
}
|
||
|
|
||
|
// NewPrinter returns a new tabulated printer type based on the format specified
|
||
|
// format: can be human, csv
|
||
|
func NewPrinter(format string, w io.Writer) TabulatedPrinter {
|
||
|
if w == nil {
|
||
|
w = os.Stdout
|
||
|
}
|
||
|
|
||
|
switch format {
|
||
|
case "csv":
|
||
|
return &CSVPrinter{
|
||
|
writer: w,
|
||
|
}
|
||
|
|
||
|
case "json":
|
||
|
return &JSONPrinter{
|
||
|
writer: w,
|
||
|
}
|
||
|
|
||
|
case "human":
|
||
|
p := &HumanPrinter{
|
||
|
writer: new(tabwriter.Writer),
|
||
|
}
|
||
|
p.writer.Init(w, 0, 8, 2, ' ', 0)
|
||
|
return p
|
||
|
}
|
||
|
return nil
|
||
|
}
|