Skip to content

Commit db7d18f

Browse files
authored
Merge pull request #2171 from dearchap/issue_2169
Fix:(issue_2169) Allow trim space for string slice flags
2 parents c185573 + 2f6400c commit db7d18f

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

command_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4311,6 +4311,9 @@ func TestCommandReadArgsFromStdIn(t *testing.T) {
43114311
},
43124312
&StringSliceFlag{
43134313
Name: "ssf",
4314+
Config: StringConfig{
4315+
TrimSpace: true,
4316+
},
43144317
},
43154318
}
43164319

flag_slice_base.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,21 @@ func (i *SliceBase[T, C, VC]) Set(value string) error {
4747
return nil
4848
}
4949

50+
trimSpace := true
51+
// hack. How do we know if we should trim spaces?
52+
// it makes sense only for string slice flags which have
53+
// an option to not trim spaces. So by default we trim spaces
54+
// otherwise we let the underlying value type handle it.
55+
var t T
56+
if reflect.TypeOf(t).Kind() == reflect.String {
57+
trimSpace = false
58+
}
59+
5060
for _, s := range flagSplitMultiValues(value) {
51-
if err := i.value.Set(strings.TrimSpace(s)); err != nil {
61+
if trimSpace {
62+
s = strings.TrimSpace(s)
63+
}
64+
if err := i.value.Set(s); err != nil {
5265
return err
5366
}
5467
*i.slice = append(*i.slice, i.value.Get().(T))

flag_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,12 @@ func TestFlagsFromEnv(t *testing.T) {
350350
output: []string{"foo", "bar"},
351351
fl: &StringSliceFlag{Name: "names", Sources: EnvVars("NAMES"), Config: StringConfig{TrimSpace: true}},
352352
},
353+
{
354+
name: "StringSliceFlag valid without TrimSpace",
355+
input: "foo , bar ",
356+
output: []string{"foo ", " bar "},
357+
fl: &StringSliceFlag{Name: "names", Sources: EnvVars("NAMES")},
358+
},
353359

354360
{
355361
name: "StringMapFlag valid",

0 commit comments

Comments
 (0)