-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoutput_yaml.go
387 lines (318 loc) · 10.5 KB
/
output_yaml.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Copyright © 2019 The Homeport Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package neat
import (
"fmt"
"reflect"
"strings"
"time"
yamlv2 "gopkg.in/yaml.v2"
yamlv3 "gopkg.in/yaml.v3"
"github.com/gonvenience/bunt"
)
var (
yamlReservedKeywords = []string{"true", "false", "null"}
// YAML Spec regarding timestamp: https://yaml.org/type/timestamp.html
yamlTimeLayouts = [...]string{
time.RFC3339,
"2006-01-02T15:04:05.999999999Z",
"2006-01-02t15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999 07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02",
}
)
// ToYAMLString marshals the provided object into YAML with text decorations
// and is basically just a convenience function to create the output processor
// and call its `ToYAML` function.
func ToYAMLString(obj interface{}) (string, error) {
return NewOutputProcessor(true, true, &DefaultColorSchema).ToYAML(obj)
}
// ToYAML processes the provided input object and tries to neatly output it as
// human-readable YAML honoring the preferences provided to the output processor
func (p *OutputProcessor) ToYAML(obj interface{}) (string, error) {
if err := p.neatYAML("", false, obj); err != nil {
return "", err
}
p.out.Flush()
return p.data.String(), nil
}
func (p *OutputProcessor) neatYAML(prefix string, skipIndentOnFirstLine bool, obj interface{}) error {
switch t := obj.(type) {
case yamlv2.MapSlice:
return p.neatYAMLofMapSlice(prefix, skipIndentOnFirstLine, t)
case []interface{}:
return p.neatYAMLofSlice(prefix, skipIndentOnFirstLine, t)
case []yamlv2.MapSlice:
return p.neatYAMLofSlice(prefix, skipIndentOnFirstLine, p.simplify(t))
case yamlv3.Node:
return p.neatYAMLofNode(prefix, skipIndentOnFirstLine, &t)
default:
switch reflect.TypeOf(obj).Kind() {
case reflect.Ptr:
return p.neatYAML(prefix, skipIndentOnFirstLine, reflect.ValueOf(obj).Elem().Interface())
case reflect.Struct:
return p.neatYAMLOfStruct(prefix, skipIndentOnFirstLine, t)
default:
return p.neatYAMLofScalar(prefix, skipIndentOnFirstLine, t)
}
}
}
func (p *OutputProcessor) neatYAMLofMapSlice(prefix string, skipIndentOnFirstLine bool, mapslice yamlv2.MapSlice) error {
for i, mapitem := range mapslice {
if !skipIndentOnFirstLine || i > 0 {
_, _ = p.out.WriteString(prefix)
}
keyString := fmt.Sprintf("%v:", mapitem.Key)
if p.boldKeys {
keyString = bunt.Style(keyString, bunt.Bold())
}
_, _ = p.out.WriteString(p.colorize(colorKey, keyString))
switch mapitem.Value.(type) {
case yamlv2.MapSlice:
if len(mapitem.Value.(yamlv2.MapSlice)) == 0 {
_, _ = p.out.WriteString(" ")
_, _ = p.out.WriteString(p.colorize(emptyStructures, emptyObject))
_, _ = p.out.WriteString("\n")
} else {
_, _ = p.out.WriteString("\n")
if err := p.neatYAMLofMapSlice(prefix+p.prefixAdd(), false, mapitem.Value.(yamlv2.MapSlice)); err != nil {
return err
}
}
case []interface{}:
if len(mapitem.Value.([]interface{})) == 0 {
_, _ = p.out.WriteString(" ")
_, _ = p.out.WriteString(p.colorize(emptyStructures, emptyList))
_, _ = p.out.WriteString("\n")
} else {
_, _ = p.out.WriteString("\n")
if err := p.neatYAMLofSlice(prefix, false, mapitem.Value.([]interface{})); err != nil {
return err
}
}
default:
_, _ = p.out.WriteString(" ")
if err := p.neatYAMLofScalar(prefix, false, mapitem.Value); err != nil {
return err
}
}
}
return nil
}
func (p *OutputProcessor) neatYAMLofSlice(prefix string, skipIndentOnFirstLine bool, list []interface{}) error {
for _, entry := range list {
_, _ = p.out.WriteString(prefix)
_, _ = p.out.WriteString(p.colorize(colorDash, "-"))
_, _ = p.out.WriteString(" ")
if err := p.neatYAML(prefix+p.prefixAdd(), true, entry); err != nil {
return err
}
}
return nil
}
func (p *OutputProcessor) neatYAMLofScalar(prefix string, skipIndentOnFirstLine bool, obj interface{}) error {
// Process nil values immediately and return afterwards
if obj == nil {
_, _ = p.out.WriteString(p.colorize(colorNull, "null"))
_, _ = p.out.WriteString("\n")
return nil
}
// Any other value: Run through Go YAML marshaller and colorize afterwards
data, err := yamlv2.Marshal(obj)
if err != nil {
return err
}
// Decide on one color to be used
color := p.determineColorByType(obj)
// Cast byte slice to string, remove trailing newlines, split into lines
for i, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
if i > 0 {
_, _ = p.out.WriteString(prefix)
}
_, _ = p.out.WriteString(p.colorize(color, line))
_, _ = p.out.WriteString("\n")
}
return nil
}
func (p *OutputProcessor) neatYAMLofNode(prefix string, skipIndentOnFirstLine bool, node *yamlv3.Node) error {
var keyStyles []bunt.StyleOption
if p.boldKeys {
keyStyles = append(keyStyles, bunt.Bold())
}
switch node.Kind {
case yamlv3.DocumentNode:
bunt.Fprint(p.out, p.colorize(documentStart, "---"), "\n")
for _, content := range node.Content {
if err := p.neatYAML(prefix, false, content); err != nil {
return err
}
}
if len(node.FootComment) > 0 {
fmt.Fprint(p.out, p.colorize(colorComment, node.FootComment), "\n")
}
case yamlv3.SequenceNode:
for i, entry := range node.Content {
if i == 0 {
if !skipIndentOnFirstLine {
fmt.Fprint(p.out, prefix)
}
} else {
fmt.Fprint(p.out, prefix)
}
fmt.Fprint(p.out, p.colorize(colorDash, "-"), " ")
if err := p.neatYAMLofNode(prefix+p.prefixAdd(), true, entry); err != nil {
return err
}
}
case yamlv3.MappingNode:
for i := 0; i < len(node.Content); i += 2 {
if !skipIndentOnFirstLine || i > 0 {
fmt.Fprint(p.out, prefix)
}
key := node.Content[i]
if len(key.HeadComment) > 0 {
fmt.Fprint(p.out, p.colorize(colorComment, key.HeadComment), "\n")
}
fmt.Fprint(p.out,
bunt.Style(p.colorizef(colorKey, "%s:", key.Value), keyStyles...),
)
value := node.Content[i+1]
switch value.Kind {
case yamlv3.MappingNode:
if len(value.Content) == 0 {
fmt.Fprint(p.out, p.createAnchorDefinition(value), " ", p.colorize(emptyStructures, emptyObject), "\n")
} else {
fmt.Fprint(p.out, p.createAnchorDefinition(value), "\n")
if err := p.neatYAMLofNode(prefix+p.prefixAdd(), false, value); err != nil {
return err
}
}
case yamlv3.SequenceNode:
if len(value.Content) == 0 {
fmt.Fprint(p.out, p.createAnchorDefinition(value), " ", p.colorize(emptyStructures, emptyList), "\n")
} else {
fmt.Fprint(p.out, p.createAnchorDefinition(value), "\n")
if err := p.neatYAMLofNode(prefix, false, value); err != nil {
return err
}
}
case yamlv3.ScalarNode:
fmt.Fprint(p.out, p.createAnchorDefinition(value), " ")
if err := p.neatYAMLofNode(prefix+p.prefixAdd(), false, value); err != nil {
return err
}
case yamlv3.AliasNode:
fmt.Fprintf(p.out, " %s\n", p.colorizef(colorAnchor, "*%s", value.Value))
}
if len(key.FootComment) > 0 {
fmt.Fprint(p.out, p.colorize(colorComment, key.FootComment), "\n")
}
}
case yamlv3.ScalarNode:
var colorName = colorScalarDefault
switch node.Tag {
case nodeTagBinary:
colorName = colorBinary
case nodeTagString: // default colorName
colorName = colorScalarDefault
case nodeTagFloat:
colorName = colorFloat
case nodeTagInt:
colorName = colorInt
case nodeTagBool:
colorName = colorBool
case nodeTagNull:
colorName = colorNull
}
lines := strings.Split(node.Value, "\n")
switch len(lines) {
case 1:
if needsQuotes(node) {
fmt.Fprint(p.out, p.colorizef(colorName, "%q", node.Value))
} else {
fmt.Fprint(p.out, p.colorize(colorName, node.Value))
}
default:
colorName = colorMultiLineText
fmt.Fprint(p.out, p.colorize(colorName, "|"), "\n")
for i, line := range lines {
fmt.Fprint(p.out,
prefix,
p.colorize(colorName, line),
)
if i != len(lines)-1 {
fmt.Fprint(p.out, "\n")
}
}
}
if len(node.LineComment) > 0 {
fmt.Fprint(p.out, " ", p.colorize(colorComment, node.LineComment))
}
fmt.Fprint(p.out, "\n")
if len(node.FootComment) > 0 {
fmt.Fprint(p.out, p.colorize(colorComment, node.FootComment), "\n")
}
case yamlv3.AliasNode:
if err := p.neatYAMLofNode(prefix, skipIndentOnFirstLine, node.Alias); err != nil {
return err
}
}
return nil
}
func (p *OutputProcessor) neatYAMLOfStruct(prefix string, skipIndentOnFirstLine bool, obj interface{}) error {
// There might be better ways to do it. With generic struct objects, the
// only option is to do a roundtrip marshal and unmarshal to get the
// object into a universal Go YAML library version 3 node object and
// to render the node instead.
data, err := yamlv3.Marshal(obj)
if err != nil {
return err
}
var tmp yamlv3.Node
if err := yamlv3.Unmarshal(data, &tmp); err != nil {
return err
}
return p.neatYAML(prefix, skipIndentOnFirstLine, tmp)
}
func (p *OutputProcessor) createAnchorDefinition(node *yamlv3.Node) string {
if len(node.Anchor) != 0 {
return fmt.Sprint(" ", p.colorizef(colorAnchor, "&%s", node.Anchor))
}
return ""
}
func needsQuotes(node *yamlv3.Node) bool {
// skip all non string nodes
if node.Tag != nodeTagString {
return false
}
// check if string matches one of the known reserved keywords
for _, chk := range yamlReservedKeywords {
if node.Value == chk {
return true
}
}
// check if strings starts with a dash
if strings.HasPrefix(node.Value, "-") {
return true
}
// check if string contains special characters
return strings.ContainsAny(node.Value, " *&:,")
}