From 802f64479d6684c1735d975f519fbb8428479fd8 Mon Sep 17 00:00:00 2001 From: Omer Murat Yildirim Date: Sun, 21 Feb 2016 15:57:11 +0200 Subject: [PATCH] Add NArg method to context structure --- README.md | 6 +++--- context.go | 5 +++++ context_test.go | 8 ++++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ae0a4ca..5facb70 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ app.Flags = []cli.Flag { } app.Action = func(c *cli.Context) { name := "someone" - if len(c.Args()) > 0 { + if c.NArg() > 0 { name = c.Args()[0] } if c.String("lang") == "spanish" { @@ -180,7 +180,7 @@ app.Flags = []cli.Flag { } app.Action = func(c *cli.Context) { name := "someone" - if len(c.Args()) > 0 { + if c.NArg() > 0 { name = c.Args()[0] } if language == "spanish" { @@ -308,7 +308,7 @@ app.Commands = []cli.Command{ }, BashComplete: func(c *cli.Context) { // This will complete if no args are passed - if len(c.Args()) > 0 { + if c.NArg() > 0 { return } for _, t := range tasks { diff --git a/context.go b/context.go index 0513d34..b66d278 100644 --- a/context.go +++ b/context.go @@ -197,6 +197,11 @@ func (c *Context) Args() Args { return args } +// Returns the number of the command line arguments. +func (c *Context) NArg() int { + return len(c.Args()) +} + // Returns the nth argument, or else a blank string func (a Args) Get(n int) string { if len(a) > n { diff --git a/context_test.go b/context_test.go index 7f8e928..b8ab37d 100644 --- a/context_test.go +++ b/context_test.go @@ -64,6 +64,14 @@ func TestContext_Args(t *testing.T) { expect(t, c.Bool("myflag"), true) } +func TestContext_NArg(t *testing.T) { + set := flag.NewFlagSet("test", 0) + set.Bool("myflag", false, "doc") + c := NewContext(nil, set, nil) + set.Parse([]string{"--myflag", "bat", "baz"}) + expect(t, c.NArg(), 2) +} + func TestContext_IsSet(t *testing.T) { set := flag.NewFlagSet("test", 0) set.Bool("myflag", false, "doc")