mirror of
https://github.com/coder/coder.git
synced 2025-07-23 21:32:07 +00:00
fix(clibase): allow empty values to unset defaults (#6832)
This commit is contained in:
@ -293,11 +293,19 @@ func (i *Invocation) run(state *runState) error {
|
||||
return
|
||||
}
|
||||
|
||||
// If flag was changed, we need to remove the default values.
|
||||
sv, ok := f.Value.(pflag.SliceValue)
|
||||
if !ok {
|
||||
panic("defaulted array option is not a slice value")
|
||||
}
|
||||
err := sv.Replace(sv.GetSlice()[i:])
|
||||
ss := sv.GetSlice()
|
||||
if len(ss) == 0 {
|
||||
// Slice likely zeroed by a flag.
|
||||
// E.g. "--fruit" may default to "apples,oranges" but the user
|
||||
// provided "--fruit=""".
|
||||
return
|
||||
}
|
||||
err := sv.Replace(ss[i:])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
@ -503,3 +503,35 @@ func TestCommand_SliceFlags(t *testing.T) {
|
||||
err = cmd("bad", "bad", "bad").Invoke().Run()
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestCommand_EmptySlice(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := func(want ...string) *clibase.Cmd {
|
||||
var got []string
|
||||
return &clibase.Cmd{
|
||||
Use: "root",
|
||||
Options: clibase.OptionSet{
|
||||
{
|
||||
Name: "arr",
|
||||
Flag: "arr",
|
||||
Default: "bad,bad,bad",
|
||||
Env: "ARR",
|
||||
Value: clibase.StringArrayOf(&got),
|
||||
},
|
||||
},
|
||||
Handler: (func(i *clibase.Invocation) error {
|
||||
require.Equal(t, want, got)
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// Base-case
|
||||
err := cmd("bad", "bad", "bad").Invoke().Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
inv := cmd().Invoke("--arr", "")
|
||||
err = inv.Run()
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
@ -126,6 +126,9 @@ func (s *OptionSet) ParseEnv(vs []EnvVar) error {
|
||||
// way for a user to change a Default value to an empty string from
|
||||
// the environment. Unfortunately, we have old configuration files
|
||||
// that rely on the faulty behavior.
|
||||
//
|
||||
// TODO: We should remove this hack in May 2023, when deployments
|
||||
// have had months to migrate to the new behavior.
|
||||
if !ok || envVal == "" {
|
||||
continue
|
||||
}
|
||||
|
@ -146,6 +146,10 @@ func writeAsCSV(vals []string) string {
|
||||
}
|
||||
|
||||
func (s *StringArray) Set(v string) error {
|
||||
if v == "" {
|
||||
*s = nil
|
||||
return nil
|
||||
}
|
||||
ss, err := readAsCSV(v)
|
||||
if err != nil {
|
||||
return err
|
||||
|
Reference in New Issue
Block a user