Skip to content

Commit 5ec36f8

Browse files
authored
Merge pull request #300 from peterebden/dynamically-add-options
Add ability to programmatically add options to a group
2 parents 28ec126 + 2442d95 commit 5ec36f8

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

group.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,13 @@ func (g *Group) AddGroup(shortDescription string, longDescription string, data i
7373
return group, nil
7474
}
7575

76+
// AddOption adds a new option to this group.
77+
func (g *Group) AddOption(option *Option, data interface{}) {
78+
option.value = reflect.ValueOf(data)
79+
option.group = g
80+
g.options = append(g.options, option)
81+
}
82+
7683
// Groups returns the list of groups embedded in this group.
7784
func (g *Group) Groups() []*Group {
7885
return g.groups

group_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,3 +253,19 @@ func TestFindOptionByShortFlagInSubGroup(t *testing.T) {
253253
t.Errorf("Expected 't', but got %v", opt.ShortName)
254254
}
255255
}
256+
257+
func TestAddOptionNonOptional(t *testing.T) {
258+
var opts struct {
259+
Test bool
260+
}
261+
p := NewParser(&opts, Default)
262+
p.AddOption(&Option{
263+
LongName: "test",
264+
}, &opts.Test)
265+
_, err := p.ParseArgs([]string{"--test"})
266+
if err != nil {
267+
t.Errorf("unexpected error: %s", err)
268+
} else if !opts.Test {
269+
t.Errorf("option not set")
270+
}
271+
}

0 commit comments

Comments
 (0)