Merge pull request #57 from fraenkel/optional
Allow to detect optional flags
This commit is contained in:
commit
1cb2291894
14
context.go
14
context.go
@ -15,11 +15,12 @@ type Context struct {
|
|||||||
App *App
|
App *App
|
||||||
flagSet *flag.FlagSet
|
flagSet *flag.FlagSet
|
||||||
globalSet *flag.FlagSet
|
globalSet *flag.FlagSet
|
||||||
|
setFlags map[string]bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Creates a new context. For use in when invoking an App or Command action.
|
// 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 {
|
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
|
// 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)
|
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
|
type Args []string
|
||||||
|
|
||||||
// Returns the command line arguments associated with the context.
|
// Returns the command line arguments associated with the context.
|
||||||
|
@ -45,3 +45,14 @@ func TestContext_Args(t *testing.T) {
|
|||||||
expect(t, len(c.Args()), 2)
|
expect(t, len(c.Args()), 2)
|
||||||
expect(t, c.Bool("myflag"), true)
|
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)
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user