From 50fae88a843c0b6ae9962d23022bcf68340fd476 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 30 Jun 2026 23:14:41 +0000 Subject: [PATCH] Scope k3kcli viper env binding to K3KCLI_ prefix to fix flaky test-cli --- cli/cmds/root.go | 4 ++++ cli/cmds/root_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 cli/cmds/root_test.go diff --git a/cli/cmds/root.go b/cli/cmds/root.go index fbe4e6c6..97eb0921 100644 --- a/cli/cmds/root.go +++ b/cli/cmds/root.go @@ -92,6 +92,10 @@ func CobraFlagNamespace(appCtx *AppContext, flag *pflag.FlagSet) { } func InitializeConfig(cmd *cobra.Command) { + // Use a "K3KCLI" prefix so that only namespaced environment variables (e.g. + // K3KCLI_VERSION) bind to flags. Without a prefix, common environment variables + // such as VERSION, MODE or TOKEN would silently override the matching CLI flags. + viper.SetEnvPrefix("K3KCLI") viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) viper.AutomaticEnv() diff --git a/cli/cmds/root_test.go b/cli/cmds/root_test.go new file mode 100644 index 00000000..b4d8ee43 --- /dev/null +++ b/cli/cmds/root_test.go @@ -0,0 +1,43 @@ +package cmds + +import ( + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" +) + +func Test_InitializeConfig_envPrefix(t *testing.T) { + tests := []struct { + name string + envName string + want string + }{ + { + name: "unprefixed env does not bind to flag", + envName: "VERSION", + want: "", + }, + { + name: "prefixed env binds to flag", + envName: "K3KCLI_VERSION", + want: "1h", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + viper.Reset() + t.Setenv(tt.envName, "1h") + + var version string + cmd := &cobra.Command{Use: "create"} + cmd.Flags().StringVar(&version, "version", "", "k3s version") + + InitializeConfig(cmd) + + assert.Equal(t, tt.want, version) + }) + } +}