Skip to content
Myr

Merge pull request #84 from eparis/subcommand-invalid-flag

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Stop special casing runnable root commands

authored by Eric Paris · committed by Eric Paris · parents 09b49c3, bd0f8a8 · Browse files · 2 files+89 added−51 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+89 added−51 removed

  • other:+89 added−51 removed

2 files+89 added−51 removed

modified:cobra_test.go+83 added-2 removed
1 unmodified line
23import (4 "bytes"5 "fmt"6 "os"7 "strings"8 "testing"9)1011var _ = fmt.Println12var _ = os.Stderr1314var tp, te, tt, t1 []string15var flagb1, flagb2, flagb3, flagbr, flagbp bool16var flags1, flags2a, flags2b, flags3 string
6 unmodified lines
2324var cmdPrint = &Command{25 Use: "print [string to print]",26 Short: "Print anything to the screen",25 Long: `an utterly useless command for testing.`,27 Long: `an absolutely utterly useless command for testing.`,28 Run: func(cmd *Command, args []string) {29 tp = args30 },31}
10 unmodified lines
4243var cmdTimes = &Command{44 Use: "times [# times] [string to echo]",45 Short: "Echo anything to the screen more times",44 Long: `an slightly useless command for testing.`,46 Long: `a slightly useless command for testing.`,47 Run: func(cmd *Command, args []string) {48 tt = args49 },50}
367 unmodified lines
418 t.Errorf("invalid flag should generate error")419 }420}421422func TestInvalidSubCommandFlags(t *testing.T) {423 cmd := initializeWithRootCmd()424 cmd.AddCommand(cmdTimes)425426 result := simpleTester(cmd, "times --inttwo=2 --badflag=bar")427428 checkResultContains(t, result, "unknown flag: --badflag")429430 if strings.Contains(result.Output, "unknown flag: --inttwo") {431 t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag")432 }433434}435436func TestPersistentFlags(t *testing.T) {437 fullSetupTest("echo -s something -p more here")438439 // persistentFlag should act like normal flag on it's own command
48 unmodified lines
488 t.Errorf("Root Function was not called")489 }490}491492func TestRunnableRootCommandNilInput(t *testing.T) {493 empty_arg := make([]string, 0)494 c := initializeWithRootCmd()495496 buf := new(bytes.Buffer)497 // Testing flag with invalid input498 c.SetOutput(buf)499 cmdEcho.AddCommand(cmdTimes)500 c.AddCommand(cmdPrint, cmdEcho)501 c.SetArgs(empty_arg)502503 c.Execute()504505 if rootcalled != true {506 t.Errorf("Root Function was not called")507 }508}509510func TestRunnableRootCommandEmptyInput(t *testing.T) {511 args := make([]string, 3)512 args[0] = ""513 args[1] = "--introot=12"514 args[2] = ""515 c := initializeWithRootCmd()516517 buf := new(bytes.Buffer)518 // Testing flag with invalid input519 c.SetOutput(buf)520 cmdEcho.AddCommand(cmdTimes)521 c.AddCommand(cmdPrint, cmdEcho)522 c.SetArgs(args)523524 c.Execute()525526 if rootcalled != true {527 t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf)528 }529}530531func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {532 fullSetupTest("echo invalid-sub")533534 if te[0] != "invalid-sub" {535 t.Errorf("Subcommand didn't work...")536 }537}538539func TestRootFlags(t *testing.T) {540 fullSetupTest("-i 17 -b")541542 if flagbr != true {
53 unmodified lines
596597 }598}599600func TestNoNRunnableRootCommandNilInput(t *testing.T) {601 args := make([]string, 0)602 c := initialize()603604 buf := new(bytes.Buffer)605 // Testing flag with invalid input606 c.SetOutput(buf)607 cmdEcho.AddCommand(cmdTimes)608 c.AddCommand(cmdPrint, cmdEcho)609 c.SetArgs(args)610611 c.Execute()612613 if !strings.Contains(buf.String(), cmdRootNoRun.Long) {614 t.Errorf("Expected to get help output, Got: \n %s", buf)615 }616}617618func TestRootNoCommandHelp(t *testing.T) {619 x := rootOnlySetupTest("--help")620621 checkResultOmits(t, x, "Available Commands:")
78 unmodified lines
modified:command.go+6 added-49 removed
303 unmodified lines
304 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):305 inFlag = true306 case inFlag:307 inFlag = false308 case y == "":309 // strip empty commands, as the go tests expect this to be ok....310 case !strings.HasPrefix(y, "-"):311 commands = append(commands, y)312 inFlag = false313 }
62 unmodified lines
376 }377378 commandFound, a := innerfind(c, arrs)379378 // if commander returned and the first argument (if it exists) doesn't379 // match the command name, return nil & error380 if commandFound.Name() == c.Name() && len(arrs[0]) > 0 && commandFound.Name() != arrs[0] {380 // If we matched on the root, but we asked for a subcommand, return an error381 if commandFound.Name() == c.Name() && len(stripFlags(arrs, c)) > 0 && commandFound.Name() != arrs[0] {382 return nil, a, fmt.Errorf("unknown command %q", a[0])383 }384385 return commandFound, a, nil
12 unmodified lines
398399 return findRoot(c)400}401401// execute the command determined by args and the command tree402func (c *Command) findAndExecute(args []string) (err error) {403404 cmd, a, e := c.Find(args)405 if e != nil {406 return e407 }408 return cmd.execute(a)409}410402func (c *Command) execute(a []string) (err error) {403 if c == nil {404 return fmt.Errorf("Called Execute() on a nil Command")405 }
78 unmodified lines
484 } else {485 c.Help()486 }487 } else {497 err = c.findAndExecute(args)498 }499500 // Now handle the case where the root is runnable and only flags are provided501 if err != nil && c.Runnable() {502 // This is pretty much a custom version of the *Command.execute method503 // with a few differences because it's the final command (no fall back)504 e := c.ParseFlags(args)488 cmd, flags, e := c.Find(args)489 if e != nil {506 // Flags parsing had an error.507 // If an error happens here, we have to report it to the user508 c.Println(e.Error())509 // If an error happens search also for subcommand info about that510 if c.cmdErrorBuf != nil && c.cmdErrorBuf.Len() > 0 {511 c.Println(c.cmdErrorBuf.String())512 } else {513 c.Usage()514 }490 err = e516 return491 } else {518 // If help is called, regardless of other flags, we print that519 if c.helpFlagVal {520 c.Help()521 return nil522 }523524 argWoFlags := c.Flags().Args()525 if len(argWoFlags) > 0 {526 // If there are arguments (not flags) one of the earlier527 // cases should have caught it.. It means invalid usage528 // print the usage529 c.Usage()530 } else {531 // Only flags left... Call root.Run532 c.preRun()533 c.Run(c, argWoFlags)534 err = nil535 }492 err = cmd.execute(flags)493 }494 }495496 if err != nil {
419 unmodified lines