From 1505cae05de98bcd399698d6461d15d88dc33d71 Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Thu, 15 Sep 2011 17:04:51 -0400 Subject: [PATCH] flag: make zero FlagSet useful This makes it possible to use a FlagSet as a field in a larger struct. R=golang-dev, r CC=golang-dev https://golang.org/cl/5036041 --- src/pkg/flag/flag.go | 22 +++++++++++++++++++--- src/pkg/flag/flag_test.go | 3 ++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/pkg/flag/flag.go b/src/pkg/flag/flag.go index 38b65d1a1eb..f13f7a45cd3 100644 --- a/src/pkg/flag/flag.go +++ b/src/pkg/flag/flag.go @@ -286,6 +286,9 @@ func (f *FlagSet) Set(name, value string) bool { if !ok { return false } + if f.actual == nil { + f.actual = make(map[string]*Flag) + } f.actual[name] = flag return true } @@ -559,6 +562,9 @@ func (f *FlagSet) Var(value Value, name string, usage string) { fmt.Fprintf(os.Stderr, "%s flag redefined: %s\n", f.name, name) panic("flag redefinition") // Happens only if flags are declared with identical names } + if f.formal == nil { + f.formal = make(map[string]*Flag) + } f.formal[name] = flag } @@ -586,6 +592,8 @@ func (f *FlagSet) failf(format string, a ...interface{}) os.Error { func (f *FlagSet) usage() { if f == commandLine { Usage() + } else if f.Usage == nil { + defaultUsage(f) } else { f.Usage() } @@ -657,6 +665,9 @@ func (f *FlagSet) parseOne() (bool, os.Error) { return false, f.failf("invalid value %q for flag: -%s", value, name) } } + if f.actual == nil { + f.actual = make(map[string]*Flag) + } f.actual[name] = flag return true, nil } @@ -713,10 +724,15 @@ var commandLine = NewFlagSet(os.Args[0], ExitOnError) func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { f := &FlagSet{ name: name, - actual: make(map[string]*Flag), - formal: make(map[string]*Flag), errorHandling: errorHandling, } - f.Usage = func() { defaultUsage(f) } return f } + +// Init sets the name and error handling property for a flag set. +// By default, the zero FlagSet uses an empty name and the +// ContinueOnError error handling policy. +func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { + f.name = name + f.errorHandling = errorHandling +} diff --git a/src/pkg/flag/flag_test.go b/src/pkg/flag/flag_test.go index 19c0deaf5c9..f13531669c1 100644 --- a/src/pkg/flag/flag_test.go +++ b/src/pkg/flag/flag_test.go @@ -180,7 +180,8 @@ func (f *flagVar) Set(value string) bool { } func TestUserDefined(t *testing.T) { - flags := NewFlagSet("test", ContinueOnError) + var flags FlagSet + flags.Init("test", ContinueOnError) var v flagVar flags.Var(&v, "v", "usage") if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil {