add ability to parse []string types

This commit is contained in:
Thesyncim 2013-09-24 02:41:31 +01:00
parent e8d8047f49
commit 4d9038a156
3 changed files with 54 additions and 8 deletions

View File

@ -1,9 +1,9 @@
package cli
import (
"os"
"fmt"
"io/ioutil"
"os"
"strings"
)
@ -12,7 +12,7 @@ type Command struct {
ShortName string
Usage string
Description string
Action func (context *Context)
Action func(context *Context)
Flags []Flag
}
@ -52,7 +52,6 @@ func (c Command) Run(ctx *Context) {
context := NewContext(ctx.App, set, ctx.globalSet)
checkCommandHelp(context, c.Name)
c.Action(context)
}

View File

@ -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 {

34
flag.go
View File

@ -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