Skip to content

Commit

Permalink
Ensure that prefix is separated from field name (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
wesdean authored Oct 8, 2021
1 parent 5a278be commit a200114
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
3 changes: 3 additions & 0 deletions flagset.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ func (f *FlagSetFiller) Fill(flagSet *flag.FlagSet, from interface{}) error {
func (f *FlagSetFiller) walkFields(flagSet *flag.FlagSet, prefix string,
structVal reflect.Value, structType reflect.Type) error {

if prefix != "" {
prefix += "-"
}
for i := 0; i < structVal.NumField(); i++ {
field := structType.Field(i)
fieldValue := structVal.Field(i)
Expand Down
12 changes: 8 additions & 4 deletions flagset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ func TestNestedFields(t *testing.T) {
SomeGrouping struct {
SomeField string
}
ALLCAPS struct {
ALLCAPS string
}
}

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

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

assert.Equal(t, "h1", config.Host)
assert.Equal(t, "val1", config.SomeGrouping.SomeField)
assert.Equal(t, "val2", config.ALLCAPS.ALLCAPS)
}

func TestNestedAdjacentFields(t *testing.T) {
Expand Down Expand Up @@ -695,17 +699,17 @@ func ExampleWithEnv() {
}

// simulate env variables from program invocation
os.Setenv("MY_APP_MULTI_WORD_NAME", "from env")
_ = os.Setenv("MY_APP_MULTI_WORD_NAME", "from env")

var config Config

// enable environment variable processing with given prefix
filler := flagsfiller.New(flagsfiller.WithEnv("MyApp"))
var flagset flag.FlagSet
filler.Fill(&flagset, &config)
_ = filler.Fill(&flagset, &config)

// simulate no args passed in
flagset.Parse([]string{})
_ = flagset.Parse([]string{})

fmt.Println(config.MultiWordName)
// Output:
Expand Down

0 comments on commit a200114

Please sign in to comment.