diff --git a/cmd/camput/camput_test.go b/cmd/camput/camput_test.go index 59dec6696..d7f8f567d 100644 --- a/cmd/camput/camput_test.go +++ b/cmd/camput/camput_test.go @@ -89,6 +89,23 @@ func TestUsageOnNoargs(t *testing.T) { } } +// TestCommandUsage tests that we output a command-specific usage message and return +// with a non-zero exit status. +func TestCommandUsage(t *testing.T) { + var e env + out, err, code := e.Run("attr") + if code != 1 { + t.Errorf("exit code = %d; want 1", code) + } + if len(out) != 0 { + t.Errorf("wanted nothing on stdout; got:\n%s", out) + } + sub := "Attr takes 3 args: " + if !bytes.Contains(err, []byte(sub)) { + t.Errorf("stderr doesn't contain substring %q. Got:\n%s", sub, err) + } +} + func TestUploadingChangingDirectory(t *testing.T) { // TODO(bradfitz): // $ mkdir /tmp/somedir diff --git a/pkg/cmdmain/cmdmain.go b/pkg/cmdmain/cmdmain.go index e7b36c73b..0fabd9872 100644 --- a/pkg/cmdmain/cmdmain.go +++ b/pkg/cmdmain/cmdmain.go @@ -61,6 +61,7 @@ var ( // mode name to actual subcommand mapping modeCommand = make(map[string]CommandRunner) modeFlags = make(map[string]*flag.FlagSet) + wantHelp = make(map[string]*bool) // Indirections for replacement by tests Stderr io.Writer = os.Stderr @@ -100,6 +101,10 @@ func RegisterCommand(mode string, makeCmd func(Flags *flag.FlagSet) CommandRunne } flags := flag.NewFlagSet(mode+" options", flag.ContinueOnError) flags.Usage = func() {} + + var cmdHelp bool + flags.BoolVar(&cmdHelp, "help", false, "Help for this mode.") + wantHelp[mode] = &cmdHelp modeFlags[mode] = flags modeCommand[mode] = makeCmd(flags) } @@ -249,13 +254,11 @@ func Main() { cmdFlags := modeFlags[mode] cmdFlags.SetOutput(Stderr) - var cmdHelp bool - cmdFlags.BoolVar(&cmdHelp, "help", false, "Help for this mode.") err := cmdFlags.Parse(args[1:]) if err != nil { err = ErrUsage } else { - if cmdHelp { + if *wantHelp[mode] { help(mode) return }