Skip to content
Myr

command.go

This file

Path

command.go

655 lines · 15.8 KiB · Go

Last changed by

Cobra behavior is now more consistent. Invalid flags cause Usage to be printed.spf13before adoption71bb1df

History of this file

Take it

Organize the files a bit betterspf13before adoption62fb674

lines 1–22why, one step back
1// Copyright © 2013 Steve Francia <spf@spf13.com>.
2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314// Commands similar to git, go tools and other modern CLI tools15// inspired by go, go-Commander, gh and subcommand1617package cobra1819import (20 "bytes"21 "fmt"22 "io"

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 23why, one step back
23 "os"

Organize the files a bit betterspf13before adoption62fb674

line 24why, one step back
24 "strings"

Print root usage when help called with no args.Kevin Darlingtonbefore adoptione174a40

lines 25–26why, one step back
25
26 flag "github.com/spf13/pflag"

Organize the files a bit betterspf13before adoption62fb674

lines 27–48why, one step back
27)
2829// Command is just that, a command for your application.30// eg. 'go run' ... 'run' is the command. Cobra requires31// you to define the usage and description as part of your command32// definition to ensure usability.33type Command struct {34 // Name is the command name, usually the executable's name.35 name string36 // The one-line usage message.37 Use string38 // The short description shown in the 'help' output.39 Short string40 // The long message shown in the 'help <this-command>' output.41 Long string42 // Set of flags specific to this command.43 flags *flag.FlagSet44 // Set of flags children commands will inherit45 pflags *flag.FlagSet46 // Run runs the command.47 // The args are the arguments after the command name.48 Run func(cmd *Command, args []string)

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 49why, one step back
49 // Commands is the list of commands supported by this program.

Organize the files a bit betterspf13before adoption62fb674

lines 50–51why, one step back
50 commands []*Command
51 // Parent Command for this command

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 52why, one step back
52 parent *Command

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 53–55why, one step back
53 // max lengths of commands' string lengths for use in padding
54 commandsMaxUseLen int55 commandsMaxCommandPathLen int

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 56why, one step back
56

Organize the files a bit betterspf13before adoption62fb674

line 57why, one step back
57 flagErrorBuf *bytes.Buffer

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 58–59why, one step back
58
59 args []string

Documentation updatespf13before adoption59bd285

line 60why, one step back
60 output *io.Writer // nil means stderr; use Out() method instead

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 61–65why, one step back
61 usageFunc func(*Command) error // Usage can be defined by application
62 usageTemplate string // Can be defined by Application63 helpTemplate string // Can be defined by Application64 helpFunc func(*Command, []string) // Help can be defined by application65 helpCommand *Command // The help command

Organize the files a bit betterspf13before adoption62fb674

lines 66–67why, one step back
66}
67

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 68–71why, one step back
68// os.Args[1:] by default, if desired, can be overridden
69// particularly useful when testing.70func (c *Command) SetArgs(a []string) {71 c.args = a

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 72–73why, one step back
72}
73

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 74–140why, one step back
74func (c *Command) Out() io.Writer {
75 if c.output != nil {76 return *c.output77 }7879 if c.HasParent() {80 return c.parent.Out()81 } else {82 return os.Stderr83 }84}8586// SetOutput sets the destination for usage and error messages.87// If output is nil, os.Stderr is used.88func (c *Command) SetOutput(output io.Writer) {89 c.output = &output90}9192// Usage can be defined by application93func (c *Command) SetUsageFunc(f func(*Command) error) {94 c.usageFunc = f95}9697// Can be defined by Application98func (c *Command) SetUsageTemplate(s string) {99 c.usageTemplate = s100}101102// Can be defined by Application103func (c *Command) SetHelpFunc(f func(*Command, []string)) {104 c.helpFunc = f105}106107func (c *Command) SetHelpCommand(cmd *Command) {108 c.helpCommand = cmd109}110111// Can be defined by Application112func (c *Command) SetHelpTemplate(s string) {113 c.helpTemplate = s114}115116func (c *Command) UsageFunc() (f func(*Command) error) {117 if c.usageFunc != nil {118 return c.usageFunc119 }120121 if c.HasParent() {122 return c.parent.UsageFunc()123 } else {124 return func(c *Command) error {125 err := tmpl(c.Out(), c.UsageTemplate(), c)126 return err127 }128 }129}130func (c *Command) HelpFunc() func(*Command, []string) {131 if c.helpFunc != nil {132 return c.helpFunc133 }134135 if c.HasParent() {136 return c.parent.HelpFunc()137 } else {138 return func(c *Command, args []string) {139 if len(args) == 0 {140 // Help called without any topic, calling on root

