]> Cypherpunks repositories - gostls13.git/commitdiff
flag: allow CommandLine's Usage function to be set
authorRob Pike <r@golang.org>
Fri, 26 Sep 2014 19:33:05 +0000 (12:33 -0700)
committerRob Pike <r@golang.org>
Fri, 26 Sep 2014 19:33:05 +0000 (12:33 -0700)
Fixes #7779.

LGTM=rsc
R=golang-codereviews, rsc
CC=golang-codereviews
https://golang.org/cl/147210043

src/flag/flag.go
src/flag/flag_test.go

index de2d91f8b1b12c5e154dab12718f8e7b599f23d7..323e452a832dea87f8dccc966212b0bd4b4b9a59 100644 (file)
@@ -406,6 +406,7 @@ func defaultUsage(f *FlagSet) {
 // for how to write your own usage function.
 
 // Usage prints to standard error a usage message documenting all defined command-line flags.
+// It is called when an error occurs while parsing flags.
 // The function is a variable that may be changed to point to a custom function.
 var Usage = func() {
        fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
@@ -702,13 +703,15 @@ func (f *FlagSet) failf(format string, a ...interface{}) error {
        return err
 }
 
-// usage calls the Usage method for the flag set, or the usage function if
-// the flag set is CommandLine.
+// usage calls the Usage method for the flag set if one is specified,
+// or the appropriate default usage function otherwise.
 func (f *FlagSet) usage() {
-       if f == CommandLine {
-               Usage()
-       } else if f.Usage == nil {
-               defaultUsage(f)
+       if f.Usage == nil {
+               if f == CommandLine {
+                       Usage()
+               } else {
+                       defaultUsage(f)
+               }
        } else {
                f.Usage()
        }
index 2c0387269791b3004db2f5bb9e31c9dc7556980c..8c88c8c2744371ff7e3a4e87f0ee7c7bb5e91010 100644 (file)
@@ -251,6 +251,16 @@ func TestUserDefined(t *testing.T) {
        }
 }
 
+func TestUserDefinedForCommandLine(t *testing.T) {
+       const help = "HELP"
+       var result string
+       ResetForTesting(func() { result = help })
+       Usage()
+       if result != help {
+               t.Fatalf("got %q; expected %q", result, help)
+       }
+}
+
 // Declare a user-defined boolean flag type.
 type boolFlagVar struct {
        count int