Skip to content
Myr

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

3 files+171 added−121 removed

modified:cobra_test.go+82 added-108 removed
166 unmodified lines
167 }168}169170func 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")172173 if te != nil || tt != nil {174 t.Error("Wrong command called")175 }
5 unmodified lines
181 }182}183184func 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")186187 if te != nil || tp != nil {188 t.Error("Wrong command called")189 }
5 unmodified lines
195 }196}197198func 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")200201 if te != nil || tp != nil {202 t.Error("Wrong command called")203 }
39 unmodified lines
243 }244}245246func 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")248249 if strings.Join(te, " ") != "something here" {250 t.Errorf("flags didn't leave proper args remaining..%s given", te)251 }
5 unmodified lines
257 }258}259260func 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")262263 if strings.Join(te, " ") != "something here" {264 t.Errorf("flags didn't leave proper args remaining..%s given", te)265 }
3 unmodified lines
269 if flagi2 != 234 {270 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)271 }272290 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")274275 if strings.Join(te, " ") != "something here" {276 t.Errorf("flags didn't leave proper args remaining..%s given", te)277 }
3 unmodified lines
281 if flagi2 != 234 {282 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)283 }284305 // 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")286287 if strings.Join(tp, " ") != "one two" {288 t.Errorf("flags didn't leave proper args remaining..%s given", tp)289 }
5 unmodified lines
295 }296}297298func 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")300301 if strings.Join(tt, " ") != "one two" {302 t.Errorf("flags didn't leave proper args remaining..%s given", tt)303 }304333 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")307344 if e == nil {308 if r.Error == nil {309 t.Errorf("invalid flag should generate error")310 }311348 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 }315316 if flagi2 != 99 {317 t.Errorf("flag value should be 99, %d given", flagi2)
3 unmodified lines
321 t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)322 }323324 // 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")326369 if err == nil {327 if r.Error == nil {328 t.Errorf("invalid flag should generate error")329 }330373 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 }334335 // 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")337386 if err == nil {338 if r.Error == nil {339 t.Errorf("invalid input should generate error")340 }341390 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 }393345}346347func 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")349405 if e3 == nil {350 if x.Error == nil {351 t.Errorf("invalid flag should generate error")352 }353}354355func 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")357358 // 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 lines
364 if flags1 != "something" {365 t.Errorf("string flag didn't get correct value, had %v", flags1)366 }367427 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")369370 if strings.Join(tt, " ") != "test here" {371 t.Errorf("flags didn't leave proper args remaining..%s given", tt)372 }
7 unmodified lines
380 }381}382383func 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)386452 checkOutputContains(t, c, cmdEcho.Long)453454 c = initialize()455 cmdEcho.AddCommand(cmdTimes)456 c.AddCommand(cmdPrint, cmdEcho)457 c.SetArgs(strings.Split("help echo times", " "))458459 checkOutputContains(t, c, cmdTimes.Long)387 r := fullSetupTest("help echo times")388 checkResultContains(t, r, cmdTimes.Long)389}390391func TestRunnableRootCommand(t *testing.T) {463 c := initializeWithRootCmd()464 c.AddCommand(cmdPrint, cmdEcho)465 c.SetArgs([]string(nil))466 c.Execute()392 fullSetupTest("")393394 if rootcalled != true {395 t.Errorf("Root Function was not called")396 }397}398399func 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")401402 if flagbr != true {403 t.Errorf("flag value should be true, %v given", flagbr)404 }
21 unmodified lines
426 }427428}429507 checkOutputContains(t, c, "Available Commands:")430func 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 }436437 // short (int) with equals438 // It appears that pflags doesn't support this...439 // Commenting out until support can be added440441 //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 //}445446 // 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 }451452 // 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 }457458 //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 }463464 //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 }469470 //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 }475476 //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 }481482}
modified:command.go+66 added-11 removed
223 unmodified lines
224 x.parent = c225 }226}227228func stripFlags(args []string) []string {229 if len(args) < 1 {230 return args231 }232233 commands := []string{}234235 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 }247248 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {249 inQuote = false250 }251 }252253 return commands254}255256func argsMinusX(args []string, x string) []string {257 newargs := []string{}258259 for _, y := range args {260 if x != y {261 newargs = append(newargs, y)262 }263 }264 return newargs265}266267// find the target command given the args and command tree268// Meant to be run on the highest node. Only searches down.269func (c *Command) Find(arrs []string) (*Command, []string, error) {270 if c == nil {
7 unmodified lines
278 var innerfind func(*Command, []string) (*Command, []string)279280 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 }292252 // 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 }299300 return c, args
54 unmodified lines
355 return nil356 }357}358359func (c *Command) errorMsgFromParse() string {360 s := c.flagErrorBuf.String()361362 x := strings.Split(s, "\n")363364 if len(x) > 0 {365 return x[0]366 } else {367 return ""368 }369}370371// 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.374func (c *Command) Execute() (err error) {
30 unmodified lines
405 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 lines
modified:README.md+23 added-2 removed
16 unmodified lines
1718Cobra has an exceptionally clean interface and simple design without needless19constructors or initialization methods.2021Applications built with Cobra commands are designed to be as user friendly as22possible. Flags can be placed before or after the command (as long as a23confusing space isn’t provided). Both short and long flags can be used. A24command need not even be fully typed. The shortest unambiguous string will25suffice. Help is automatically generated and available for the application or26for a specific command using either the help command or the --help flag.2728## Concepts2930Cobra is built on a structure of commands & flags.31
257 unmodified lines
289 command.SetHelpTemplate(s string)290291The latter two will also apply to any children commands.292286293## Usage294295When the user provides an invalid flag or invalid command Cobra responds by296showing the user the 'usage'297298### Example293You may recognize this from the help above. That's because the default help 299You may recognize this from the help above. That's because the default help300embeds the usage as part of it's output.301302 Usage:303 hugo [flags]
33 unmodified lines
337338 command.SetUsageTemplate(s string)339340341## Debugging342343Cobra provides a ‘DebugFlags’ method on a command which when called will print344out everything Cobra knows about the flags for each command345346### Example347348 command.DebugFlags()349350## 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 needed
37 unmodified lines