Print root usage when help called with no args.Kevin Darlingtonbefore adoptione174a40

line 141why, one step back
141 c.Root().Usage()

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 142–159why, one step back
142 return
143 }144145 cmd, _, e := c.Root().Find(args)146 if cmd == nil || e != nil {147 c.Printf("Unknown help topic %#q.", args)148149 c.Root().Usage()150 } else {151 err := cmd.Help()152 if err != nil {153 c.Println(err)154 }155 }156 }157 }158}159

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 160–179why, one step back
160var minUsagePadding int = 25
161162func (c *Command) UsagePadding() int {163 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {164 return minUsagePadding165 } else {166 return c.parent.commandsMaxUseLen167 }168}169170var minCommandPathPadding int = 11171172func (c *Command) CommandPathPadding() int {173 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {174 return minCommandPathPadding175 } else {176 return c.parent.commandsMaxCommandPathLen177 }178}179

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 180–193why, one step back
180func (c *Command) UsageTemplate() string {
181 if c.usageTemplate != "" {182 return c.usageTemplate183 }184185 if c.HasParent() {186 return c.parent.UsageTemplate()187 } else {188 return `{{ $cmd := . }}189Usage: {{if .Runnable}}190 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}191 {{ .CommandPath}} [command]{{end}}192{{ if .HasSubCommands}}193Available Commands: {{range .Commands}}{{if .Runnable}}

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

line 194why, one step back
194 {{rpad .Use .UsagePadding }} :: {{.Short}}{{end}}{{end}}

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 195–197why, one step back
195{{end}}
196{{ if .HasFlags}} Available Flags:197{{.Flags.FlagUsages}}{{end}}{{if .HasParent}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 198–199why, one step back
198Additional help topics: {{if gt .Commands 0 }}{{range .Commands}}{{if not .Runnable}} {{rpad .CommandPath .CommandPathPadding}} :: {{.Short}}{{end}}{{end}}{{end}}{{if gt .Parent.Commands 1 }}{{range .Parent.Commands}}{{if .Runnable}}{{if not (eq .Name $cmd.Name) }}{{end}}
199 {{rpad .CommandPath .CommandPathPadding}} :: {{.Short}}{{end}}{{end}}{{end}}{{end}}

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 200–219why, one step back
200{{end}}
201Use "{{.Root.Name}} help [command]" for more information about that command.202`203 }204}205206func (c *Command) HelpTemplate() string {207 if c.helpTemplate != "" {208 return c.helpTemplate209 }210211 if c.HasParent() {212 return c.parent.HelpTemplate()213 } else {214 return `{{.Long | trim}}215{{if .Runnable}}{{.UsageString}}{{end}}216`217 }218}219

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 220–226why, one step back
220// Really only used when casting a command to a commander
221func (c *Command) resetChildrensParents() {222 for _, x := range c.commands {223 x.parent = c224 }225}226

Organize the files a bit betterspf13before adoption62fb674

line 227why, one step back
227// find the target command given the args and command tree

Add support for help commandspf13before adoptionfb2146e

line 228why, one step back
228// Meant to be run on the highest node. Only searches down.

