Skip to content

Commit

Permalink
flag: allow CommandLine's Usage function to be set
Browse files Browse the repository at this point in the history
Fixes golang#7779.

LGTM=rsc
R=golang-codereviews, rsc
CC=golang-codereviews
https://golang.org/cl/147210043
  • Loading branch information
robpike committed Sep 26, 2014
1 parent 1bf18b4 commit b2487ef
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/flag/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down Expand Up @@ -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()
}
Expand Down
10 changes: 10 additions & 0 deletions src/flag/flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit b2487ef

Please sign in to comment.