Skip to content

Commit

Permalink
Merge pull request #300 from peterebden/dynamically-add-options
Browse files Browse the repository at this point in the history
 Add ability to programmatically add options to a group
  • Loading branch information
jessevdk authored Jul 11, 2020
2 parents 28ec126 + 2442d95 commit 5ec36f8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
7 changes: 7 additions & 0 deletions group.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ func (g *Group) AddGroup(shortDescription string, longDescription string, data i
return group, nil
}

// AddOption adds a new option to this group.
func (g *Group) AddOption(option *Option, data interface{}) {
option.value = reflect.ValueOf(data)
option.group = g
g.options = append(g.options, option)
}

// Groups returns the list of groups embedded in this group.
func (g *Group) Groups() []*Group {
return g.groups
Expand Down
16 changes: 16 additions & 0 deletions group_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,19 @@ func TestFindOptionByShortFlagInSubGroup(t *testing.T) {
t.Errorf("Expected 't', but got %v", opt.ShortName)
}
}

func TestAddOptionNonOptional(t *testing.T) {
var opts struct {
Test bool
}
p := NewParser(&opts, Default)
p.AddOption(&Option{
LongName: "test",
}, &opts.Test)
_, err := p.ParseArgs([]string{"--test"})
if err != nil {
t.Errorf("unexpected error: %s", err)
} else if !opts.Test {
t.Errorf("option not set")
}
}

0 comments on commit 5ec36f8

Please sign in to comment.