Skip to content

Commit b1a42b8

Browse files
committed
Add ability to programmatically add options to a group
1 parent c0795c8 commit b1a42b8

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-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, value reflect.Value) {
78+
option.value = value
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: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package flags
22

33
import (
4+
"reflect"
45
"testing"
56
)
67

@@ -253,3 +254,19 @@ func TestFindOptionByShortFlagInSubGroup(t *testing.T) {
253254
t.Errorf("Expected 't', but got %v", opt.ShortName)
254255
}
255256
}
257+
258+
func TestAddOptionNonOptional(t *testing.T) {
259+
var opts struct {
260+
Test bool
261+
}
262+
p := NewParser(&opts, Default)
263+
p.AddOption(&Option{
264+
LongName: "test",
265+
}, reflect.ValueOf(&opts.Test))
266+
_, err := p.ParseArgs([]string{"--test"})
267+
if err != nil {
268+
t.Errorf("unexpected error: %s", err)
269+
} else if !opts.Test {
270+
t.Errorf("option not set")
271+
}
272+
}

0 commit comments

Comments
 (0)