Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/dev/gpctl/pkg/prettyprint/prettyprint.go
2500 views
1
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package prettyprint
6
7
import (
8
"encoding/json"
9
"fmt"
10
"html/template"
11
"io"
12
"text/tabwriter"
13
14
"github.com/Masterminds/sprig"
15
"golang.org/x/xerrors"
16
"k8s.io/client-go/util/jsonpath"
17
)
18
19
// Format defines how to print an object
20
type Format string
21
22
const (
23
// StringFormat prints an object as repr string
24
StringFormat Format = "string"
25
26
// JSONPathFormat extracts info using jsonpath
27
JSONPathFormat Format = "jsonpath"
28
29
// TemplateFormat prints info using a Go template
30
TemplateFormat Format = "tpl"
31
32
// JSONFormat prints an object as JSON
33
JSONFormat Format = "json"
34
)
35
36
type formatterFunc func(*Printer, interface{}) error
37
38
var formatter = map[Format]formatterFunc{
39
StringFormat: formatString,
40
TemplateFormat: formatTemplate,
41
JSONFormat: formatJSON,
42
JSONPathFormat: formatJSONPath,
43
}
44
45
func formatString(pp *Printer, obj interface{}) error {
46
_, err := fmt.Fprintf(pp.Writer, "%s", obj)
47
return err
48
}
49
50
func formatJSONPath(pp *Printer, obj interface{}) error {
51
p := jsonpath.New("expr")
52
if err := p.Parse(pp.Template); err != nil {
53
return err
54
}
55
return p.Execute(pp.Writer, obj)
56
}
57
58
func formatTemplate(pp *Printer, obj interface{}) error {
59
tmpl, err := template.New("prettyprint").Funcs(sprig.FuncMap()).Parse(pp.Template)
60
if err != nil {
61
return err
62
}
63
64
w := tabwriter.NewWriter(pp.Writer, 8, 8, 8, ' ', 0)
65
if err := tmpl.Execute(w, obj); err != nil {
66
return err
67
}
68
if err := w.Flush(); err != nil {
69
return err
70
}
71
return nil
72
}
73
74
func formatJSON(pp *Printer, obj interface{}) error {
75
enc := json.NewEncoder(pp.Writer)
76
enc.SetIndent("", " ")
77
return enc.Encode(obj)
78
}
79
80
// Printer is pretty-printer
81
type Printer struct {
82
Format Format
83
Writer io.Writer
84
Template string
85
}
86
87
// Print pretty-prints the content
88
func (pp *Printer) Print(obj interface{}) error {
89
formatter, ok := formatter[pp.Format]
90
if !ok {
91
return xerrors.Errorf("Unknown format: %s", pp.Format)
92
}
93
94
return formatter(pp, obj)
95
}
96
97