Commit b2487ef6 authored by Rob Pike's avatar Rob Pike

flag: allow CommandLine's Usage function to be set

Fixes #7779.

LGTM=rsc
R=golang-codereviews, rsc
CC=golang-codereviews
https://golang.org/cl/147210043
parent 1bf18b42
...@@ -406,6 +406,7 @@ func defaultUsage(f *FlagSet) { ...@@ -406,6 +406,7 @@ func defaultUsage(f *FlagSet) {
// for how to write your own usage function. // for how to write your own usage function.
// Usage prints to standard error a usage message documenting all defined command-line flags. // 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. // The function is a variable that may be changed to point to a custom function.
var Usage = func() { var Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
...@@ -702,13 +703,15 @@ func (f *FlagSet) failf(format string, a ...interface{}) error { ...@@ -702,13 +703,15 @@ func (f *FlagSet) failf(format string, a ...interface{}) error {
return err return err
} }
// usage calls the Usage method for the flag set, or the usage function if // usage calls the Usage method for the flag set if one is specified,
// the flag set is CommandLine. // or the appropriate default usage function otherwise.
func (f *FlagSet) usage() { func (f *FlagSet) usage() {
if f.Usage == nil {
if f == CommandLine { if f == CommandLine {
Usage() Usage()
} else if f.Usage == nil { } else {
defaultUsage(f) defaultUsage(f)
}
} else { } else {
f.Usage() f.Usage()
} }
......
...@@ -251,6 +251,16 @@ func TestUserDefined(t *testing.T) { ...@@ -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. // Declare a user-defined boolean flag type.
type boolFlagVar struct { type boolFlagVar struct {
count int count int
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment