From 4d9038a156af4f41d55e51685c91a8499882b832 Mon Sep 17 00:00:00 2001 From: Thesyncim Date: Tue, 24 Sep 2013 02:41:31 +0100 Subject: [PATCH] add ability to parse []string types --- command.go | 15 +++++++-------- context.go | 13 +++++++++++++ flag.go | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 8 deletions(-) diff --git a/command.go b/command.go index d1ca8e4..ce67258 100644 --- a/command.go +++ b/command.go @@ -1,19 +1,19 @@ package cli import ( - "os" "fmt" "io/ioutil" + "os" "strings" ) type Command struct { - Name string - ShortName string - Usage string - Description string - Action func (context *Context) - Flags []Flag + Name string + ShortName string + Usage string + Description string + Action func(context *Context) + Flags []Flag } func (c Command) Run(ctx *Context) { @@ -52,7 +52,6 @@ func (c Command) Run(ctx *Context) { context := NewContext(ctx.App, set, ctx.globalSet) checkCommandHelp(context, c.Name) - c.Action(context) } diff --git a/context.go b/context.go index 6e3867a..f7e88d8 100644 --- a/context.go +++ b/context.go @@ -34,6 +34,10 @@ func (c *Context) String(name string) string { return c.lookupString(name, c.flagSet) } +func (c *Context) StringSlice(name string) flag.Value { + return c.lookupStringSlice(name, c.flagSet) +} + // Looks up the value of a global int flag, returns 0 if no int flag exists func (c *Context) GlobalInt(name string) int { return c.lookupInt(name, c.globalSet) @@ -75,6 +79,15 @@ func (c *Context) lookupString(name string, set *flag.FlagSet) string { return "" } +func (c *Context) lookupStringSlice(name string, set *flag.FlagSet) flag.Value { + f := set.Lookup(name) + if f != nil { + return f.Value + } + + return nil +} + func (c *Context) lookupBool(name string, set *flag.FlagSet) bool { f := set.Lookup(name) if f != nil { diff --git a/flag.go b/flag.go index e37d2a0..fc8eb14 100644 --- a/flag.go +++ b/flag.go @@ -8,14 +8,48 @@ type Flag interface { Apply(*flag.FlagSet) } +type SliceFlag interface { + Value() []string +} + func flagSet(name string, flags []Flag) *flag.FlagSet { set := flag.NewFlagSet(name, flag.ContinueOnError) + for _, f := range flags { f.Apply(set) } return set } +type StringSlice []string + +func (i *StringSlice) Set(value string) error { + *i = append(*i, value) + return nil +} + +func (i *StringSlice) String() string { + return fmt.Sprintf("%s", *i) +} + +func (i *StringSlice) Value() []string { + return *i +} + +type StringSliceFlag struct { + Name string + Value *StringSlice + Usage string +} + +func (f StringSliceFlag) String() string { + return fmt.Sprintf("%s%v '%v'\t%v", prefixFor(f.Name), f.Name, "-"+f.Name+" option -"+f.Name+" option", f.Usage) +} + +func (f StringSliceFlag) Apply(set *flag.FlagSet) { + set.Var(f.Value, f.Name, f.Usage) +} + type BoolFlag struct { Name string Usage string