From f88df0aa5aa5c12b29d33b8b938fc3f5c737bae3 Mon Sep 17 00:00:00 2001 From: fraenkel Date: Wed, 18 Dec 2013 12:09:16 -0600 Subject: [PATCH] Allow optional flags by asking if its been set/present on the command line --- context.go | 14 +++++++++++++- context_test.go | 11 +++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 08fa59a..d142442 100644 --- a/context.go +++ b/context.go @@ -15,11 +15,12 @@ type Context struct { App *App flagSet *flag.FlagSet globalSet *flag.FlagSet + setFlags map[string]bool } // Creates a new context. For use in when invoking an App or Command action. func NewContext(app *App, set *flag.FlagSet, globalSet *flag.FlagSet) *Context { - return &Context{app, set, globalSet} + return &Context{app, set, globalSet, nil} } // Looks up the value of a local int flag, returns 0 if no int flag exists @@ -77,6 +78,17 @@ func (c *Context) GlobalIntSlice(name string) []int { return lookupIntSlice(name, c.globalSet) } +// Determines if the flag was actually set exists +func (c *Context) IsSet(name string) bool { + if c.setFlags == nil { + c.setFlags = make(map[string]bool) + c.flagSet.Visit(func(f *flag.Flag) { + c.setFlags[f.Name] = true + }) + } + return c.setFlags[name] == true +} + type Args []string // Returns the command line arguments associated with the context. diff --git a/context_test.go b/context_test.go index cb3a551..63f2a70 100644 --- a/context_test.go +++ b/context_test.go @@ -45,3 +45,14 @@ func TestContext_Args(t *testing.T) { expect(t, len(c.Args()), 2) expect(t, c.Bool("myflag"), true) } + +func TestContext_IsSet(t *testing.T) { + set := flag.NewFlagSet("test", 0) + set.Bool("myflag", false, "doc") + set.String("otherflag", "hello world", "doc") + c := cli.NewContext(nil, set, set) + set.Parse([]string{"--myflag", "bat", "baz"}) + expect(t, c.IsSet("myflag"), true) + expect(t, c.IsSet("otherflag"), false) + expect(t, c.IsSet("bogusflag"), false) +}