flabk/pkg/ld/internal/parse/parse.go

74 lines
1.5 KiB
Go

package parse
import (
"fmt"
"reflect"
"strconv"
"strings"
"sectorinf.com/emilis/flabk/pkg/ld/internal/consts"
)
type LazyMapFunc func(name string, value string)
func GetMap(v any) LazyMapFunc {
val := reflect.ValueOf(v)
// typ := reflect.TypeOf(v)
switch val.Kind() {
case reflect.Map:
return func(name string, value string) {
// val.SetMapIndex(reflect.ValueOf(name), value)
}
case reflect.Struct:
// fields := GetStructFields(val, typ)
return func(name, value string) {
// val, ok := fields[name]
// if ok {
// val.Set(value)
// }
}
default:
panic("wrong")
}
}
func ParseAsValue(v string, valType reflect.Type) (any, error) {
// Might not be necessary to trim
v = strings.TrimSpace(v)
switch valType.Kind() {
case reflect.String:
return v[1 : len(v)-1], nil
case reflect.Bool:
b, err := strconv.ParseBool(strings.ToLower(v))
if err != nil {
fmt.Errorf("boolean: %w", err)
}
return b, nil
case reflect.Struct, reflect.Map:
panic("todo")
default:
panic("todo")
}
}
func GetStructFields(val reflect.Value, typ reflect.Type) map[string]reflect.Value {
total := val.NumField()
out := map[string]reflect.Value{}
for index := 0; index < total; index++ {
cName := StructName(typ.Field(index))
if cName != "-" {
out[cName] = val.Field(index)
}
}
return out
}
func StructName(v reflect.StructField) string {
tag := v.Tag.Get(consts.PkgTag)
if tag != "" {
return tag
}
// Default to field name
return v.Name
}