Skip to content

Commit

Permalink
Honor NoTrimSpace field for flags from env
Browse files Browse the repository at this point in the history
This commits addresses the following comment:
#1649 (comment)

String slice flag values from environment now follows the same rules as
parsed values.
  • Loading branch information
palsivertsen committed Jan 31, 2023
1 parent 12b6187 commit d14954f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
5 changes: 4 additions & 1 deletion flag_string_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,10 @@ func (f *StringSliceFlag) Apply(set *flag.FlagSet) error {

if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found {
for _, s := range f.separator.flagSplitMultiValues(val) {
if err := setValue.Set(strings.TrimSpace(s)); err != nil {
if !f.NoTrimSpace {
s = strings.TrimSpace(s)
}
if err := setValue.Set(s); err != nil {
return fmt.Errorf("could not parse %q as string value from %s for flag %s: %s", val, source, f.Name, err)
}
}
Expand Down
7 changes: 7 additions & 0 deletions flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ func TestFlagsFromEnv(t *testing.T) {
s.hasBeenSet = false
return *s
}
newSetStringSliceNoTrimSpace := func(defaults ...string) StringSlice {
s := newSetStringSlice(defaults...)
s.noTrimSpace = true
return s
}

var flagTests = []struct {
input string
Expand Down Expand Up @@ -198,6 +203,8 @@ func TestFlagsFromEnv(t *testing.T) {
{"path", "path", &PathFlag{Name: "path", EnvVars: []string{"PATH"}}, ""},

{"foo,bar", newSetStringSlice("foo", "bar"), &StringSliceFlag{Name: "names", EnvVars: []string{"NAMES"}}, ""},
{" space ", newSetStringSliceNoTrimSpace(" space "), &StringSliceFlag{Name: "names", NoTrimSpace: true, EnvVars: []string{"NAMES"}}, ""},
{" no space ", newSetStringSlice("no space"), &StringSliceFlag{Name: "names", EnvVars: []string{"NAMES"}}, ""},

{"1", uint(1), &UintFlag{Name: "seconds", EnvVars: []string{"SECONDS"}}, ""},
{"08", uint(8), &UintFlag{Name: "seconds", EnvVars: []string{"SECONDS"}, Base: 10}, ""},
Expand Down

0 comments on commit d14954f

Please sign in to comment.