From b1a42b8a49ad63f8cdd199b64f81b1e0e44d18e2 Mon Sep 17 00:00:00 2001 From: Peter Ebden Date: Sun, 24 Feb 2019 19:41:40 +0000 Subject: [PATCH 1/2] Add ability to programmatically add options to a group --- group.go | 7 +++++++ group_test.go | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/group.go b/group.go index ec909e5..544e538 100644 --- a/group.go +++ b/group.go @@ -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, value reflect.Value) { + option.value = value + 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 diff --git a/group_test.go b/group_test.go index 18cd6c1..5673f26 100644 --- a/group_test.go +++ b/group_test.go @@ -1,6 +1,7 @@ package flags import ( + "reflect" "testing" ) @@ -253,3 +254,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", + }, reflect.ValueOf(&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") + } +} From 2442d95fb2f201050bd2bd4ab06ac2869dbd4b7c Mon Sep 17 00:00:00 2001 From: Peter Ebden Date: Sun, 24 Feb 2019 19:46:04 +0000 Subject: [PATCH 2/2] use an interface{} instead of reflect.Value --- group.go | 4 ++-- group_test.go | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/group.go b/group.go index 544e538..181caab 100644 --- a/group.go +++ b/group.go @@ -74,8 +74,8 @@ func (g *Group) AddGroup(shortDescription string, longDescription string, data i } // AddOption adds a new option to this group. -func (g *Group) AddOption(option *Option, value reflect.Value) { - option.value = value +func (g *Group) AddOption(option *Option, data interface{}) { + option.value = reflect.ValueOf(data) option.group = g g.options = append(g.options, option) } diff --git a/group_test.go b/group_test.go index 5673f26..409a7f2 100644 --- a/group_test.go +++ b/group_test.go @@ -1,7 +1,6 @@ package flags import ( - "reflect" "testing" ) @@ -262,7 +261,7 @@ func TestAddOptionNonOptional(t *testing.T) { p := NewParser(&opts, Default) p.AddOption(&Option{ LongName: "test", - }, reflect.ValueOf(&opts.Test)) + }, &opts.Test) _, err := p.ParseArgs([]string{"--test"}) if err != nil { t.Errorf("unexpected error: %s", err)