aboutsummaryrefslogtreecommitdiff
path: root/flag.go
diff options
context:
space:
mode:
authorEric Paris <[email protected]>2015-05-30 21:07:46 -0400
committerEric Paris <[email protected]>2015-06-01 18:45:34 -0400
commit1e0a23de9163cb0706137856f1d060f88e3f277c (patch)
treede398763dd538847a8c32d4073ce07d5fe8bb210 /flag.go
parent5644820622454e71517561946e3d94b9f9db6842 (diff)
Add new FlagSet.Get{Int,String,...} accessor functions
If I declared a bool flag named "hello" I can now call b, err := f.GetBool("hello") And b will hold the value of the flag We can see this is already done in https://github.com/codegangsta/cli/blob/bcec9b08c7e5564f7512ad7e7b03778fe1923116/context.go If people use the codegangsta/cli Other projects have done it themselves using pflags (what inspired this patch) https://github.com/GoogleCloudPlatform/kubernetes/blob/cd817aebd848facda29e0befbbd6e31bf22402e6/pkg/kubectl/cmd/util/helpers.go#L176 Lets just do it ourselves...
Diffstat (limited to 'flag.go')
-rw-r--r--flag.go21
1 files changed, 21 insertions, 0 deletions
diff --git a/flag.go b/flag.go
index 0070b93..534fce4 100644
--- a/flag.go
+++ b/flag.go
@@ -257,6 +257,27 @@ func (f *FlagSet) lookup(name NormalizedName) *Flag {
return f.formal[name]
}
+// func to return a given type for a given flag name
+func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {
+ flag := f.Lookup(name)
+ if flag == nil {
+ err := fmt.Errorf("flag accessed but not defined: %s\n", name)
+ return nil, err
+ }
+
+ if flag.Value.Type() != ftype {
+ err := fmt.Errorf("trying to get %s value of flag of type %s\n", ftype, flag.Value.Type())
+ return nil, err
+ }
+
+ sval := flag.Value.String()
+ result, err := convFunc(sval)
+ if err != nil {
+ return nil, err
+ }
+ return result, nil
+}
+
// Mark a flag deprecated in your program
func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
flag := f.Lookup(name)