config updated to improve setting values, writing changes and test coverage

This commit is contained in:
bwilliams committed 2026-10-13 13:19:01 +01:00
1 parent 8f0e72821f
commit 169c6c6b64
8 files changed
+453 -59

No files matched your search

+24 -13
View File
@@ -4,7 +4,9 @@ import (
"encoding/json"
"fmt"
"log/slog"
"maps"
"reflect"
"slices"
"strings"
"github.com/spf13/viper"
@@ -65,23 +67,31 @@ func LoadFromViper(conf *JobSearchConfig) {
if keyType == reflect.Invalid {
continue
}
var err error
switch keyType {
case reflect.String:
err = conf.SetValue(key, viper.GetString(key))
case reflect.Int:
err = conf.SetValue(key, viper.GetInt(key))
case reflect.Bool:
err = conf.SetValue(key, viper.GetBool(key))
default:
value, ok := viperValue(key, keyType)
if !ok {
slog.Error(fmt.Sprintf("unknown key type: %s", keyType))
continue
}
if err != nil {
if err := conf.SetValue(key, value); err != nil {
slog.Warn("ignoring invalid config value", "key", key, "err", err)
}
}
}
// viperValue reads key from Viper as a value of kind. ok is false for a kind
// LoadFromViper doesn't handle.
func viperValue(key string, kind reflect.Kind) (value any, ok bool) {
switch kind {
case reflect.String:
return viper.GetString(key), true
case reflect.Int:
return viper.GetInt(key), true
case reflect.Bool:
return viper.GetBool(key), true
}
return nil, false
}
// LoadToViper sets every key of conf as a Viper default.
func LoadToViper(conf JobSearchConfig) {
flatMap := conf.Flatten()
@@ -91,12 +101,13 @@ func LoadToViper(conf JobSearchConfig) {
}
// String formats the configuration one "key = value <type>" line per key, with
// dotted keys.
// dotted keys, sorted by key.
func (conf JobSearchConfig) String() string {
var sb strings.Builder
for k, v := range conf.Flatten() {
flat := conf.Flatten()
for _, k := range slices.Sorted(maps.Keys(flat)) {
typ, _ := conf.TypeOf(k)
fmt.Fprint(&sb, k, " = ", v, " <", typ, ">\n")
fmt.Fprint(&sb, k, " = ", flat[k], " <", typ, ">\n")
}
return sb.String()
}