Finding command based on args cleaned upspf13before adoption55ff474

line 229why, one step back
229func (c *Command) Find(arrs []string) (*Command, []string, error) {

Organize the files a bit betterspf13before adoption62fb674

lines 230–233why, one step back
230 if c == nil {
231 return nil, nil, fmt.Errorf("Called find() on a nil Command")232 }233

Finding command based on args cleaned upspf13before adoption55ff474

line 234why, one step back
234 if len(arrs) == 0 {

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 235why, one step back
235 return c.Root(), arrs, nil

Finding command based on args cleaned upspf13before adoption55ff474

lines 236–241why, one step back
236 }
237238 var innerfind func(*Command, []string) (*Command, []string)239240 innerfind = func(c *Command, args []string) (*Command, []string) {241 if len(args) > 0 && c.HasSubCommands() {

Add command name prefix matchingtummychowbefore adoptionf4c075f

line 242why, one step back
242 matches := make([]*Command, 0)

Finding command based on args cleaned upspf13before adoption55ff474

line 243why, one step back
243 for _, cmd := range c.commands {

Add command name prefix matchingtummychowbefore adoptionf4c075f

line 244why, one step back
244 if cmd.Name() == args[0] { // exact name match

Finding command based on args cleaned upspf13before adoption55ff474

line 245why, one step back
245 return innerfind(cmd, args[1:])

Add command name prefix matchingtummychowbefore adoptionf4c075f

lines 246–247why, one step back
246 } else if strings.HasPrefix(cmd.Name(), args[0]) { // prefix match
247 matches = append(matches, cmd)

Finding command based on args cleaned upspf13before adoption55ff474

line 248why, one step back
248 }

Add command name prefix matchingtummychowbefore adoptionf4c075f

lines 249–253why, one step back
249 }
250251 // only accept a single prefix match - multiple matches would be ambiguous252 if len(matches) == 1 {253 return innerfind(matches[0], args[1:])

Organize the files a bit betterspf13before adoption62fb674

lines 254–255why, one step back
254 }
255 }

Finding command based on args cleaned upspf13before adoption55ff474

lines 256–257why, one step back
256
257 return c, args

Organize the files a bit betterspf13before adoption62fb674

line 258why, one step back
258 }

Finding command based on args cleaned upspf13before adoption55ff474

lines 259–262why, one step back
259
260 commandFound, a := innerfind(c, arrs)261262 // if commander returned and not appropriately matched return nil & error

Test behavior for subcommand with same name as root commandtummychowbefore adoption667c348

line 263why, one step back
263 if commandFound.Name() == c.Name() && !strings.HasPrefix(commandFound.Name(), arrs[0]) {

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

line 264why, one step back
264 return nil, a, fmt.Errorf("unknown command %q\nRun 'help' for usage.\n", a[0])

Organize the files a bit betterspf13before adoption62fb674

lines 265–266why, one step back
265 }
266

Finding command based on args cleaned upspf13before adoption55ff474

line 267why, one step back
267 return commandFound, a, nil

Organize the files a bit betterspf13before adoption62fb674

lines 268–269why, one step back
268}
269

Add support for help commandspf13before adoptionfb2146e

line 270why, one step back
270func (c *Command) Root() *Command {

Organize the files a bit betterspf13before adoption62fb674

lines 271–279why, one step back
271 var findRoot func(*Command) *Command
272273 findRoot = func(x *Command) *Command {274 if x.HasParent() {275 return findRoot(x.parent)276 } else {277 return x278 }279 }

Add support for help commandspf13before adoptionfb2146e

lines 280–283why, one step back
280
281 return findRoot(c)282}283

Organize the files a bit betterspf13before adoption62fb674

line 284why, one step back
284// execute the command determined by args and the command tree

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

