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
Provenance
- Commit
29e27b1- Tree
8cdb8de- Author
Eric Paris <eparis@redhat.com>- Committer
Eric Paris <eparis@redhat.com>- Parent 1
09b49c3- Parent 2
bd0f8a8
2 files changed+89 added−51 removed
modified:cobra_test.go+83 added-2 removed
1 unmodified line2 3 import (4 "bytes"5 "fmt"6+ "os"7 "strings"8 "testing"9 )10 11 var _ = fmt.Println12+var _ = os.Stderr13 14 var tp, te, tt, t1 []string15 var flagb1, flagb2, flagb3, flagbr, flagbp bool16 var flags1, flags2a, flags2b, flags3 string6 unmodified lines23 24 var 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 lines42 43 var 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 lines418 t.Errorf("invalid flag should generate error")419 }420 }421 422+func TestInvalidSubCommandFlags(t *testing.T) {423+ cmd := initializeWithRootCmd()424+ cmd.AddCommand(cmdTimes)425+426+ result := simpleTester(cmd, "times --inttwo=2 --badflag=bar")427+428+ checkResultContains(t, result, "unknown flag: --badflag")429+430+ if strings.Contains(result.Output, "unknown flag: --inttwo") {431+ t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag")432+ }433+434+}435+436 func TestPersistentFlags(t *testing.T) {437 fullSetupTest("echo -s something -p more here")438 439 // persistentFlag should act like normal flag on it's own command48 unmodified lines488 t.Errorf("Root Function was not called")489 }490 }491 492+func TestRunnableRootCommandNilInput(t *testing.T) {493+ empty_arg := make([]string, 0)494+ c := initializeWithRootCmd()495+496+ 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)502+503+ c.Execute()504+505+ if rootcalled != true {506+ t.Errorf("Root Function was not called")507+ }508+}509+510+func TestRunnableRootCommandEmptyInput(t *testing.T) {511+ args := make([]string, 3)512+ args[0] = ""513+ args[1] = "--introot=12"514+ args[2] = ""515+ c := initializeWithRootCmd()516+517+ 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)523+524+ c.Execute()525+526+ if rootcalled != true {527+ t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf)528+ }529+}530+531+func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {532+ fullSetupTest("echo invalid-sub")533+534+ if te[0] != "invalid-sub" {535+ t.Errorf("Subcommand didn't work...")536+ }537+}538+539 func TestRootFlags(t *testing.T) {540 fullSetupTest("-i 17 -b")541 542 if flagbr != true {53 unmodified lines596 597 }598 }599 600+func TestNoNRunnableRootCommandNilInput(t *testing.T) {601+ args := make([]string, 0)602+ c := initialize()603+604+ 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)610+611+ c.Execute()612+613+ if !strings.Contains(buf.String(), cmdRootNoRun.Long) {614+ t.Errorf("Expected to get help output, Got: \n %s", buf)615+ }616+}617+618 func TestRootNoCommandHelp(t *testing.T) {619 x := rootOnlySetupTest("--help")620 621 checkResultOmits(t, x, "Available Commands:")78 unmodified linesmodified:command.go+6 added-49 removed
303 unmodified lines304 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 lines376 }377 378 commandFound, a := innerfind(c, arrs)379 378- // 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 }384 385 return commandFound, a, nil12 unmodified lines398 399 return findRoot(c)400 }401 401-// execute the command determined by args and the command tree402-func (c *Command) findAndExecute(args []string) (err error) {403-404- cmd, a, e := c.Find(args)405- if e != nil {406- return e407- }408- return cmd.execute(a)409-}410-402 func (c *Command) execute(a []string) (err error) {403 if c == nil {404 return fmt.Errorf("Called Execute() on a nil Command")405 }78 unmodified lines484 } else {485 c.Help()486 }487 } else {497- err = c.findAndExecute(args)498- }499-500- // 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- }523-524- 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 }495 496 if err != nil {419 unmodified lines