Support for flags before commands
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by spf13 · committed by spf13 · parent 07be814 · Browse files · 3 files·+171 added−121 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+171 added−121 removed
- other:+171 added−121 removed
Provenance
- Commit
10a8494- Tree
3d870f2- Author
spf13 <steve.francia@gmail.com>- Committer
spf13 <steve.francia@gmail.com>- Parent
07be814
3 files changed+171 added−121 removed
modified:cobra_test.go+82 added-108 removed
166 unmodified lines167 }168 }169 170 func TestSingleCommand(t *testing.T) {171- c := initialize()172- c.AddCommand(cmdPrint, cmdEcho)173- c.SetArgs(strings.Split("print one two", " "))174- c.Execute()171+ noRRSetupTest("print one two")172 173 if te != nil || tt != nil {174 t.Error("Wrong command called")175 }5 unmodified lines181 }182 }183 184 func TestChildCommand(t *testing.T) {188- c := initialize()189- cmdEcho.AddCommand(cmdTimes)190- c.AddCommand(cmdPrint, cmdEcho)191- c.SetArgs(strings.Split("echo times one two", " "))192- c.Execute()185+ noRRSetupTest("echo times one two")186 187 if te != nil || tp != nil {188 t.Error("Wrong command called")189 }5 unmodified lines195 }196 }197 198 func TestChildCommandPrefix(t *testing.T) {206- c := initialize()207- cmdEcho.AddCommand(cmdTimes)208- c.AddCommand(cmdPrint, cmdEcho)209- c.SetArgs(strings.Split("ech tim one two", " "))210- c.Execute()199+ noRRSetupTest("ech tim one two")200 201 if te != nil || tp != nil {202 t.Error("Wrong command called")203 }39 unmodified lines243 }244 }245 246 func TestFlagLong(t *testing.T) {258- c := initialize()259- c.AddCommand(cmdPrint, cmdEcho, cmdTimes)260- c.SetArgs(strings.Split("echo --intone=13 something here", " "))261- c.Execute()247+ noRRSetupTest("echo --intone=13 something here")248 249 if strings.Join(te, " ") != "something here" {250 t.Errorf("flags didn't leave proper args remaining..%s given", te)251 }5 unmodified lines257 }258 }259 260 func TestFlagShort(t *testing.T) {275- c := initialize()276- c.AddCommand(cmdPrint, cmdEcho, cmdTimes)277- c.SetArgs(strings.Split("echo -i13 something here", " "))278- c.Execute()261+ noRRSetupTest("echo -i13 something here")262 263 if strings.Join(te, " ") != "something here" {264 t.Errorf("flags didn't leave proper args remaining..%s given", te)265 }3 unmodified lines269 if flagi2 != 234 {270 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)271 }272 290- c = initialize()291- c.AddCommand(cmdPrint, cmdEcho, cmdTimes)292- c.SetArgs(strings.Split("echo -i 13 something here", " "))293- c.Execute()273+ noRRSetupTest("echo -i 13 something here")274 275 if strings.Join(te, " ") != "something here" {276 t.Errorf("flags didn't leave proper args remaining..%s given", te)277 }3 unmodified lines281 if flagi2 != 234 {282 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)283 }284 305- // Testing same shortcode, different command306- c = initialize()307- c.AddCommand(cmdPrint, cmdEcho, cmdTimes)308- c.SetArgs(strings.Split("print -i99 one two", " "))309- c.Execute()285+ noRRSetupTest("print -i99 one two")286 287 if strings.Join(tp, " ") != "one two" {288 t.Errorf("flags didn't leave proper args remaining..%s given", tp)289 }5 unmodified lines295 }296 }297 298 func TestChildCommandFlags(t *testing.T) {323- c := initialize()324- cmdEcho.AddCommand(cmdTimes)325- c.AddCommand(cmdPrint, cmdEcho)326- c.SetArgs(strings.Split("echo times -j 99 one two", " "))327- c.Execute()299+ noRRSetupTest("echo times -j 99 one two")300 301 if strings.Join(tt, " ") != "one two" {302 t.Errorf("flags didn't leave proper args remaining..%s given", tt)303 }304 333- buf := new(bytes.Buffer)305 // Testing with flag that shouldn't be persistent335- c = initialize()336- c.SetOutput(buf)337- // define children338- c.AddCommand(cmdPrint, cmdEcho)339- // define grandchild340- cmdEcho.AddCommand(cmdTimes)341- c.SetArgs(strings.Split("echo times -j 99 -i77 one two", " "))342- e := c.Execute()306+ r := noRRSetupTest("echo times -j 99 -i77 one two")307 344- if e == nil {308+ if r.Error == nil {309 t.Errorf("invalid flag should generate error")310 }311 348- if !strings.Contains(buf.String(), "unknown shorthand") {349- t.Errorf("Wrong error message displayed, \n %s", buf.String())312+ if !strings.Contains(r.Output, "unknown shorthand") {313+ t.Errorf("Wrong error message displayed, \n %s", r.Output)314 }315 316 if flagi2 != 99 {317 t.Errorf("flag value should be 99, %d given", flagi2)3 unmodified lines321 t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)322 }323 324 // Testing with flag only existing on child361- buf.Reset()362- c = initialize()363- c.SetOutput(buf)364- cmdEcho.AddCommand(cmdTimes)365- c.AddCommand(cmdPrint, cmdEcho)366- c.SetArgs(strings.Split("echo -j 99 -i77 one two", " "))367- err := c.Execute()325+ r = noRRSetupTest("echo -j 99 -i77 one two")326 369- if err == nil {327+ if r.Error == nil {328 t.Errorf("invalid flag should generate error")329 }330 373- if !strings.Contains(buf.String(), "intone=123") {374- t.Errorf("Wrong error message displayed, \n %s", buf.String())331+ if !strings.Contains(r.Output, "intone=123") {332+ t.Errorf("Wrong error message displayed, \n %s", r.Output)333 }334 335 // Testing flag with invalid input378- buf.Reset()379- c = initialize()380- c.SetOutput(buf)381- cmdEcho.AddCommand(cmdTimes)382- c.AddCommand(cmdPrint, cmdEcho)383- c.SetArgs(strings.Split("echo -i10E", " "))384- err = c.Execute()336+ r = noRRSetupTest("echo -i10E")337 386- if err == nil {338+ if r.Error == nil {339 t.Errorf("invalid input should generate error")340 }341 390- if !strings.Contains(buf.String(), "invalid argument \"10E\" for -i10E") {391- t.Errorf("Wrong error message displayed, \n %s", buf.String())342+ if !strings.Contains(r.Output, "invalid argument \"10E\" for -i10E") {343+ t.Errorf("Wrong error message displayed, \n %s", r.Output)344 }393-345 }346 347 func TestTrailingCommandFlags(t *testing.T) {397- buf := new(bytes.Buffer)398- c := initialize()399- c.SetOutput(buf)400- cmdEcho.AddCommand(cmdTimes)401- c.AddCommand(cmdPrint, cmdEcho)402- c.SetArgs(strings.Split("echo two -x", " "))403- e3 := c.Execute()348+ x := fullSetupTest("echo two -x")349 405- if e3 == nil {350+ if x.Error == nil {351 t.Errorf("invalid flag should generate error")352 }353 }354 355 func TestPersistentFlags(t *testing.T) {411- c := initialize()412- cmdEcho.AddCommand(cmdTimes)413- c.AddCommand(cmdPrint, cmdEcho)414- c.SetArgs(strings.Split("echo -s something more here", " "))415- c.Execute()356+ fullSetupTest("echo -s something more here")357 358 // persistentFlag should act like normal flag on it's own command359 if strings.Join(te, " ") != "more here" {360 t.Errorf("flags didn't leave proper args remaining..%s given", te)3 unmodified lines364 if flags1 != "something" {365 t.Errorf("string flag didn't get correct value, had %v", flags1)366 }367 427- c = initialize()428- cmdEcho.AddCommand(cmdTimes)429- c.AddCommand(cmdPrint, cmdEcho)430- c.SetArgs(strings.Split("echo times -s again -c test here", " "))431- c.Execute()368+ fullSetupTest("echo times -s again -c test here")369 370 if strings.Join(tt, " ") != "test here" {371 t.Errorf("flags didn't leave proper args remaining..%s given", tt)372 }7 unmodified lines380 }381 }382 383 func TestHelpCommand(t *testing.T) {447- c := initialize()448- cmdEcho.AddCommand(cmdTimes)449- c.AddCommand(cmdPrint, cmdEcho)450- c.SetArgs(strings.Split("help echo", " "))384+ c := fullSetupTest("help echo")385+ checkResultContains(t, c, cmdEcho.Long)386 452- checkOutputContains(t, c, cmdEcho.Long)453-454- c = initialize()455- cmdEcho.AddCommand(cmdTimes)456- c.AddCommand(cmdPrint, cmdEcho)457- c.SetArgs(strings.Split("help echo times", " "))458-459- checkOutputContains(t, c, cmdTimes.Long)387+ r := fullSetupTest("help echo times")388+ checkResultContains(t, r, cmdTimes.Long)389 }390 391 func TestRunnableRootCommand(t *testing.T) {463- c := initializeWithRootCmd()464- c.AddCommand(cmdPrint, cmdEcho)465- c.SetArgs([]string(nil))466- c.Execute()392+ fullSetupTest("")393 394 if rootcalled != true {395 t.Errorf("Root Function was not called")396 }397 }398 399 func TestRootFlags(t *testing.T) {474- c := initializeWithRootCmd()475- c.AddCommand(cmdPrint, cmdEcho)476- c.SetArgs(strings.Split("-i 17 -b", " "))477- c.Execute()400+ fullSetupTest("-i 17 -b")401 402 if flagbr != true {403 t.Errorf("flag value should be true, %v given", flagbr)404 }21 unmodified lines426 }427 428 }429 507- checkOutputContains(t, c, "Available Commands:")430+func TestFlagsBeforeCommand(t *testing.T) {431+ // short without space432+ x := fullSetupTest("-i10 echo")433+ if x.Error != nil {434+ t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)435+ }436+437+ // short (int) with equals438+ // It appears that pflags doesn't support this...439+ // Commenting out until support can be added440+441+ //x = noRRSetupTest("echo -i=10")442+ //if x.Error != nil {443+ //t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)444+ //}445+446+ // long with equals447+ x = noRRSetupTest("--intone=123 echo one two")448+ if x.Error != nil {449+ t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)450+ }451+452+ // With parsing error properly reported453+ x = fullSetupTest("-i10E echo")454+ if !strings.Contains(x.Output, "invalid argument \"10E\" for -i10E") {455+ t.Errorf("Wrong error message displayed, \n %s", x.Output)456+ }457+458+ //With quotes459+ x = fullSetupTest("-s=\"walking\" echo")460+ if x.Error != nil {461+ t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)462+ }463+464+ //With quotes and space465+ x = fullSetupTest("-s=\"walking fast\" echo")466+ if x.Error != nil {467+ t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)468+ }469+470+ //With inner quote471+ x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")472+ if x.Error != nil {473+ t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)474+ }475+476+ //With quotes and space477+ x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")478+ if x.Error != nil {479+ t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)480+ }481+482 }modified:command.go+66 added-11 removed
223 unmodified lines224 x.parent = c225 }226 }227 228+func stripFlags(args []string) []string {229+ if len(args) < 1 {230+ return args231+ }232+233+ commands := []string{}234+235+ inQuote := false236+ for _, y := range args {237+ if !inQuote {238+ switch {239+ case strings.HasPrefix(y, "\""):240+ inQuote = true241+ case strings.Contains(y, "=\""):242+ inQuote = true243+ case !strings.HasPrefix(y, "-"):244+ commands = append(commands, y)245+ }246+ }247+248+ if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {249+ inQuote = false250+ }251+ }252+253+ return commands254+}255+256+func argsMinusX(args []string, x string) []string {257+ newargs := []string{}258+259+ for _, y := range args {260+ if x != y {261+ newargs = append(newargs, y)262+ }263+ }264+ return newargs265+}266+267 // find the target command given the args and command tree268 // Meant to be run on the highest node. Only searches down.269 func (c *Command) Find(arrs []string) (*Command, []string, error) {270 if c == nil {7 unmodified lines278 var innerfind func(*Command, []string) (*Command, []string)279 280 innerfind = func(c *Command, args []string) (*Command, []string) {281 if len(args) > 0 && c.HasSubCommands() {282+ argsWOflags := stripFlags(args)283+ if len(argsWOflags) > 0 {243- matches := make([]*Command, 0)244- for _, cmd := range c.commands {245- if cmd.Name() == args[0] { // exact name match246- return innerfind(cmd, args[1:])247- } else if strings.HasPrefix(cmd.Name(), args[0]) { // prefix match248- matches = append(matches, cmd)284+ matches := make([]*Command, 0)285+ for _, cmd := range c.commands {286+ if cmd.Name() == argsWOflags[0] { // exact name match287+ return innerfind(cmd, argsMinusX(args, cmd.Name()))288+ } else if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match289+ matches = append(matches, cmd)290+ }291 }250- }292 252- // only accept a single prefix match - multiple matches would be ambiguous253- if len(matches) == 1 {254- return innerfind(matches[0], args[1:])293+ // only accept a single prefix match - multiple matches would be ambiguous294+ if len(matches) == 1 {295+ return innerfind(matches[0], argsMinusX(args, argsWOflags[0]))296+ }297 }298 }299 300 return c, args54 unmodified lines355 return nil356 }357 }358 359+func (c *Command) errorMsgFromParse() string {360+ s := c.flagErrorBuf.String()361+362+ x := strings.Split(s, "\n")363+364+ if len(x) > 0 {365+ return x[0]366+ } else {367+ return ""368+ }369+}370+371 // Call execute to use the args (os.Args[1:] by default)372 // and run through the command tree finding appropriate matches373 // for commands and then corresponding flags.374 func (c *Command) Execute() (err error) {30 unmodified lines405 if err != nil && c.Runnable() {406 e := c.ParseFlags(args)407 if e != nil {408 // Flags parsing had an error.355- fmt.Println(e)409+ //fmt.Println(e)410+ c.Println(c.errorMsgFromParse())411 c.Usage()412 return e413 } else {414 310 unmodified linesmodified:README.md+23 added-2 removed
16 unmodified lines17 18 Cobra has an exceptionally clean interface and simple design without needless19 constructors or initialization methods.20 21+Applications built with Cobra commands are designed to be as user friendly as22+possible. Flags can be placed before or after the command (as long as a23+confusing space isn’t provided). Both short and long flags can be used. A24+command need not even be fully typed. The shortest unambiguous string will25+suffice. Help is automatically generated and available for the application or26+for a specific command using either the help command or the --help flag.27+28 ## Concepts29 30 Cobra is built on a structure of commands & flags.31 257 unmodified lines289 command.SetHelpTemplate(s string)290 291 The latter two will also apply to any children commands.292 286-293 ## Usage294 295 When the user provides an invalid flag or invalid command Cobra responds by296 showing the user the 'usage'297 298 ### Example293-You may recognize this from the help above. That's because the default help 299+You may recognize this from the help above. That's because the default help300 embeds the usage as part of it's output.301 302 Usage:303 hugo [flags]33 unmodified lines337 338 command.SetUsageTemplate(s string)339 340 341+## Debugging342+343+Cobra provides a ‘DebugFlags’ method on a command which when called will print344+out everything Cobra knows about the flags for each command345+346+### Example347+348+ command.DebugFlags()349+350 ## Release Notes351+* **0.9.0** June 17, 2014352+ * flags can appears anywhere in the args (provided they are unambiguous)353+ * --help prints usage screen for app or command354+ * Prefix matching for commands355+ * Cleaner looking help and usage output356+ * Extensive test suite357 * **0.8.0** Nov 5, 2013358 * Reworked interface to remove commander completely359 * Command now primary structure360 * No initialization needed37 unmodified lines