line 285why, one step back
285func (c *Command) findAndExecute(args []string) (err error) {

Organize the files a bit betterspf13before adoption62fb674

line 286why, one step back
286

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

lines 287–294why, one step back
287 cmd, a, e := c.Find(args)
288 if e != nil {289 return e290 }291 return cmd.execute(a)292}293294func (c *Command) execute(a []string) (err error) {

Organize the files a bit betterspf13before adoption62fb674

lines 295–298why, one step back
295 if c == nil {
296 return fmt.Errorf("Called Execute() on a nil Command")297 }298

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

line 299why, one step back
299 err = c.ParseFlags(a)

Fixing error messaging when upstream flag library is inconsistent.spf13before adoptionfae1335

line 300why, one step back
300

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

lines 301–306why, one step back
301 if err != nil {
302 return err303 } else {304 argWoFlags := c.Flags().Args()305 c.Run(c, argWoFlags)306 return nil

Organize the files a bit betterspf13before adoption62fb674

lines 307–309why, one step back
307 }
308}309

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 310–346why, one step back
310// Call execute to use the args (os.Args[1:] by default)
311// and run through the command tree finding appropriate matches312// for commands and then corresponding flags.313func (c *Command) Execute() (err error) {314315 // Regardless of what command execute is called on, run on Root only316 if c.HasParent() {317 return c.Root().Execute()318 }319320 // initialize help as the last point possible to allow for user321 // overriding322 c.initHelp()323324 var args []string325326 if len(c.args) == 0 {327 args = os.Args[1:]328 } else {329 args = c.args330 }331332 if len(args) == 0 {333 // Only the executable is called and the root is runnable, run it334 if c.Runnable() {335 err = c.execute([]string(nil))336 } else {337 c.Usage()338 }339 } else {340 err = c.findAndExecute(args)341 }342343 // Now handle the case where the root is runnable and only flags are provided344 if err != nil && c.Runnable() {345 e := c.ParseFlags(args)346 if e != nil {

Cobra behavior is now more consistent. Invalid flags cause Usage to be printed.spf13before adoption71bb1df

lines 347–349why, one step back
347 // Flags parsing had an error.
348 fmt.Println(e)349 c.Usage()

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 350–383why, one step back
350 return e
351 } else {352 argWoFlags := c.Flags().Args()353 if len(argWoFlags) > 0 {354 c.Usage()355 } else {356 c.Run(c, argWoFlags)357 err = nil358 }359 }360 }361362 if err != nil {363 c.Println("Error:", err.Error())364 c.Printf("%v: invalid command %#q\n", c.Root().Name(), os.Args[1:])365 c.Printf("Run '%v help' for usage\n", c.Root().Name())366 }367368 return369}370371func (c *Command) initHelp() {372 if c.helpCommand == nil {373 c.helpCommand = &Command{374 Use: "help [command]",375 Short: "Help about any command",376 Long: `Help provides help for any command in the application.377 Simply type ` + c.Name() + ` help [path to command] for full details.`,378 Run: c.HelpFunc(),379 }380 }381 c.AddCommand(c.helpCommand)382}383

Organize the files a bit betterspf13before adoption62fb674

lines 384–399why, one step back
384// Used for testing
385func (c *Command) ResetCommands() {386 c.commands = nil387}388389func (c *Command) Commands() []*Command {390 return c.commands391}392393// Add one or many commands as children of this394func (c *Command) AddCommand(cmds ...*Command) {395 for i, x := range cmds {396 if cmds[i] == c {397 panic("Command can't be a child of itself")398 }399 cmds[i].parent = c

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 400–408why, one step back
400 // update max lengths
401 usageLen := len(x.Use)402 if usageLen > c.commandsMaxUseLen {403 c.commandsMaxUseLen = usageLen404 }405 commandPathLen := len(x.CommandPath())406 if commandPathLen > c.commandsMaxCommandPathLen {407 c.commandsMaxCommandPathLen = commandPathLen408 }

Organize the files a bit betterspf13before adoption62fb674

