/
encoder.go
356 lines (284 loc) · 7.29 KB
/
encoder.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package encoder
import (
"reflect"
"sort"
"strings"
yaml "gopkg.in/yaml.v3"
)
// Encoder implements config encoder.
type Encoder struct {
value interface{}
options *Options
}
// NewEncoder initializes and returns an `Encoder`.
func NewEncoder(value interface{}, opts ...Option) *Encoder {
return &Encoder{
value: value,
options: newOptions(opts...),
}
}
// Marshal converts value to YAML-serializable value (suitable for MarshalYAML).
func (e *Encoder) Marshal() (*yaml.Node, error) {
node, err := toYamlNode(e.value, e.options.Comments)
if err != nil {
return nil, err
}
if e.options.Comments.enabled(CommentsDocs) {
addComments(node, getDoc(e.value), HeadComment, LineComment)
}
return node, nil
}
// Encode converts value to yaml.
//nolint:gocyclo
func (e *Encoder) Encode() ([]byte, error) {
if e.options.Comments == CommentsDisabled {
return yaml.Marshal(e.value)
}
node, err := e.Marshal()
if err != nil {
return nil, err
}
// special handling for case when we get an empty output
if node.Kind == yaml.MappingNode && len(node.Content) == 0 && node.FootComment != "" && e.options.Comments.enabled(CommentsExamples) {
res := ""
if node.HeadComment != "" {
res += node.HeadComment + "\n"
}
lines := strings.Split(res+node.FootComment, "\n")
for i, line := range lines {
if strings.HasPrefix(line, "#") || strings.TrimSpace(line) == "" {
continue
}
lines[i] = "# " + line
}
return []byte(strings.Join(lines, "\n")), nil
}
return yaml.Marshal(node)
}
func isEmpty(value reflect.Value) bool {
if !value.IsValid() {
return true
}
//nolint:exhaustive
switch value.Kind() {
case reflect.Ptr:
return value.IsNil()
case reflect.Map:
return len(value.MapKeys()) == 0
case reflect.Slice:
return value.Len() == 0
default:
return value.IsZero()
}
}
func isNil(value reflect.Value) bool {
if !value.IsValid() {
return true
}
//nolint:exhaustive
switch value.Kind() {
case reflect.Ptr, reflect.Map, reflect.Slice:
return value.IsNil()
default:
return false
}
}
//nolint:gocyclo,cyclop
func toYamlNode(in interface{}, flags CommentsFlags) (*yaml.Node, error) {
node := &yaml.Node{}
// do not wrap yaml.Node into yaml.Node
if n, ok := in.(*yaml.Node); ok {
return n, nil
}
// if input implements yaml.Marshaler we should use that marshaller instead
// same way as regular yaml marshal does
if m, ok := in.(yaml.Marshaler); ok {
res, err := m.MarshalYAML()
if err != nil {
return nil, err
}
if n, ok := res.(*yaml.Node); ok {
return n, nil
}
in = res
}
v := reflect.ValueOf(in)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
doc := getDoc(in)
//nolint:exhaustive
switch v.Kind() {
case reflect.Struct:
node.Kind = yaml.MappingNode
t := v.Type()
examples := []string{}
for i := 0; i < v.NumField(); i++ {
// skip unexported fields
if !v.Field(i).CanInterface() {
continue
}
tag := t.Field(i).Tag.Get("yaml")
parts := strings.Split(tag, ",")
fieldName := parts[0]
parts = parts[1:]
tag = t.Field(i).Tag.Get("talos")
if tag != "" {
parts = append(parts, strings.Split(tag, ",")...)
}
if fieldName == "" {
fieldName = strings.ToLower(t.Field(i).Name)
}
if fieldName == "-" {
continue
}
var (
empty = isEmpty(v.Field(i))
null = isNil(v.Field(i))
skip bool
inline bool
flow bool
)
for _, part := range parts {
if part == "omitempty" && empty {
skip = true
}
if part == "omitonlyifnil" && !null {
skip = false
}
if part == "inline" {
inline = true
}
if part == "flow" {
flow = true
}
}
var value interface{}
if v.Field(i).CanInterface() {
value = v.Field(i).Interface()
}
// get documentation data either from field, or from type
var fieldDoc *Doc
if doc != nil {
fieldDoc = mergeDoc(getDoc(value), doc.Field(i))
} else {
fieldDoc = getDoc(value)
}
// inlineExample is rendered after the value
var inlineExample string
if empty && flags.enabled(CommentsExamples) && fieldDoc != nil {
if skip {
// render example to be appended to the end of the rendered struct
example := renderExample(fieldName, fieldDoc, flags)
if example != "" {
examples = append(examples, example)
}
} else {
// render example to be appended to the empty field
fieldDocCopy := *fieldDoc
fieldDocCopy.Comments = [3]string{}
inlineExample = renderExample("", &fieldDocCopy, flags)
}
}
if skip {
continue
}
var style yaml.Style
if flow {
style |= yaml.FlowStyle
}
if inline {
child, err := toYamlNode(value, flags)
if err != nil {
return nil, err
}
if child.Kind == yaml.MappingNode || child.Kind == yaml.SequenceNode {
appendNodes(node, child.Content...)
}
} else if err := addToMap(node, fieldDoc, fieldName, value, style, flags); err != nil {
return nil, err
}
if inlineExample != "" {
nodeToAttach := node.Content[len(node.Content)-1]
if nodeToAttach.FootComment != "" {
nodeToAttach.FootComment += "\n"
}
nodeToAttach.FootComment += inlineExample
}
}
if len(examples) > 0 {
comment := strings.Join(examples, "\n")
// add rendered example to the foot comment of the last node
// or to the foot comment of parent node
if len(node.Content) > 0 {
node.Content[len(node.Content)-2].FootComment += "\n" + comment
} else {
node.FootComment += comment
}
}
case reflect.Map:
node.Kind = yaml.MappingNode
keys := v.MapKeys()
// always interate keys in alphabetical order to preserve the same output for maps
sort.Slice(keys, func(i, j int) bool {
return keys[i].String() < keys[j].String()
})
for _, k := range keys {
element := v.MapIndex(k)
value := element.Interface()
if err := addToMap(node, nil, k.Interface(), value, 0, flags); err != nil {
return nil, err
}
}
case reflect.Slice:
node.Kind = yaml.SequenceNode
nodes := make([]*yaml.Node, v.Len())
for i := 0; i < v.Len(); i++ {
element := v.Index(i)
var err error
nodes[i], err = toYamlNode(element.Interface(), flags)
if err != nil {
return nil, err
}
}
appendNodes(node, nodes...)
default:
if err := node.Encode(in); err != nil {
return nil, err
}
}
return node, nil
}
func appendNodes(dest *yaml.Node, nodes ...*yaml.Node) {
if dest.Content == nil {
dest.Content = []*yaml.Node{}
}
dest.Content = append(dest.Content, nodes...)
}
func addToMap(dest *yaml.Node, doc *Doc, fieldName, in interface{}, style yaml.Style, flags CommentsFlags) error {
key, err := toYamlNode(fieldName, flags)
if err != nil {
return err
}
value, err := toYamlNode(in, flags)
if err != nil {
return err
}
value.Style = style
if flags.enabled(CommentsDocs) {
addComments(key, doc, HeadComment, FootComment)
addComments(value, doc, LineComment)
}
// override head comment with line comment for non-scalar nodes
if value.Kind != yaml.ScalarNode {
if key.HeadComment == "" {
key.HeadComment = value.LineComment
}
value.LineComment = ""
}
appendNodes(dest, key, value)
return nil
}