1
0
mirror of https://github.com/golang/go synced 2024-11-20 07:04:40 -07:00

allow user to override the Usage function

R=gri
DELTA=15  (6 added, 5 deleted, 4 changed)
OCL=31649
CL=31649
This commit is contained in:
Rob Pike 2009-07-14 17:44:20 -07:00
parent eb815c0fa2
commit ba9d697336

View File

@ -260,16 +260,11 @@ func PrintDefaults() {
}) })
} }
// Usage prints to standard error a default usage message documenting all defined flags and // Usage prints to standard error a default usage message documenting all defined flags.
// then calls os.Exit(1). // The function is a variable that may be changed to point to a custom function.
func Usage() { var Usage = func() {
if len(os.Args) > 0 {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]); fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]);
} else {
fmt.Fprintln(os.Stderr, "Usage:");
}
PrintDefaults(); PrintDefaults();
os.Exit(1);
} }
func NFlag() int { func NFlag() int {
@ -415,6 +410,7 @@ func (f *allFlags) parseOne(index int) (ok bool, next int)
if len(name) == 0 || name[0] == '-' || name[0] == '=' { if len(name) == 0 || name[0] == '-' || name[0] == '=' {
print("bad flag syntax: ", s, "\n"); print("bad flag syntax: ", s, "\n");
Usage(); Usage();
os.Exit(2);
} }
// it's a flag. does it have an argument? // it's a flag. does it have an argument?
@ -432,18 +428,21 @@ func (f *allFlags) parseOne(index int) (ok bool, next int)
if alreadythere { if alreadythere {
print("flag specified twice: -", name, "\n"); print("flag specified twice: -", name, "\n");
Usage(); Usage();
os.Exit(2);
} }
m := flags.formal; m := flags.formal;
flag, alreadythere = m[name]; // BUG flag, alreadythere = m[name]; // BUG
if !alreadythere { if !alreadythere {
print("flag provided but not defined: -", name, "\n"); print("flag provided but not defined: -", name, "\n");
Usage(); Usage();
os.Exit(2);
} }
if f, ok := flag.Value.(*boolValue); ok { // special case: doesn't need an arg if f, ok := flag.Value.(*boolValue); ok { // special case: doesn't need an arg
if has_value { if has_value {
if !f.set(value) { if !f.set(value) {
print("invalid boolean value ", value, " for flag: -", name, "\n"); print("invalid boolean value ", value, " for flag: -", name, "\n");
Usage(); Usage();
os.Exit(2);
} }
} else { } else {
f.set("true") f.set("true")
@ -459,11 +458,13 @@ func (f *allFlags) parseOne(index int) (ok bool, next int)
if !has_value { if !has_value {
print("flag needs an argument: -", name, "\n"); print("flag needs an argument: -", name, "\n");
Usage(); Usage();
os.Exit(2);
} }
ok = flag.Value.set(value); ok = flag.Value.set(value);
if !ok { if !ok {
print("invalid value ", value, " for flag: -", name, "\n"); print("invalid value ", value, " for flag: -", name, "\n");
Usage(); Usage();
os.Exit(2);
} }
} }
flags.actual[name] = flag; flags.actual[name] = flag;