From d4c2b35b2ef5b67c3ec6f904cea0dff806d51e2c Mon Sep 17 00:00:00 2001 From: Kenneth Shaw Date: Fri, 3 Mar 2017 19:12:17 +0700 Subject: Adding separate tag option As outlined in #49, there is a need to mimic the behavior of other applications by interweaving positional and non-positional parameters. This change adds the 'separate' option that will force a arg of type []string to only read the next supplied value. For example, when dealing with the following arg type: var MyArgs struct { Pos []string `arg:"positional"` Separate []string `arg:"-s,separate"` } This commit will parse the following command line: ./app pos1 pos2 -s=separate1 -s=separate2 pos3 -s=separate3 pos4 Such that MyArgs.Pos will be [pos1 pos2 pos3 pos4] and MyArgs.Separate will be [separate1 separate2 separate3]. Unit tests for the above have also been written and are included in this commit, as well as the addition of a section to README.md and an example func in example_test.go. Fixes #49 --- parse_test.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) (limited to 'parse_test.go') diff --git a/parse_test.go b/parse_test.go index 91e17bb..267e57c 100644 --- a/parse_test.go +++ b/parse_test.go @@ -739,3 +739,57 @@ func TestHyphenInMultiPositional(t *testing.T) { require.NoError(t, err) assert.Equal(t, []string{"---", "x", "-", "y"}, args.Foo) } + +func TestSeparate(t *testing.T) { + for _, val := range []string{"-f one", "-f=one", "--foo one", "--foo=one"} { + var args struct { + Foo []string `arg:"--foo,-f,separate"` + } + + err := parse(val, &args) + require.NoError(t, err) + assert.Equal(t, []string{"one"}, args.Foo) + } +} + +func TestSeparateWithDefault(t *testing.T) { + args := struct { + Foo []string `arg:"--foo,-f,separate"` + }{ + Foo: []string{"default"}, + } + + err := parse("-f one -f=two", &args) + require.NoError(t, err) + assert.Equal(t, []string{"default", "one", "two"}, args.Foo) +} + +func TestSeparateWithPositional(t *testing.T) { + var args struct { + Foo []string `arg:"--foo,-f,separate"` + Bar string `arg:"positional"` + Moo string `arg:"positional"` + } + + err := parse("zzz --foo one -f=two --foo=three -f four aaa", &args) + require.NoError(t, err) + assert.Equal(t, []string{"one", "two", "three", "four"}, args.Foo) + assert.Equal(t, "zzz", args.Bar) + assert.Equal(t, "aaa", args.Moo) +} + +func TestSeparatePositionalInterweaved(t *testing.T) { + var args struct { + Foo []string `arg:"--foo,-f,separate"` + Bar []string `arg:"--bar,-b,separate"` + Pre string `arg:"positional"` + Post []string `arg:"positional"` + } + + err := parse("zzz -f foo1 -b=bar1 --foo=foo2 -b bar2 post1 -b bar3 post2 post3", &args) + require.NoError(t, err) + assert.Equal(t, []string{"foo1", "foo2"}, args.Foo) + assert.Equal(t, []string{"bar1", "bar2", "bar3"}, args.Bar) + assert.Equal(t, "zzz", args.Pre) + assert.Equal(t, []string{"post1", "post2", "post3"}, args.Post) +} -- cgit v1.2.3