Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to programmatically add options to a group #300

Merged
merged 2 commits into from
Jul 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
}
}