forked from anchore/fangs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsummarize.go
328 lines (284 loc) · 6.87 KB
/
summarize.go
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package fangs
import (
"bytes"
"fmt"
"reflect"
"strings"
"github.com/spf13/cobra"
"github.com/anchore/go-logger"
)
func Summarize(cfg Config, descriptions DescriptionProvider, filter ValueFilterFunc, values ...any) string {
root := §ion{}
for _, value := range values {
v := reflect.ValueOf(value)
summarize(cfg, descriptions, root, v, nil)
}
if filter == nil {
filter = func(s string) string {
return s
}
}
return root.stringify(cfg, filter)
}
func SummarizeCommand(cfg Config, cmd *cobra.Command, filter ValueFilterFunc, values ...any) string {
root := cmd
for root.Parent() != nil {
root = root.Parent()
}
descriptions := DescriptionProviders(
NewFieldDescriber(values...),
NewStructDescriptionTagProvider(),
NewCommandFlagDescriptionProvider(cfg.TagName, root),
)
return Summarize(cfg, descriptions, filter, values...)
}
func SummarizeLocations(cfg Config) (out []string) {
for _, f := range cfg.Finders {
out = append(out, f(cfg)...)
}
return
}
type ValueFilterFunc func(string) string
//nolint:gocognit
func summarize(cfg Config, descriptions DescriptionProvider, s *section, value reflect.Value, path []string) {
v, t := base(value)
if !isStruct(t) {
panic(fmt.Sprintf("Summarize requires struct types, got: %#v", value.Interface()))
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !includeField(f) {
continue
}
path := path
name := f.Name
if tag, ok := f.Tag.Lookup(cfg.TagName); ok {
parts := strings.Split(tag, ",")
tag = parts[0]
if tag == "-" {
continue
}
switch {
case contains(parts, "squash"):
name = ""
case tag == "":
path = append(path, name)
default:
name = tag
path = append(path, tag)
}
} else {
path = append(path, name)
}
v := v.Field(i)
_, t := base(v)
if isStruct(t) {
sub := s
if name != "" {
sub = s.sub(name)
}
if isPtr(v.Type()) && v.IsNil() {
v = reflect.New(t)
}
summarize(cfg, descriptions, sub, v, path)
} else {
env := envVar(cfg.AppName, path...)
// for slices of structs, do not output an env var
if t.Kind() == reflect.Slice && baseType(t.Elem()).Kind() == reflect.Struct {
env = ""
}
s.add(cfg.Logger,
name,
v,
descriptions.GetDescription(v, f),
env)
}
}
}
// printVal prints a value in YAML format
// nolint:gocognit
func printVal(cfg Config, filter ValueFilterFunc, value reflect.Value, indent string) string {
buf := bytes.Buffer{}
v, t := base(value)
switch {
case isSlice(t):
if v.Len() == 0 {
return "[]"
}
for i := 0; i < v.Len(); i++ {
v := v.Index(i)
buf.WriteString("\n")
buf.WriteString(indent)
buf.WriteString("- ")
val := printVal(cfg, filter, v, indent+" ")
val = strings.TrimSpace(val)
buf.WriteString(val)
// separate struct entries by an empty line
_, t := base(v)
if isStruct(t) {
buf.WriteString("\n")
}
}
case isStruct(t):
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !includeField(f) {
continue
}
name := f.Name
if tag, ok := f.Tag.Lookup(cfg.TagName); ok {
parts := strings.Split(tag, ",")
tag = parts[0]
if tag == "-" {
continue
}
switch {
case contains(parts, "squash"):
name = ""
case tag == "":
default:
name = tag
}
}
v := v.Field(i)
buf.WriteString("\n")
buf.WriteString(indent)
val := printVal(cfg, filter, v, indent+" ")
val = fmt.Sprintf("%s: %s", name, val)
buf.WriteString(val)
}
case v.CanInterface():
if v.Kind() == reflect.Pointer && v.IsNil() {
return ""
}
if v.Kind() == reflect.String {
return fmt.Sprintf("'%s'", filter(v.String()))
}
return filter(fmt.Sprintf("%v", v.Interface()))
}
val := buf.String()
// for slices, there will be an extra newline, which we want to remove
val = strings.TrimSuffix(val, "\n")
return val
}
func base(v reflect.Value) (reflect.Value, reflect.Type) {
t := v.Type()
for isPtr(t) {
t = t.Elem()
if v.IsNil() {
newV := reflect.New(t)
// If the field we're looking at is nil, and is a pointer to a struct,
// change it to point to an empty instance of the struct, so that we can
// continue recursing on the config structure. However, if it's a nil pointer
// to a primitive type, leave it as nil so that we can tell later in the summary
// that it wasn't set.
if newV.Kind() == reflect.Struct {
v = newV
}
} else {
v = v.Elem()
}
}
return v, t
}
func baseType(t reflect.Type) reflect.Type {
for isPtr(t) {
t = t.Elem()
}
return t
}
type section struct {
name string
value reflect.Value
description string
env string
subsections []*section
}
func (s *section) get(name string) *section {
for _, s := range s.subsections {
if s.name == name {
return s
}
}
return nil
}
func (s *section) sub(name string) *section {
sub := s.get(name)
if sub == nil {
sub = §ion{
name: name,
}
s.subsections = append(s.subsections, sub)
}
return sub
}
func (s *section) add(log logger.Logger, name string, value reflect.Value, description string, env string) *section {
add := §ion{
name: name,
value: value,
description: description,
env: env,
}
sub := s.get(name)
if sub != nil {
if sub.name != name || !sub.value.CanConvert(value.Type()) || sub.description != description || sub.env != env {
log.Warnf("multiple entries with different values: %#v != %#v", sub, add)
}
return sub
}
s.subsections = append(s.subsections, add)
return add
}
func (s *section) stringify(cfg Config, filter ValueFilterFunc) string {
out := &bytes.Buffer{}
stringifySection(cfg, filter, out, s, "")
return out.String()
}
func stringifySection(cfg Config, filter ValueFilterFunc, out *bytes.Buffer, s *section, indent string) {
nextIndent := indent
if s.name != "" {
nextIndent += " "
if s.description != "" {
// support multi-line descriptions
lines := strings.Split(strings.TrimSpace(s.description), "\n")
for idx, line := range lines {
out.WriteString(indent + "# " + line)
if idx < len(lines)-1 {
out.WriteString("\n")
}
}
}
if s.env != "" {
value := fmt.Sprintf("(env: %s)", s.env)
if s.description == "" {
// since there is no description, we need to start the comment
out.WriteString(indent + "# ")
} else {
// buffer between description and env hint
out.WriteString(" ")
}
out.WriteString(value)
}
if s.description != "" || s.env != "" {
out.WriteString("\n")
}
out.WriteString(indent)
out.WriteString(s.name)
out.WriteString(":")
if s.value.IsValid() {
val := printVal(cfg, filter, s.value, indent+" ")
if val != "" {
out.WriteString(" ")
}
out.WriteString(val)
}
out.WriteString("\n")
}
for _, s := range s.subsections {
stringifySection(cfg, filter, out, s, nextIndent)
if len(s.subsections) == 0 {
out.WriteString(nextIndent)
out.WriteString("\n")
}
}
}