From 819190826ad33b0a55d9158b612a4c39a7dbad90 Mon Sep 17 00:00:00 2001 From: Pat Downey Date: Sat, 14 Nov 2026 23:51:42 +0000 Subject: [PATCH] fix: leave flags nobody set out of the decoded config Viper answers for every bound flag, so since flags were bound under their config keys a slice flag nobody set decoded as an empty slice, and a pointer block was allocated. Neither equals its zero value, so a check for whether a block is set, such as dioad/net's tls.ServerConfig.Check, saw every block as set and rejected configs that did not mention it. UnmarshalConfig now decodes an empty slice as nil and leaves out a pointer block whose values are all zero. A config that sets a block to nothing but zero values reads as not setting it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01SS4MAwAn85D1gkEzLtjYaZ --- config.go | 93 +++++++++++++++++++++++++++++++++++++++++++--- go.mod | 2 +- initconfig_test.go | 51 +++++++++++++++++++++++++ 3 files changed, 139 insertions(+), 7 deletions(-) diff --git a/config.go b/config.go index fa993cb..f788374 100644 --- a/config.go +++ b/config.go @@ -4,11 +4,14 @@ import ( "context" "errors" "fmt" + "maps" "os" "os/user" "path/filepath" + "reflect" "strings" + "github.com/go-viper/mapstructure/v2" "github.com/mitchellh/go-homedir" "github.com/rs/zerolog/log" "github.com/spf13/cobra" @@ -88,8 +91,7 @@ func InitViperConfigWithFlagSet(orgName, appName string, cfg any, parsedFlagSet err = viper.ReadInConfig() if err != nil { // Handle errors reading the config file - var configFileNotFoundError viper.ConfigFileNotFoundError - if !errors.As(err, &configFileNotFoundError) { + if _, ok := errors.AsType[viper.ConfigFileNotFoundError](err); !ok { return fmt.Errorf("fatal error reading config file: %w", err) } } @@ -230,8 +232,7 @@ func readConfigFile(v *viper.Viper) error { if err == nil { return nil } - var configFileNotFoundError viper.ConfigFileNotFoundError - if errors.As(err, &configFileNotFoundError) { + if _, ok := errors.AsType[viper.ConfigFileNotFoundError](err); ok { return nil } return fmt.Errorf("fatal error reading config file: %w", err) @@ -243,9 +244,89 @@ func readConfigFile(v *viper.Viper) error { // net.IP, and net.IPNet. This allows for seamless unmarshalling of complex configuration fields. // // The hook is configcheck.DecodeHook, so configcheck.Decode accepts exactly -// the values this function does. +// the values this function does, after unset flags have been dropped. func UnmarshalConfig(v *viper.Viper, c any) error { - return v.Unmarshal(c, viper.DecodeHook(configcheck.DecodeHook())) + hook := mapstructure.ComposeDecodeHookFunc(configcheck.DecodeHook(), dropUnset) + + return v.Unmarshal(c, viper.DecodeHook(hook)) +} + +// dropUnset keeps what viper answers for every bound flag, but did not get +// from the config, out of the decoded struct: a flag nobody set arrives as an +// empty slice, or as a block of zero values for a pointer field. Decoding +// those would leave an empty slice, or an allocated block, in a field the +// config never mentioned. Such a field differs from its zero value, and a check +// for whether it is set would see it as set. A config that sets a block to +// nothing but zero values reads as not setting it. +// +// It is composed last because a hook that returns nil leaves the ones after it +// nothing to convert. +func dropUnset(from, to reflect.Value) (any, error) { + switch { + case from.Kind() == reflect.Slice && to.Kind() == reflect.Slice && from.Len() == 0: + return nil, nil + case from.Kind() == reflect.Map && to.Kind() == reflect.Struct: + if m, ok := from.Interface().(map[string]any); ok { + return withoutUnsetBlocks(m, to.Type()), nil + } + } + + return from.Interface(), nil +} + +// withoutUnsetBlocks returns m without the entries for pointer-to-struct +// fields of t whose values are nothing but zero values. +func withoutUnsetBlocks(m map[string]any, t reflect.Type) map[string]any { + var out map[string]any + for field := range t.Fields() { + field := field + if field.Type.Kind() != reflect.Pointer || field.Type.Elem().Kind() != reflect.Struct { + continue + } + name, _, _ := strings.Cut(field.Tag.Get("mapstructure"), ",") + if name == "" { + name = field.Name + } + for key, value := range m { + if !strings.EqualFold(key, name) || !allZero(reflect.ValueOf(value)) { + continue + } + if out == nil { + out = maps.Clone(m) + } + delete(out, key) + } + } + if out == nil { + return m + } + + return out +} + +// allZero reports whether v holds nothing but zero values, empty slices and +// maps of the same. +func allZero(v reflect.Value) bool { + for v.Kind() == reflect.Interface { + v = v.Elem() + } + + switch v.Kind() { + case reflect.Map: + for _, key := range v.MapKeys() { + if !allZero(v.MapIndex(key)) { + return false + } + } + + return true + case reflect.Slice: + return v.Len() == 0 + case reflect.Invalid: + return true + default: + return v.IsZero() + } } // IsDocker detects if the application is running inside a Docker container. diff --git a/go.mod b/go.mod index e87950b..44b0ca8 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.26.0 require ( github.com/dioad/config v0.2.0 + github.com/go-viper/mapstructure/v2 v2.5.0 github.com/mitchellh/go-homedir v1.1.0 github.com/rs/zerolog v1.35.1 github.com/spf13/cobra v1.10.2 @@ -19,7 +20,6 @@ require ( github.com/dioad/generics v0.0.9 // indirect github.com/dioad/util v0.7.0 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect - github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/mattn/go-colorable v0.1.16 // indirect diff --git a/initconfig_test.go b/initconfig_test.go index 8c98ce3..39d086a 100644 --- a/initconfig_test.go +++ b/initconfig_test.go @@ -3,6 +3,7 @@ package cli_test import ( + "context" "os" "path/filepath" "runtime" @@ -248,3 +249,53 @@ func TestInitViperConfigWithFlagSet(t *testing.T) { "TESTAPP2_HOST should override the --host flag default") }) } + +// TestInitConfigLeavesUnsetBlocksNil pins that a slice flag nobody set decodes +// to a nil slice, and a pointer block no flag or config set stays nil. Viper +// answers for every bound flag, so without that an unset slice would decode +// empty and an unset block would be allocated, and neither would equal its +// zero value: a check for whether a block is set would see every block as set. +func TestInitConfigLeavesUnsetBlocksNil(t *testing.T) { + type block struct { + URL string `mapstructure:"url"` + Names []string `mapstructure:"names"` + } + type testConfig struct { + Block block `mapstructure:"block"` + Pointer *block `mapstructure:"pointer"` + } + + cfg := &testConfig{} + cmd := cli.NewCommand(&cobra.Command{Use: "testapp"}, func(context.Context, *testConfig) error { return nil }, cfg) + require.NoError(t, cmd.ParseFlags(nil)) + + // Generating the flags allocates the pointer in cfg, so decode into a fresh value. + got := &testConfig{} + _, err := cli.InitConfig("testorg", "testapp", cmd, got, cli.WithoutLogging()) + + require.NoError(t, err) + assert.Equal(t, testConfig{}, *got) +} + +// TestInitConfigKeepsABlockTheConfigSets pins that dropping unset blocks does +// not drop one the config file gives a value. +func TestInitConfigKeepsABlockTheConfigSets(t *testing.T) { + type block struct { + URL string `mapstructure:"url"` + Names []string `mapstructure:"names"` + } + type testConfig struct { + Pointer *block `mapstructure:"pointer"` + } + + cfg := &testConfig{} + cmd := cli.NewCommand(&cobra.Command{Use: "testapp"}, func(context.Context, *testConfig) error { return nil }, cfg) + cmd.Flags().String("config", writeYAML(t, "pointer:\n names: [a]\n"), "") + require.NoError(t, cmd.ParseFlags(nil)) + + got := &testConfig{} + _, err := cli.InitConfig("testorg", "testapp", cmd, got, cli.WithoutLogging()) + + require.NoError(t, err) + assert.Equal(t, &block{Names: []string{"a"}}, got.Pointer) +}