-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonoctl.go
More file actions
177 lines (137 loc) · 3.87 KB
/
monoctl.go
File metadata and controls
177 lines (137 loc) · 3.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package monoctl
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/spf13/cobra"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.yaml.in/yaml/v4"
)
type Runner interface {
GetRows() ([][]any, error)
}
func CheckErr(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
func configDir(paths ...string) (string, error) {
dir, err := os.UserConfigDir()
if err != nil {
return "", fmt.Errorf("unable to find config directory: %w", err)
}
paths = append([]string{dir, "monoctl"}, paths...)
path := filepath.Join(paths...)
if err := os.MkdirAll(path, 0700); err != nil {
return "", fmt.Errorf("cannot create config directory '%s': %w", path, err)
}
return path, nil
}
func formatValue(v any) any {
switch t := v.(type) {
case nil:
return ""
case primitive.DateTime:
return t.Time().Format("2006-01-02 15:04:05")
case time.Time:
return t.Format("2006-01-02 15:04:05")
default:
return v
}
}
func mapToRows(fields []string, rawData []map[string]any) [][]any {
var rows [][]any
for _, rd := range rawData {
row := make([]any, len(fields))
for i, f := range fields {
row[i] = formatValue(rd[f])
}
rows = append(rows, row)
}
return rows
}
// convert value to JSON string
func toJson(v any) (string, error) {
b, err := json.Marshal(v)
if err != nil {
return "", fmt.Errorf("json encode error: %w", err)
}
return string(b), nil
}
// convert value to YAML string
func toYaml(v any) (string, error) {
b, err := yaml.Marshal(v)
if err != nil {
return "", fmt.Errorf("yaml encode error: %w", err)
}
return string(b), nil
}
// bind functions to Go template
var funcMap = template.FuncMap{
"json": toJson,
"yaml": toYaml,
}
// render Go template with helpers
func tmpl(name string, text string, data any) error {
t, err := template.New(name).Funcs(funcMap).Parse(text)
if err != nil {
return fmt.Errorf("template parse error: %w", err)
}
if err := t.Execute(os.Stdout, data); err != nil {
return fmt.Errorf("template execution error: %w", err)
}
if !strings.Contains(text, "yaml") {
if _, err := os.Stdout.Write([]byte("\n")); err != nil {
return fmt.Errorf("unable to write newline: %w", err)
}
}
return nil
}
var valFormatFlag string
// bind flag like: monoctl <command> --format
func BindFormatFlag(cmd *cobra.Command) {
usage := `Format output using a custom template:
'json': Print in JSON format
'yaml': Print in YAML format
'TEMPLATE': Print output using the given Go template.`
cmd.Flags().StringVar(&valFormatFlag, "format", "", usage)
}
// output as json, yaml, or template
func executeFormatFlag(cmd *cobra.Command, data any) error {
value := strings.TrimSpace(valFormatFlag)
switch {
case value == "{{.}}" || !cmd.Flags().Changed("format"):
if _, err := fmt.Fprintf(os.Stdout, "%+v\n", data); err != nil {
return fmt.Errorf("printing default output failed: %w", err)
}
case strings.HasPrefix(value, "{{") && strings.HasSuffix(value, "}}"):
return tmpl("formatterTemplate", valFormatFlag, data)
case strings.EqualFold(value, "json"):
return printFn(data, toJson, &PrintOptions{NewLine: true})
case strings.EqualFold(value, "yaml"):
return printFn(data, toYaml)
default:
return fmt.Errorf("invalid format value: '%s'", value)
}
return nil
}
type PrintOptions struct { NewLine bool }
func printFn(v any, fn func(any) (string, error), opts ...*PrintOptions) error {
out, err := fn(v)
if err != nil { return err }
newline := false
if opts != nil {
newline = opts[0].NewLine
}
suffix := ""
if newline { suffix = "\n" }
if _, err := fmt.Printf("%v%s", out, suffix); err != nil {
return fmt.Errorf("printing output failed: %w", err)
}
return nil
}