From 9ce3b0b9b14653000d58ebdd93a1d2a9f448ac35 Mon Sep 17 00:00:00 2001 From: Tom Payne Date: Mon, 2 Dec 2024 01:14:32 +0000 Subject: [PATCH] fix: Fix error when choice variables are set in flags and config file --- internal/cmd/addcmd_test.go | 16 ++++++++++++++++ internal/cmd/choiceflag.go | 10 ++++++++++ internal/cmd/testdata/scripts/issue4104.txtar | 9 +++++++++ 3 files changed, 35 insertions(+) create mode 100644 internal/cmd/testdata/scripts/issue4104.txtar diff --git a/internal/cmd/addcmd_test.go b/internal/cmd/addcmd_test.go index 12c8e218263..b721e0f7752 100644 --- a/internal/cmd/addcmd_test.go +++ b/internal/cmd/addcmd_test.go @@ -292,3 +292,19 @@ func TestAddCmdSecretsError(t *testing.T) { assert.Error(t, newTestConfig(t, fileSystem).execute([]string{"add", "--secrets=error", "/home/user/.secret"})) }) } + +func TestIssue4107(t *testing.T) { + chezmoitest.WithTestFS(t, map[string]any{ + "/home/user": map[string]any{ + ".secret": "AWS_ACCESS_KEY_ID=AKIA0123456789ABCDEF\n", + ".config/chezmoi": map[string]any{ + "chezmoi.toml": chezmoitest.JoinLines( + `[add]`, + ` secrets = "error"`, + ), + }, + }, + }, func(fileSystem vfs.FS) { + assert.NoError(t, newTestConfig(t, fileSystem).execute([]string{"add", "--secrets=ignore", "/home/user/.secret"})) + }) +} diff --git a/internal/cmd/choiceflag.go b/internal/cmd/choiceflag.go index 97ba93e4166..f55fa5b0506 100644 --- a/internal/cmd/choiceflag.go +++ b/internal/cmd/choiceflag.go @@ -60,6 +60,16 @@ func (f *choiceFlag) MarshalText() ([]byte, error) { // Set implements github.com/spf13/pflag.Value.Set. func (f *choiceFlag) Set(s string) error { + // If uniqueAbbreviations is nil then all values are allowed. This + // functionality, although counter-intuitive, is required because the unique + // abbreviations are carried in the value, not in the type, so a + // serialization/deserialization round trip discards the unique + // abbreviations. To allow deserialization to succeed, we must allow all + // values. + if f.uniqueAbbreviations == nil { + f.value = s + return nil + } value, ok := f.uniqueAbbreviations[s] if !ok { return errors.New("invalid value") diff --git a/internal/cmd/testdata/scripts/issue4104.txtar b/internal/cmd/testdata/scripts/issue4104.txtar new file mode 100644 index 00000000000..1c41c3fe0ce --- /dev/null +++ b/internal/cmd/testdata/scripts/issue4104.txtar @@ -0,0 +1,9 @@ +# test that chezmoi add --secrets=ignore succeeds when the add.secrets config variable is set to error +exec chezmoi add --secrets=ignore $HOME${/}.secret +! stderr . + +-- home/user/.config/chezmoi/chezmoi.toml -- +[add] + secrets = "error" +-- home/user/.secret -- +AWS_ACCESS_KEY_ID=AKIA0123456789ABCDEF