lines 409–414why, one step back
409 c.commands = append(c.commands, x)
410 }411}412413// Convenience method to Print to the defined output414func (c *Command) Print(i ...interface{}) {

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 415why, one step back
415 fmt.Fprint(c.Out(), i...)

Organize the files a bit betterspf13before adoption62fb674

lines 416–431why, one step back
416}
417418// Convenience method to Println to the defined output419func (c *Command) Println(i ...interface{}) {420 str := fmt.Sprintln(i...)421 c.Print(str)422}423424// Convenience method to Printf to the defined output425func (c *Command) Printf(format string, i ...interface{}) {426 str := fmt.Sprintf(format, i...)427 c.Print(str)428}429430// Output the usage for the command431// Used when a user provides invalid input

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 432why, one step back
432// Can be defined by user by overriding UsageFunc

Organize the files a bit betterspf13before adoption62fb674

line 433why, one step back
433func (c *Command) Usage() error {

Help improvementsspf13before adoption2d02c31

line 434why, one step back
434 c.mergePersistentFlags()

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 435why, one step back
435 err := c.UsageFunc()(c)

Help improvementsspf13before adoption2d02c31

lines 436–443why, one step back
436 return err
437}438439// Output the help for the command440// Used when a user calls help [command]441// by the default HelpFunc in the commander442func (c *Command) Help() error {443 c.mergePersistentFlags()

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 444why, one step back
444 err := tmpl(c.Out(), c.HelpTemplate(), c)

Organize the files a bit betterspf13before adoption62fb674

lines 445–447why, one step back
445 return err
446}447

fix trailing <nil> on help outputspf13before adoption3958385

line 448why, one step back
448func (c *Command) UsageString() string {

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 449why, one step back
449 tmpOutput := c.output

fix trailing <nil> on help outputspf13before adoption3958385

line 450why, one step back
450 bb := new(bytes.Buffer)

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 451why, one step back
451 c.SetOutput(bb)

fix trailing <nil> on help outputspf13before adoption3958385

line 452why, one step back
452 c.Usage()

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 453why, one step back
453 c.output = tmpOutput

fix trailing <nil> on help outputspf13before adoption3958385

lines 454–456why, one step back
454 return bb.String()
455}456

Organize the files a bit betterspf13before adoption62fb674

