Debian Codegraph @

pkg/format/node.go

raw
1 package format
2
3 import (
4 "fmt"
5 "reflect"
6 "sort"
7 "strconv"
8 "strings"
9 "time"
10
11 "github.com/nicholas-fedor/shoutrrr/pkg/types"
12 "github.com/nicholas-fedor/shoutrrr/pkg/util"
13 )
14
15 // Node is the generic config tree item.
16 type Node interface {
17 Field() *FieldInfo
18 TokenType() NodeTokenType
19 Update(tv reflect.Value)
20 }
21
22 // NodeTokenType is used to represent the type of value that a node has for syntax highlighting.
23 type NodeTokenType int
24
25 // ContainerNode is a Node with child items.
26 type ContainerNode struct {
27 *FieldInfo
28
29 Items []Node
30 MaxKeyLength int
31 }
32
33 // ValueNode is a Node without any child items.
34 type ValueNode struct {
35 *FieldInfo
36
37 Value string
38 tokenType NodeTokenType
39 }
40
41 const (
42 // UnknownToken represents all unknown/unspecified tokens.
43 UnknownToken NodeTokenType = iota
44 // NumberToken represents all numbers.
45 NumberToken
46 // StringToken represents strings and keys.
47 StringToken
48 // EnumToken represents enum values.
49 EnumToken
50 // TrueToken represent boolean true.
51 TrueToken
52 // FalseToken represent boolean false.
53 FalseToken
54 // PropToken represent a serializable struct prop.
55 PropToken
56 // ErrorToken represent a value that was not serializable or otherwise invalid.
57 ErrorToken
58 // ContainerToken is used for Array/Slice and Map tokens.
59 ContainerToken
60 )
61
62 // Constants for number bases.
63 const (
64 BaseDecimalLen = 10
65 BaseHexLen = 16
66 )
67
68 // Field returns the FieldInfo associated with this value node.
69 //
70 // Returns:
71 // - The node's FieldInfo.
72 func (n *ValueNode) Field() *FieldInfo {
73 return n.FieldInfo
74 }
75
76 // TokenType returns the syntax-highlighting token type for this node's value.
77 //
78 // Returns:
79 // - The NodeTokenType that matches the stored value.
80 func (n *ValueNode) TokenType() NodeTokenType {
81 return n.tokenType
82 }
83
84 // Update refreshes the node's display string and token type from the provided value.
85 //
86 // Parameters:
87 // - tv: The reflected field value to render.
88 func (n *ValueNode) Update(tv reflect.Value) {
89 value, token := getValueNodeValue(tv, n.FieldInfo)
90 n.Value = value
91 n.tokenType = token
92 }
93
94 // Field returns the FieldInfo associated with this container node.
95 //
96 // Returns:
97 // - The node's FieldInfo.
98 func (n *ContainerNode) Field() *FieldInfo {
99 return n.FieldInfo
100 }
101
102 // TokenType returns ContainerToken for every container node.
103 //
104 // Returns:
105 // - ContainerToken.
106 func (n *ContainerNode) TokenType() NodeTokenType {
107 return ContainerToken
108 }
109
110 // Update rebuilds the container's child items to match the provided value.
111 //
112 // Array and slice values replace Items with one node per element.
113 // Map values replace Items with one node per key, sorted by key name.
114 // Other kinds are left unchanged.
115 //
116 // Parameters:
117 // - tv: The reflected container value to expand into child items.
118 func (n *ContainerNode) Update(tv reflect.Value) {
119 switch n.Type.Kind() {
120 case reflect.Array, reflect.Slice:
121 n.updateArrayNode(tv)
122 case reflect.Map:
123 n.updateMapNode(tv)
124 case reflect.Invalid,
125 reflect.Bool,
126 reflect.Int,
127 reflect.Int8,
128 reflect.Int16,
129 reflect.Int32,
130 reflect.Int64,
131 reflect.Uint,
132 reflect.Uint8,
133 reflect.Uint16,
134 reflect.Uint32,
135 reflect.Uint64,
136 reflect.Uintptr,
137 reflect.Float32,
138 reflect.Float64,
139 reflect.Complex64,
140 reflect.Complex128,
141 reflect.Chan,
142 reflect.Func,
143 reflect.Interface,
144 reflect.Pointer,
145 reflect.String,
146 reflect.Struct,
147 reflect.UnsafePointer:
148 // No-op for unsupported kinds
149 default:
150 // No-op for any remaining kinds
151 }
152 }
153
154 // updateArrayNode rebuilds the container's Items from an array or slice value.
155 //
156 // Each element becomes a ValueNode named by its index.
157 //
158 // Parameters:
159 // - arrayValue: The reflected array or slice to expand.
160 func (n *ContainerNode) updateArrayNode(arrayValue reflect.Value) {
161 itemCount := arrayValue.Len()
162 n.Items = make([]Node, 0, itemCount)
163
164 elemType := arrayValue.Type().Elem()
165
166 for i := range itemCount {
167 key := strconv.Itoa(i)
168 val := arrayValue.Index(i)
169 n.Items = append(n.Items, getValueNode(val, &FieldInfo{
170 Name: key,
171 Type: elemType,
172 EnumFormatter: nil,
173 Description: "",
174 DefaultValue: "",
175 Template: "",
176 Required: false,
177 URLParts: nil,
178 Title: false,
179 Base: 0,
180 Keys: nil,
181 ItemSeparator: 0,
182 }))
183 }
184 }
185
186 // getArrayNode builds a ContainerNode whose children represent the elements of an array or slice.
187 //
188 // Parameters:
189 // - arrayValue: The reflected array or slice to expand.
190 // - fieldInfo: Metadata for the array or slice field.
191 //
192 // Returns:
193 // - A ContainerNode with one child node per element.
194 func getArrayNode(arrayValue reflect.Value, fieldInfo *FieldInfo) *ContainerNode {
195 node := &ContainerNode{
196 FieldInfo: fieldInfo,
197 Items: nil,
198 MaxKeyLength: 0,
199 }
200 node.updateArrayNode(arrayValue)
201
202 return node
203 }
204
205 // sortNodeItems sorts node items in place by their FieldInfo name.
206 //
207 // Parameters:
208 // - nodeItems: The slice of nodes to sort.
209 func sortNodeItems(nodeItems []Node) {
210 sort.Slice(nodeItems, func(i, j int) bool {
211 return nodeItems[i].Field().Name < nodeItems[j].Field().Name
212 })
213 }
214
215 // updateMapNode rebuilds the container's Items from a map value.
216 //
217 // Each map entry becomes a ValueNode named by its string key.
218 // Items are sorted by key, and MaxKeyLength is set to the longest key.
219 //
220 // Parameters:
221 // - mapValue: The reflected map to expand.
222 func (n *ContainerNode) updateMapNode(mapValue reflect.Value) {
223 base := n.Base
224 if base == 0 {
225 base = BaseDecimalLen
226 }
227
228 elemType := mapValue.Type().Elem()
229 mapKeys := mapValue.MapKeys()
230 nodeItems := make([]Node, len(mapKeys))
231 maxKeyLength := 0
232
233 for i, keyVal := range mapKeys {
234 // The keys will always be strings
235 key := keyVal.String()
236 val := mapValue.MapIndex(keyVal)
237 nodeItems[i] = getValueNode(val, &FieldInfo{
238 Name: key,
239 Type: elemType,
240 EnumFormatter: nil,
241 Description: "",
242 DefaultValue: "",
243 Template: "",
244 Required: false,
245 URLParts: nil,
246 Title: false,
247 Base: base,
248 Keys: nil,
249 ItemSeparator: 0,
250 })
251 maxKeyLength = util.Max(len(key), maxKeyLength)
252 }
253
254 sortNodeItems(nodeItems)
255
256 n.Items = nodeItems
257 n.MaxKeyLength = maxKeyLength
258 }
259
260 // getMapNode builds a ContainerNode whose children represent the entries of a map.
261 //
262 // Pointer values are dereferenced before the map is expanded.
263 //
264 // Parameters:
265 // - mapValue: The reflected map, or a pointer to a map.
266 // - fieldInfo: Metadata for the map field.
267 //
268 // Returns:
269 // - A ContainerNode with one child node per map entry.
270 func getMapNode(mapValue reflect.Value, fieldInfo *FieldInfo) *ContainerNode {
271 if mapValue.Kind() == reflect.Pointer {
272 mapValue = mapValue.Elem()
273 }
274
275 node := &ContainerNode{
276 FieldInfo: fieldInfo,
277 Items: nil,
278 MaxKeyLength: 0,
279 }
280 node.updateMapNode(mapValue)
281
282 return node
283 }
284
285 // getNode builds the tree node that represents a single config field.
286 //
287 // Arrays, slices, and maps become ContainerNodes.
288 // Every other kind becomes a ValueNode.
289 //
290 // Parameters:
291 // - fieldVal: The reflected field value.
292 // - fieldInfo: Metadata for the field.
293 //
294 // Returns:
295 // - A Node for the field.
296 func getNode(fieldVal reflect.Value, fieldInfo *FieldInfo) Node {
297 switch fieldInfo.Type.Kind() {
298 case reflect.Array, reflect.Slice:
299 return getArrayNode(fieldVal, fieldInfo)
300 case reflect.Map:
301 return getMapNode(fieldVal, fieldInfo)
302 case reflect.Invalid,
303 reflect.Bool,
304 reflect.Int,
305 reflect.Int8,
306 reflect.Int16,
307 reflect.Int32,
308 reflect.Int64,
309 reflect.Uint,
310 reflect.Uint8,
311 reflect.Uint16,
312 reflect.Uint32,
313 reflect.Uint64,
314 reflect.Uintptr,
315 reflect.Float32,
316 reflect.Float64,
317 reflect.Complex64,
318 reflect.Complex128,
319 reflect.Chan,
320 reflect.Func,
321 reflect.Interface,
322 reflect.Pointer,
323 reflect.String,
324 reflect.Struct,
325 reflect.UnsafePointer:
326 return getValueNode(fieldVal, fieldInfo)
327 default:
328 return getValueNode(fieldVal, fieldInfo)
329 }
330 }
331
332 // getRootNode builds the root ContainerNode for a service config value.
333 //
334 // It reflects the struct fields, attaches enum formatters when the value
335 // implements types.Enummer, and sorts the resulting child nodes by field name.
336 //
337 // Parameters:
338 // - value: The config value, typically a struct or a pointer to a struct.
339 //
340 // Returns:
341 // - A ContainerNode whose children represent the config fields.
342 func getRootNode(value any) *ContainerNode {
343 structValue := reflect.ValueOf(value)
344 if structValue.Kind() == reflect.Pointer {
345 structValue = structValue.Elem()
346 }
347
348 structType := structValue.Type()
349
350 enums := map[string]types.EnumFormatter{}
351 if enummer, isEnummer := value.(types.Enummer); isEnummer {
352 enums = enummer.Enums()
353 }
354
355 infoFields := getStructFieldInfo(structType, enums)
356 nodeItems := make([]Node, 0, len(infoFields))
357 maxKeyLength := 0
358
359 for i := range infoFields {
360 fieldValue := structValue.FieldByName(infoFields[i].Name)
361 if !fieldValue.IsValid() {
362 fieldValue = reflect.Zero(infoFields[i].Type)
363 }
364
365 nodeItems = append(nodeItems, getNode(fieldValue, &infoFields[i]))
366 maxKeyLength = util.Max(len(infoFields[i].Name), maxKeyLength)
367 }
368
369 sortNodeItems(nodeItems)
370
371 return &ContainerNode{
372 FieldInfo: &FieldInfo{
373 Name: "",
374 Type: structType,
375 EnumFormatter: nil,
376 Description: "",
377 DefaultValue: "",
378 Template: "",
379 Required: false,
380 URLParts: nil,
381 Title: false,
382 Base: 0,
383 Keys: nil,
384 ItemSeparator: 0,
385 },
386 Items: nodeItems,
387 MaxKeyLength: maxKeyLength,
388 }
389 }
390
391 // getValueNode wraps a field value in a ValueNode.
392 //
393 // The node's Value is the rendered display string and tokenType is the token used to color it.
394 //
395 // Parameters:
396 // - fieldVal: The reflected field value to render.
397 // - fieldInfo: Metadata for the field.
398 //
399 // Returns:
400 // - A ValueNode pairing the display string with its token type.
401 func getValueNode(fieldVal reflect.Value, fieldInfo *FieldInfo) *ValueNode {
402 value, tokenType := getValueNodeValue(fieldVal, fieldInfo)
403
404 return &ValueNode{
405 FieldInfo: fieldInfo,
406 Value: value,
407 tokenType: tokenType,
408 }
409 }
410
411 // getValueNodeValue renders a field value as its display string and token type.
412 //
413 // Enums print via their formatter and durations via Go duration syntax.
414 // All other kinds are formatted from their reflect.Kind.
415 //
416 // Parameters:
417 // - fieldValue: The reflected field value to render.
418 // - fieldInfo: Metadata for the field, including enum and duration type.
419 //
420 // Returns:
421 // - The display string for the value.
422 // - The NodeTokenType used to color that string.
423 func getValueNodeValue(fieldValue reflect.Value, fieldInfo *FieldInfo) (string, NodeTokenType) {
424 kind := fieldValue.Kind()
425
426 base := fieldInfo.Base
427 if base == 0 {
428 base = BaseDecimalLen
429 }
430
431 if fieldInfo.IsEnum() {
432 return fieldInfo.EnumFormatter.Print(int(fieldValue.Int())), EnumToken
433 }
434
435 if fieldInfo.Type == durationType {
436 return time.Duration(fieldValue.Int()).String(), StringToken
437 }
438
439 switch kind {
440 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
441 val := strconv.FormatUint(fieldValue.Uint(), base)
442 if base == BaseHexLen {
443 val = "0x" + val
444 }
445
446 return val, NumberToken
447 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
448 return strconv.FormatInt(fieldValue.Int(), base), NumberToken
449 case reflect.String:
450 return fieldValue.String(), StringToken
451 case reflect.Bool:
452 val := fieldValue.Bool()
453 if val {
454 return PrintBool(val), TrueToken
455 }
456
457 return PrintBool(val), FalseToken
458 case reflect.Array, reflect.Slice, reflect.Map:
459 return getContainerValueString(fieldValue, fieldInfo), UnknownToken
460 case reflect.Pointer, reflect.Struct:
461 if val, err := GetConfigPropString(fieldValue); err == nil {
462 return val, PropToken
463 }
464
465 return "<ERR>", ErrorToken
466 case reflect.Invalid,
467 reflect.Uintptr,
468 reflect.Float32,
469 reflect.Float64,
470 reflect.Complex64,
471 reflect.Complex128,
472 reflect.Chan,
473 reflect.Func,
474 reflect.Interface,
475 reflect.UnsafePointer:
476 return fmt.Sprintf("<?%s>", kind.String()), UnknownToken
477 default:
478 return fmt.Sprintf("<?%s>", kind.String()), UnknownToken
479 }
480 }
481
482 // getContainerValueString renders an array, slice, or map as a single display string.
483 //
484 // Elements are joined with the field's ItemSeparator.
485 // Map entries are written as key:value pairs and sorted by key.
486 //
487 // Parameters:
488 // - fieldValue: The reflected array, slice, or map to render.
489 // - fieldInfo: Metadata for the container field, including ItemSeparator and Base.
490 //
491 // Returns:
492 // - The joined display string for the container's items.
493 func getContainerValueString(fieldValue reflect.Value, fieldInfo *FieldInfo) string {
494 itemSeparator := fieldInfo.ItemSeparator
495 sliceLength := fieldValue.Len()
496
497 var mapKeys []reflect.Value
498 if fieldInfo.Type.Kind() == reflect.Map {
499 mapKeys = fieldValue.MapKeys()
500 sort.Slice(mapKeys, func(a, b int) bool {
501 return mapKeys[a].String() < mapKeys[b].String()
502 })
503 }
504
505 stringBuilder := strings.Builder{}
506
507 var itemFieldInfo *FieldInfo
508
509 for i := range sliceLength {
510 var itemValue reflect.Value
511
512 if i > 0 {
513 stringBuilder.WriteRune(itemSeparator)
514 }
515
516 if mapKeys != nil {
517 mapKey := mapKeys[i]
518 stringBuilder.WriteString(mapKey.String())
519 stringBuilder.WriteRune(':')
520
521 itemValue = fieldValue.MapIndex(mapKey)
522 } else {
523 itemValue = fieldValue.Index(i)
524 }
525
526 if i == 0 {
527 itemFieldInfo = &FieldInfo{
528 Name: "",
529 Type: itemValue.Type(),
530 EnumFormatter: nil,
531 Description: "",
532 DefaultValue: "",
533 Template: "",
534 Required: false,
535 URLParts: nil,
536 Title: false,
537 // Inherit the base from the container
538 Base: fieldInfo.Base,
539 Keys: nil,
540 ItemSeparator: 0,
541 }
542
543 if itemFieldInfo.Base == 0 {
544 itemFieldInfo.Base = BaseDecimalLen
545 }
546 }
547
548 strVal, _ := getValueNodeValue(itemValue, itemFieldInfo)
549 stringBuilder.WriteString(strVal)
550 }
551
552 return stringBuilder.String()
553 }