| 1 |
package format |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"reflect" |
| 7 |
|
| 8 |
"github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 9 |
) |
| 10 |
|
| 11 |
var ErrNotConfigProp = errors.New("struct field cannot be used as a prop") |
| 12 |
|
| 13 |
// GetConfigPropFromString deserializes a config property from a string representation using the ConfigProp interface. |
| 14 |
func GetConfigPropFromString(structType reflect.Type, value string) (reflect.Value, error) { |
| 15 |
valuePtr := reflect.New(structType) |
| 16 |
|
| 17 |
configProp, ok := valuePtr.Interface().(types.ConfigProp) |
| 18 |
if !ok { |
| 19 |
return reflect.Value{}, ErrNotConfigProp |
| 20 |
} |
| 21 |
|
| 22 |
if err := configProp.SetFromProp(value); err != nil { |
| 23 |
return reflect.Value{}, fmt.Errorf("failed to set config prop from string: %w", err) |
| 24 |
} |
| 25 |
|
| 26 |
return valuePtr, nil |
| 27 |
} |
| 28 |
|
| 29 |
// GetConfigPropString serializes a config property to a string representation using the ConfigProp interface. |
| 30 |
func GetConfigPropString(propPtr reflect.Value) (string, error) { |
| 31 |
if propPtr.Kind() != reflect.Pointer { |
| 32 |
propVal := propPtr |
| 33 |
propPtr = reflect.New(propVal.Type()) |
| 34 |
propPtr.Elem().Set(propVal) |
| 35 |
} |
| 36 |
|
| 37 |
if propPtr.CanInterface() { |
| 38 |
if configProp, ok := propPtr.Interface().(types.ConfigProp); ok { |
| 39 |
s, err := configProp.GetPropValue() |
| 40 |
if err != nil { |
| 41 |
return "", fmt.Errorf("failed to get config prop string: %w", err) |
| 42 |
} |
| 43 |
|
| 44 |
return s, nil |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
return "", ErrNotConfigProp |
| 49 |
} |