lines 457–621why, one step back
457// The full path to this command
458func (c *Command) CommandPath() string {459 str := c.Name()460 x := c461 for x.HasParent() {462 str = x.parent.Name() + " " + str463 x = x.parent464 }465 return str466}467468//The full usage for a given command (including parents)469func (c *Command) UseLine() string {470 str := ""471 if c.HasParent() {472 str = c.parent.CommandPath() + " "473 }474 return str + c.Use475}476477// For use in determining which flags have been assigned to which commands478// and which persist479func (c *Command) DebugFlags() {480 c.Println("DebugFlags called on", c.Name())481 var debugflags func(*Command)482483 debugflags = func(x *Command) {484 if x.HasFlags() || x.HasPersistentFlags() {485 c.Println(x.Name())486 }487 if x.HasFlags() {488 x.flags.VisitAll(func(f *flag.Flag) {489 if x.HasPersistentFlags() {490 if x.persistentFlag(f.Name) == nil {491 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")492 } else {493 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")494 }495 } else {496 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")497 }498 })499 }500 if x.HasPersistentFlags() {501 x.pflags.VisitAll(func(f *flag.Flag) {502 if x.HasFlags() {503 if x.flags.Lookup(f.Name) == nil {504 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")505 }506 } else {507 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")508 }509 })510 }511 c.Println(x.flagErrorBuf)512 if x.HasSubCommands() {513 for _, y := range x.commands {514 debugflags(y)515 }516 }517 }518519 debugflags(c)520}521522// Name returns the command's name: the first word in the use line.523func (c *Command) Name() string {524 if c.name != "" {525 return c.name526 }527 name := c.Use528 i := strings.Index(name, " ")529 if i >= 0 {530 name = name[:i]531 }532 return name533}534535// Determine if the command is itself runnable536func (c *Command) Runnable() bool {537 return c.Run != nil538}539540// Determine if the command has children commands541func (c *Command) HasSubCommands() bool {542 return len(c.commands) > 0543}544545// Determine if the command is a child command546func (c *Command) HasParent() bool {547 return c.parent != nil548}549550// Get the Commands FlagSet551func (c *Command) Flags() *flag.FlagSet {552 if c.flags == nil {553 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)554 if c.flagErrorBuf == nil {555 c.flagErrorBuf = new(bytes.Buffer)556 }557 c.flags.SetOutput(c.flagErrorBuf)558 }559 return c.flags560}561562// Get the Commands Persistent FlagSet563func (c *Command) PersistentFlags() *flag.FlagSet {564 if c.pflags == nil {565 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)566 if c.flagErrorBuf == nil {567 c.flagErrorBuf = new(bytes.Buffer)568 }569 c.pflags.SetOutput(c.flagErrorBuf)570 }571 return c.pflags572}573574// For use in testing575func (c *Command) ResetFlags() {576 c.flagErrorBuf = new(bytes.Buffer)577 c.flagErrorBuf.Reset()578 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)579 c.flags.SetOutput(c.flagErrorBuf)580 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)581 c.pflags.SetOutput(c.flagErrorBuf)582}583584// Does the command contain flags (local not persistent)585func (c *Command) HasFlags() bool {586 return c.Flags().HasFlags()587}588589// Does the command contain persistent flags590func (c *Command) HasPersistentFlags() bool {591 return c.PersistentFlags().HasFlags()592}593594// Climbs up the command tree looking for matching flag595func (c *Command) Flag(name string) (flag *flag.Flag) {596 flag = c.Flags().Lookup(name)597598 if flag == nil {599 flag = c.persistentFlag(name)600 }601602 return603}604605// recursively find matching persistent flag606func (c *Command) persistentFlag(name string) (flag *flag.Flag) {607 if c.HasPersistentFlags() {608 flag = c.PersistentFlags().Lookup(name)609 }610611 if flag == nil && c.HasParent() {612 flag = c.parent.persistentFlag(name)613 }614 return615}616617// Parses persistent flag tree & local flags618func (c *Command) ParseFlags(args []string) (err error) {619 c.mergePersistentFlags()620621 err = c.Flags().Parse(args)

Fixing error messaging when upstream flag library is inconsistent.spf13before adoptionfae1335

line 622why, one step back
622

Proper handling of flag error messages. Fixing test that wasn't passing.spf13before adoption68f3c66

lines 623–627why, one step back
623 // The upstream library adds spaces to the error
624 // response regardless of success.625 // Handling it here until fixing upstream626 if len(strings.TrimSpace(c.flagErrorBuf.String())) > 1 {627 return fmt.Errorf("%s", c.flagErrorBuf.String())

Organize the files a bit betterspf13before adoption62fb674

line 628why, one step back
628 }

Fixing error messaging when upstream flag library is inconsistent.spf13before adoptionfae1335

lines 629–630why, one step back
629
630 //always return nil because upstream library is inconsistent & we always check the error buffer anyway

Organize the files a bit betterspf13before adoption62fb674

lines 631–655why, one step back
631 return nil
632}633634func (c *Command) mergePersistentFlags() {635 var rmerge func(x *Command)636637 rmerge = func(x *Command) {638 if x.HasPersistentFlags() {639 x.PersistentFlags().VisitAll(func(f *flag.Flag) {640 if c.Flags().Lookup(f.Name) == nil {641 c.Flags().AddFlag(f)642 }643 })644 }645 if x.HasParent() {646 rmerge(x.parent)647 }648 }649650 rmerge(c)651}652653func (c *Command) Parent() *Command {654 return c.parent655}