Debian Codegraph @

pkg/format/formatter.go

raw
1 package format
2
3 import (
4 "errors"
5 "fmt"
6 "math"
7 "reflect"
8 "strconv"
9 "strings"
10
11 "github.com/nicholas-fedor/shoutrrr/pkg/types"
12 "github.com/nicholas-fedor/shoutrrr/pkg/util"
13 )
14
15 // Constants for map parsing and type sizes.
16 const (
17 KeyValuePairSize = 2 // Number of elements in a key:value pair
18 Int32BitSize = 32 // Bit size for 32-bit integers
19 Int64BitSize = 64 // Bit size for 64-bit integers
20 )
21
22 // Errors defined as static variables for better error handling.
23 var (
24 ErrInvalidEnumValue = errors.New("not a valid enum value")
25 ErrInvalidBoolValue = errors.New("accepted values are 1, true, yes or 0, false, no")
26 ErrUnsupportedFieldKey = errors.New("field key format is not supported")
27 ErrInvalidFieldValue = errors.New("invalid field value format")
28 ErrUnsupportedField = errors.New("field format is not supported")
29 ErrInvalidFieldCount = errors.New("invalid field value count")
30 ErrInvalidFieldKind = errors.New("invalid field kind")
31 ErrUnsupportedMapValue = errors.New("map value format is not supported")
32 ErrInvalidFieldValueData = errors.New("invalid field value")
33 ErrFailedToSetEnumValue = errors.New("failed to set enum value")
34 ErrUnexpectedUintKind = errors.New("unexpected uint kind")
35 ErrUnexpectedIntKind = errors.New("unexpected int kind")
36 ErrParseIntFailed = errors.New("failed to parse integer")
37 ErrParseUintFailed = errors.New("failed to parse unsigned integer")
38 )
39
40 // GetServiceConfig extracts the inner config from a service.
41 func GetServiceConfig(service types.Service) types.ServiceConfig {
42 serviceValue := reflect.Indirect(reflect.ValueOf(service))
43
44 configField, ok := serviceValue.Type().FieldByName("Config")
45 if !ok {
46 panic("service does not have a Config field")
47 }
48
49 configRef := serviceValue.FieldByIndex(configField.Index)
50 if configRef.IsNil() {
51 configType := configField.Type
52 if configType.Kind() == reflect.Pointer {
53 configType = configType.Elem()
54 }
55
56 newConfig := reflect.New(configType).Interface()
57 if config, ok := newConfig.(types.ServiceConfig); ok {
58 return config
59 }
60
61 panic("failed to create new config instance")
62 }
63
64 if config, ok := configRef.Interface().(types.ServiceConfig); ok {
65 return config
66 }
67
68 panic("config reference is not a ServiceConfig")
69 }
70
71 // ColorFormatTree generates a color-highlighted string representation of a node tree.
72 func ColorFormatTree(rootNode *ContainerNode, withValues bool) string {
73 return ConsoleTreeRenderer{WithValues: withValues}.RenderTree(rootNode, "")
74 }
75
76 // GetServiceConfigFormat retrieves type and field information from a service's config.
77 func GetServiceConfigFormat(service types.Service) *ContainerNode {
78 return GetConfigFormat(GetServiceConfig(service))
79 }
80
81 // GetConfigFormat retrieves type and field information from a ServiceConfig.
82 func GetConfigFormat(config types.ServiceConfig) *ContainerNode {
83 return getRootNode(config)
84 }
85
86 // SetConfigField updates a config field with a deserialized value from a string.
87 func SetConfigField(config reflect.Value, field *FieldInfo, inputValue string) (bool, error) {
88 configField := config.FieldByName(field.Name)
89 if field.EnumFormatter != nil {
90 return setEnumField(configField, field, inputValue)
91 }
92
93 switch field.Type.Kind() {
94 case reflect.String:
95 configField.SetString(inputValue)
96
97 return true, nil
98 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
99 return setIntField(configField, field, inputValue)
100 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
101 return setUintField(configField, field, inputValue)
102 case reflect.Bool:
103 return setBoolField(configField, inputValue)
104 case reflect.Map:
105 return setMapField(configField, field, inputValue)
106 case reflect.Struct:
107 return setStructField(configField, field, inputValue)
108 case reflect.Slice, reflect.Array:
109 return setSliceOrArrayField(configField, field, inputValue)
110 case reflect.Invalid,
111 reflect.Uintptr,
112 reflect.Float32,
113 reflect.Float64,
114 reflect.Complex64,
115 reflect.Complex128,
116 reflect.Chan,
117 reflect.Func,
118 reflect.Interface,
119 reflect.Pointer,
120 reflect.UnsafePointer:
121 return false, fmt.Errorf("%w: %v", ErrInvalidFieldKind, field.Type.Kind())
122 default:
123 return false, fmt.Errorf("%w: %v", ErrInvalidFieldKind, field.Type.Kind())
124 }
125 }
126
127 // setIntField handles integer field setting.
128 func setIntField(configField reflect.Value, field *FieldInfo, inputValue string) (bool, error) {
129 number, detectedBase := util.StripNumberPrefix(inputValue)
130
131 base := detectedBase
132 if field.Base > 0 {
133 base = field.Base
134
135 if detectedBase == 0 {
136 number = inputValue
137 }
138 }
139
140 value, err := strconv.ParseInt(number, base, field.Type.Bits())
141 if err != nil {
142 return false, fmt.Errorf("%w: %w", ErrParseIntFailed, err)
143 }
144
145 configField.SetInt(value)
146
147 return true, nil
148 }
149
150 // setUintField handles unsigned integer field setting.
151 func setUintField(configField reflect.Value, field *FieldInfo, inputValue string) (bool, error) {
152 number, detectedBase := util.StripNumberPrefix(inputValue)
153
154 base := detectedBase
155 if field.Base > 0 {
156 base = field.Base
157
158 if detectedBase == 0 {
159 number = inputValue
160 }
161 }
162
163 value, err := strconv.ParseUint(number, base, field.Type.Bits())
164 if err != nil {
165 return false, fmt.Errorf("%w: %w", ErrParseUintFailed, err)
166 }
167
168 configField.SetUint(value)
169
170 return true, nil
171 }
172
173 // setBoolField handles boolean field setting.
174 func setBoolField(configField reflect.Value, inputValue string) (bool, error) {
175 value, ok := ParseBool(inputValue, false)
176 if !ok {
177 return false, ErrInvalidBoolValue
178 }
179
180 configField.SetBool(value)
181
182 return true, nil
183 }
184
185 // setMapField handles map field setting.
186 func setMapField(configField reflect.Value, field *FieldInfo, inputValue string) (bool, error) {
187 if field.Type.Key().Kind() != reflect.String {
188 return false, ErrUnsupportedFieldKey
189 }
190
191 mapValue := reflect.MakeMap(field.Type)
192
193 pairs := strings.SplitSeq(inputValue, ",")
194 for pair := range pairs {
195 elems := strings.Split(pair, ":")
196 if len(elems) != KeyValuePairSize {
197 return false, ErrInvalidFieldValue
198 }
199
200 key, valueRaw := elems[0], elems[1]
201
202 value, err := getMapValue(field.Type.Elem(), valueRaw)
203 if err != nil {
204 return false, err
205 }
206
207 mapValue.SetMapIndex(reflect.ValueOf(key), value)
208 }
209
210 configField.Set(mapValue)
211
212 return true, nil
213 }
214
215 // setStructField handles struct field setting.
216 func setStructField(configField reflect.Value, field *FieldInfo, inputValue string) (bool, error) {
217 valuePtr, err := GetConfigPropFromString(field.Type, inputValue)
218 if err != nil {
219 return false, err
220 }
221
222 configField.Set(valuePtr.Elem())
223
224 return true, nil
225 }
226
227 // setSliceOrArrayField handles slice or array field setting.
228 func setSliceOrArrayField(
229 configField reflect.Value,
230 field *FieldInfo,
231 inputValue string,
232 ) (bool, error) {
233 elemType := field.Type.Elem()
234 elemKind := elemType.Kind()
235
236 if elemKind == reflect.Pointer {
237 elemKind = elemType.Elem().Kind()
238 }
239
240 if elemKind != reflect.Struct && elemKind != reflect.String {
241 return false, ErrUnsupportedField
242 }
243
244 values := strings.Split(inputValue, string(field.ItemSeparator))
245 if field.Type.Kind() == reflect.Array && len(values) != field.Type.Len() {
246 return false, fmt.Errorf("%w: needs to be %d", ErrInvalidFieldCount, field.Type.Len())
247 }
248
249 return setSliceOrArrayValues(configField, field, elemType, values)
250 }
251
252 // setSliceOrArrayValues sets the actual values for slice or array fields.
253 func setSliceOrArrayValues(
254 configField reflect.Value,
255 field *FieldInfo,
256 elemType reflect.Type,
257 values []string,
258 ) (bool, error) {
259 isPtrSlice := elemType.Kind() == reflect.Pointer
260 baseType := elemType
261
262 if isPtrSlice {
263 baseType = elemType.Elem()
264 }
265
266 if baseType.Kind() == reflect.Struct {
267 slice := reflect.MakeSlice(reflect.SliceOf(elemType), 0, len(values))
268
269 for _, v := range values {
270 propPtr, err := GetConfigPropFromString(baseType, v)
271 if err != nil {
272 return false, err
273 }
274
275 if isPtrSlice {
276 slice = reflect.Append(slice, propPtr)
277 } else {
278 slice = reflect.Append(slice, propPtr.Elem())
279 }
280 }
281
282 configField.Set(slice)
283
284 return true, nil
285 }
286
287 // Handle string slice/array
288 value := reflect.ValueOf(values)
289
290 if field.Type.Kind() == reflect.Array {
291 arr := reflect.Indirect(reflect.New(field.Type))
292 reflect.Copy(arr, value)
293 configField.Set(arr)
294 } else {
295 configField.Set(value)
296 }
297
298 return true, nil
299 }
300
301 // setEnumField handles enum field setting.
302 func setEnumField(configField reflect.Value, field *FieldInfo, inputValue string) (bool, error) {
303 value := field.EnumFormatter.Parse(inputValue)
304 if value == EnumInvalid {
305 return false, fmt.Errorf(
306 "%w: accepted values are %v",
307 ErrInvalidEnumValue,
308 field.EnumFormatter.Names(),
309 )
310 }
311
312 configField.SetInt(int64(value))
313
314 if actual := int(configField.Int()); actual != value {
315 return false, fmt.Errorf(
316 "%w: expected %d, got %d (canSet: %v)",
317 ErrFailedToSetEnumValue,
318 value,
319 actual,
320 configField.CanSet(),
321 )
322 }
323
324 return true, nil
325 }
326
327 // getMapValue converts a raw string to a map value based on type.
328 func getMapValue(valueType reflect.Type, valueRaw string) (reflect.Value, error) {
329 switch valueType.Kind() {
330 case reflect.String:
331 return reflect.ValueOf(valueRaw), nil
332 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
333 return getMapUintValue(valueRaw, valueType)
334 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
335 return getMapIntValue(valueRaw, valueType)
336 case reflect.Invalid,
337 reflect.Bool,
338 reflect.Uintptr,
339 reflect.Float32,
340 reflect.Float64,
341 reflect.Complex64,
342 reflect.Complex128,
343 reflect.Array,
344 reflect.Chan,
345 reflect.Func,
346 reflect.Interface,
347 reflect.Map,
348 reflect.Pointer,
349 reflect.Slice,
350 reflect.Struct,
351 reflect.UnsafePointer:
352 return reflect.Value{}, ErrUnsupportedMapValue
353 default:
354 return reflect.Value{}, ErrUnsupportedMapValue
355 }
356 }
357
358 // getMapUintValue converts a string to an unsigned integer map value.
359 func getMapUintValue(valueRaw string, valueType reflect.Type) (reflect.Value, error) {
360 number, base := util.StripNumberPrefix(valueRaw)
361
362 if base == 0 {
363 base = 10 // Default to decimal for maps if no prefix
364 }
365
366 numValue, err := strconv.ParseUint(number, base, valueType.Bits())
367 if err != nil {
368 return reflect.Value{}, fmt.Errorf("%w: %w", ErrParseUintFailed, err)
369 }
370
371 switch valueType.Kind() {
372 case reflect.Uint:
373 return reflect.ValueOf(uint(numValue)), nil
374 case reflect.Uint8:
375 if numValue > math.MaxUint8 {
376 return reflect.Value{}, fmt.Errorf(
377 "%w: value %d exceeds uint8 range",
378 ErrParseUintFailed,
379 numValue,
380 )
381 }
382
383 return reflect.ValueOf(uint8(numValue)), nil
384 case reflect.Uint16:
385 if numValue > math.MaxUint16 {
386 return reflect.Value{}, fmt.Errorf(
387 "%w: value %d exceeds uint16 range",
388 ErrParseUintFailed,
389 numValue,
390 )
391 }
392
393 return reflect.ValueOf(uint16(numValue)), nil
394 case reflect.Uint32:
395 if numValue > math.MaxUint32 {
396 return reflect.Value{}, fmt.Errorf(
397 "%w: value %d exceeds uint32 range",
398 ErrParseUintFailed,
399 numValue,
400 )
401 }
402
403 return reflect.ValueOf(uint32(numValue)), nil
404 case reflect.Uint64:
405 return reflect.ValueOf(numValue), nil
406 case reflect.Invalid,
407 reflect.Bool,
408 reflect.Int,
409 reflect.Int8,
410 reflect.Int16,
411 reflect.Int32,
412 reflect.Int64,
413 reflect.Uintptr,
414 reflect.Float32,
415 reflect.Float64,
416 reflect.Complex64,
417 reflect.Complex128,
418 reflect.Array,
419 reflect.Chan,
420 reflect.Func,
421 reflect.Interface,
422 reflect.Map,
423 reflect.Pointer,
424 reflect.Slice,
425 reflect.String,
426 reflect.Struct,
427 reflect.UnsafePointer:
428 return reflect.Value{}, ErrUnexpectedUintKind
429 default:
430 return reflect.Value{}, ErrUnexpectedUintKind
431 }
432 }
433
434 // getMapIntValue converts a string to a signed integer map value.
435 func getMapIntValue(valueRaw string, valueType reflect.Type) (reflect.Value, error) {
436 number, base := util.StripNumberPrefix(valueRaw)
437
438 if base == 0 {
439 base = 10 // Default to decimal for maps if no prefix
440 }
441
442 numValue, err := strconv.ParseInt(number, base, valueType.Bits())
443 if err != nil {
444 return reflect.Value{}, fmt.Errorf("%w: %w", ErrParseIntFailed, err)
445 }
446
447 switch valueType.Kind() {
448 case reflect.Int:
449 bits := valueType.Bits()
450 if bits == Int32BitSize {
451 if numValue < math.MinInt32 || numValue > math.MaxInt32 {
452 return reflect.Value{}, fmt.Errorf(
453 "%w: value %d exceeds int%d range",
454 ErrParseIntFailed,
455 numValue,
456 bits,
457 )
458 }
459 }
460
461 return reflect.ValueOf(int(numValue)), nil
462 case reflect.Int8:
463 if numValue < math.MinInt8 || numValue > math.MaxInt8 {
464 return reflect.Value{}, fmt.Errorf(
465 "%w: value %d exceeds int8 range",
466 ErrParseIntFailed,
467 numValue,
468 )
469 }
470
471 return reflect.ValueOf(int8(numValue)), nil
472 case reflect.Int16:
473 if numValue < math.MinInt16 || numValue > math.MaxInt16 {
474 return reflect.Value{}, fmt.Errorf(
475 "%w: value %d exceeds int16 range",
476 ErrParseIntFailed,
477 numValue,
478 )
479 }
480
481 return reflect.ValueOf(int16(numValue)), nil
482 case reflect.Int32:
483 if numValue < math.MinInt32 || numValue > math.MaxInt32 {
484 return reflect.Value{}, fmt.Errorf(
485 "%w: value %d exceeds int32 range",
486 ErrParseIntFailed,
487 numValue,
488 )
489 }
490
491 return reflect.ValueOf(int32(numValue)), nil
492 case reflect.Int64:
493 return reflect.ValueOf(numValue), nil
494 case reflect.Invalid,
495 reflect.Bool,
496 reflect.Uint,
497 reflect.Uint8,
498 reflect.Uint16,
499 reflect.Uint32,
500 reflect.Uint64,
501 reflect.Uintptr,
502 reflect.Float32,
503 reflect.Float64,
504 reflect.Complex64,
505 reflect.Complex128,
506 reflect.Array,
507 reflect.Chan,
508 reflect.Func,
509 reflect.Interface,
510 reflect.Map,
511 reflect.Pointer,
512 reflect.Slice,
513 reflect.String,
514 reflect.Struct,
515 reflect.UnsafePointer:
516 return reflect.Value{}, ErrUnexpectedIntKind
517 default:
518 return reflect.Value{}, ErrUnexpectedIntKind
519 }
520 }
521
522 // GetConfigFieldString converts a config field value to its string representation.
523 func GetConfigFieldString(config reflect.Value, field *FieldInfo) (string, error) {
524 configField := config.FieldByName(field.Name)
525 if field.IsEnum() {
526 return field.EnumFormatter.Print(int(configField.Int())), nil
527 }
528
529 strVal, token := getValueNodeValue(configField, field)
530 if token == ErrorToken {
531 return "", ErrInvalidFieldValueData
532 }
533
534 return strVal, nil
535 }