Breaks out functions and adds some unit tests.

This commit is contained in:
2025-02-10 09:31:01 -06:00
parent bbd6299e53
commit 2ac8e37e17
3 changed files with 242 additions and 41 deletions

View File

@ -18,7 +18,7 @@ type structInfo struct {
Tags reflect.StructTag
Type reflect.Type
DefaultValue interface{}
Secret interface{}
Secret bool
}
func getEnv[t string | bool | int | int64 | float64](env string, def t) (t, error) {
@ -77,6 +77,10 @@ func getStructInfo(spec interface{}) ([]structInfo, error) {
}
typeOfSpec := s.Type()
return parseStructInfo(s, typeOfSpec)
}
func parseStructInfo(s reflect.Value, typeOfSpec reflect.Type) ([]structInfo, error) {
infos := make([]structInfo, 0, s.NumField())
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
@ -87,17 +91,7 @@ func getStructInfo(spec interface{}) ([]structInfo, error) {
continue
}
for f.Kind() == reflect.Pointer {
if f.IsNil() {
if f.Type().Elem().Kind() != reflect.Struct {
break
}
f.Set(reflect.New(f.Type().Elem()))
}
f = f.Elem()
}
secret, err := typeConversion(ftype.Type.String(), ftype.Tag.Get("secret"))
secret, err := strconv.ParseBool(ftype.Tag.Get("secret"))
if err != nil {
secret = false
}
@ -110,31 +104,41 @@ func getStructInfo(spec interface{}) ([]structInfo, error) {
}
info := structInfo{
Name: ftype.Name,
Alt: strings.ToUpper(ftype.Tag.Get("env")),
Info: desc,
Key: ftype.Name,
Field: f,
Tags: ftype.Tag,
Type: ftype.Type,
Secret: secret,
}
if info.Alt != "" {
info.Key = info.Alt
}
info.Key = strings.ToUpper(info.Key)
if ftype.Tag.Get("default") != "" {
v, err := typeConversion(ftype.Type.String(), ftype.Tag.Get("default"))
if err != nil {
return []structInfo{}, err
}
info.DefaultValue = v
Alt: strings.ToUpper(ftype.Tag.Get("env")),
DefaultValue: getDefault(ftype),
Field: f,
Info: desc,
Key: getAlt(ftype),
Name: ftype.Name,
Secret: secret,
Tags: ftype.Tag,
Type: ftype.Type,
}
infos = append(infos, info)
}
return infos, nil
}
func getAlt(ftype reflect.StructField) string {
if len(ftype.Tag.Get("env")) > 0 {
return strings.ToUpper(ftype.Tag.Get("env"))
}
return strings.ToUpper(ftype.Name)
}
func getDefault(ftype reflect.StructField) interface{} {
if ftype.Tag.Get("default") != "" {
v, err := typeConversion(ftype.Type.String(), ftype.Tag.Get("Default"))
if err != nil {
return nil
}
return v
}
return nil
}
func typeConversion(t, v string) (interface{}, error) {
switch t {
case "string": //nolint:goconst