Skip to content

Commit a200114

Browse files
authored
Ensure that prefix is separated from field name (#5)
1 parent 5a278be commit a200114

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

flagset.go

+3
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ func (f *FlagSetFiller) Fill(flagSet *flag.FlagSet, from interface{}) error {
5858
func (f *FlagSetFiller) walkFields(flagSet *flag.FlagSet, prefix string,
5959
structVal reflect.Value, structType reflect.Type) error {
6060

61+
if prefix != "" {
62+
prefix += "-"
63+
}
6164
for i := 0; i < structVal.NumField(); i++ {
6265
field := structType.Field(i)
6366
fieldValue := structVal.Field(i)

flagset_test.go

+8-4
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@ func TestNestedFields(t *testing.T) {
8383
SomeGrouping struct {
8484
SomeField string
8585
}
86+
ALLCAPS struct {
87+
ALLCAPS string
88+
}
8689
}
8790

8891
var config Config
@@ -93,11 +96,12 @@ func TestNestedFields(t *testing.T) {
9396
err := filler.Fill(&flagset, &config)
9497
require.NoError(t, err)
9598

96-
err = flagset.Parse([]string{"--host", "h1", "--some-grouping-some-field", "val1"})
99+
err = flagset.Parse([]string{"--host", "h1", "--some-grouping-some-field", "val1", "--allcaps-allcaps", "val2"})
97100
require.NoError(t, err)
98101

99102
assert.Equal(t, "h1", config.Host)
100103
assert.Equal(t, "val1", config.SomeGrouping.SomeField)
104+
assert.Equal(t, "val2", config.ALLCAPS.ALLCAPS)
101105
}
102106

103107
func TestNestedAdjacentFields(t *testing.T) {
@@ -695,17 +699,17 @@ func ExampleWithEnv() {
695699
}
696700

697701
// simulate env variables from program invocation
698-
os.Setenv("MY_APP_MULTI_WORD_NAME", "from env")
702+
_ = os.Setenv("MY_APP_MULTI_WORD_NAME", "from env")
699703

700704
var config Config
701705

702706
// enable environment variable processing with given prefix
703707
filler := flagsfiller.New(flagsfiller.WithEnv("MyApp"))
704708
var flagset flag.FlagSet
705-
filler.Fill(&flagset, &config)
709+
_ = filler.Fill(&flagset, &config)
706710

707711
// simulate no args passed in
708-
flagset.Parse([]string{})
712+
_ = flagset.Parse([]string{})
709713

710714
fmt.Println(config.MultiWordName)
711715
// Output:

0 commit comments

Comments
 (0)