2017-07-31 18:02:57 +00:00
|
|
|
package formats
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2017-08-15 20:53:17 +00:00
|
|
|
"strings"
|
2017-07-31 18:02:57 +00:00
|
|
|
"text/template"
|
2017-08-15 20:53:17 +00:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2017-07-31 18:02:57 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Writer interface for outputs
|
|
|
|
type Writer interface {
|
|
|
|
Out() error
|
|
|
|
}
|
|
|
|
|
|
|
|
// JSONstruct for JSON output
|
|
|
|
type JSONstruct struct {
|
|
|
|
Output []interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// StdoutTemplate for Go template output
|
|
|
|
type StdoutTemplate struct {
|
|
|
|
Output []interface{}
|
|
|
|
Template string
|
2017-08-15 20:53:17 +00:00
|
|
|
Fields map[string]string
|
2017-07-31 18:02:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Out method for JSON
|
|
|
|
func (j JSONstruct) Out() error {
|
|
|
|
data, err := json.MarshalIndent(j.Output, "", " ")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
fmt.Printf("%s\n", data)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Out method for Go templates
|
|
|
|
func (t StdoutTemplate) Out() error {
|
2017-08-15 20:53:17 +00:00
|
|
|
if strings.HasPrefix(t.Template, "table") {
|
|
|
|
t.Template = strings.TrimSpace(t.Template[5:])
|
|
|
|
headerTmpl, err := template.New("header").Funcs(headerFunctions).Parse(t.Template)
|
|
|
|
if err != nil {
|
|
|
|
errors.Wrapf(err, "Template parsing error")
|
|
|
|
}
|
|
|
|
err = headerTmpl.Execute(os.Stdout, t.Fields)
|
|
|
|
fmt.Println()
|
|
|
|
}
|
|
|
|
tmpl, err := template.New("image").Funcs(basicFunctions).Parse(t.Template)
|
2017-07-31 18:02:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "Template parsing error")
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, img := range t.Output {
|
2017-08-15 20:53:17 +00:00
|
|
|
basicTmpl := tmpl.Funcs(basicFunctions)
|
|
|
|
err = basicTmpl.Execute(os.Stdout, img)
|
2017-07-31 18:02:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
fmt.Println()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
|
|
|
|
}
|