Skip to content

Commit

Permalink
Support an array value in the config file (#303)
Browse files Browse the repository at this point in the history
  • Loading branch information
tksm committed May 7, 2024
1 parent dd6b763 commit 6afabde
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 0 deletions.
14 changes: 14 additions & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,20 @@ func (o *options) overrideFlagSetDefaultFromConfig(fs *pflag.FlagSet) error {
continue
}

if valueSlice, ok := value.([]any); ok {
// the value is an array
if flagSlice, ok := flag.Value.(pflag.SliceValue); ok {
values := make([]string, len(valueSlice))
for i, v := range valueSlice {
values[i] = fmt.Sprint(v)
}
if err := flagSlice.Replace(values); err != nil {
return fmt.Errorf("invalid value %q for %q in the config file: %v", value, name, err)
}
continue
}
}

if err := flag.Value.Set(fmt.Sprint(value)); err != nil {
return fmt.Errorf("invalid value %q for %q in the config file: %v", value, name, err)
}
Expand Down
43 changes: 43 additions & 0 deletions cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -920,3 +920,46 @@ func TestOptionsOverrideFlagSetDefaultFromConfig(t *testing.T) {
})
}
}

func TestOptionsOverrideFlagSetDefaultFromConfigArray(t *testing.T) {
tests := []struct {
config string
want []string
}{
{
config: "testdata/config-string.yaml",
want: []string{"hello-world"},
},
{
config: "testdata/config-array0.yaml",
want: []string{},
},
{
config: "testdata/config-array1.yaml",
want: []string{"abcd"},
},
{
config: "testdata/config-array2.yaml",
want: []string{"abcd", "efgh"},
},
}

for _, tt := range tests {
tt := tt
t.Run(tt.config, func(t *testing.T) {
o := NewOptions(genericclioptions.NewTestIOStreamsDiscard())
fs := pflag.NewFlagSet("", pflag.ExitOnError)
o.AddFlags(fs)
if err := fs.Parse([]string{"--config=" + tt.config}); err != nil {
t.Fatal(err)
}
if err := o.overrideFlagSetDefaultFromConfig(fs); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(tt.want, o.exclude) {
t.Errorf("expected %v, but got %v", tt.want, o.exclude)
}
})
}

}
1 change: 1 addition & 0 deletions cmd/testdata/config-array0.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exclude: []
1 change: 1 addition & 0 deletions cmd/testdata/config-array1.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exclude: ["abcd"]
1 change: 1 addition & 0 deletions cmd/testdata/config-array2.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exclude: ["abcd", "efgh"]
1 change: 1 addition & 0 deletions cmd/testdata/config-string.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exclude: "hello-world"

0 comments on commit 6afabde

Please sign in to comment.