Skip to content
Myr

command.go

This file

Path

command.go

970 lines · 23.6 KiB · Go

Last changed by

Deprecated subcommandsEric Parisbefore adoptionc3e48f9

History of this file

Take it

Organize the files a bit betterspf13before adoption62fb674

lines 1–13why, 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.13

Code commentaryAhsanul Haquebefore adoptione1e66f7

lines 14–15why, one step back
14//Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
15//In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.

Organize the files a bit betterspf13before adoption62fb674

lines 16–20why, one step back
16package cobra
1718import (19 "bytes"20 "fmt"

Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29

lines 21–22why, one step back
21 "github.com/inconshreveable/mousetrap"
22 flag "github.com/spf13/pflag"

Organize the files a bit betterspf13before adoption62fb674

line 23why, one step back
23 "io"

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

line 24why, one step back
24 "os"

Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29

line 25why, one step back
25 "runtime"

Organize the files a bit betterspf13before adoption62fb674

line 26why, one step back
26 "strings"

Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29

line 27why, one step back
27 "time"

Organize the files a bit betterspf13before adoption62fb674

lines 28–38why, one step back
28)
2930// Command is just that, a command for your application.31// eg. 'go run' ... 'run' is the command. Cobra requires32// you to define the usage and description as part of your command33// definition to ensure usability.34type Command struct {35 // Name is the command name, usually the executable's name.36 name string37 // The one-line usage message.38 Use string

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 39–40why, one step back
39 // An array of aliases that can be used instead of the first word in Use.
40 Aliases []string

Organize the files a bit betterspf13before adoption62fb674

lines 41–44why, one step back
41 // The short description shown in the 'help' output.
42 Short string43 // The long message shown in the 'help <this-command>' output.44 Long string

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 45–46why, one step back
45 // Examples of how to use the command
46 Example string

Merge pull request #69 from eparis/command-annotationsEric Parisbefore adoptionc746d30

lines 47–50why, one step back
47 // List of all valid non-flag arguments, used for bash completions *TODO* actually validate these
48 ValidArgs []string49 // Custom functions used by the bash autocompletion generator50 BashCompletionFunction string

Deprecated subcommandsEric Parisbefore adoptionc3e48f9

lines 51–52why, one step back
51 // Is this command deprecated and should print this string when used?
52 Deprecated string

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 53why, one step back
53 // Full set of flags

Organize the files a bit betterspf13before adoption62fb674

line 54why, one step back
54 flags *flag.FlagSet

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 55why, one step back
55 // Set of flags childrens of this command will inherit

Organize the files a bit betterspf13before adoption62fb674

line 56why, one step back
56 pflags *flag.FlagSet

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 57–58why, one step back
57 // Flags that are declared specifically by this command (not inherited).
58 lflags *flag.FlagSet

Organize the files a bit betterspf13before adoption62fb674

lines 59–61why, one step back
59 // Run runs the command.
60 // The args are the arguments after the command name.61 Run func(cmd *Command, args []string)

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

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

Organize the files a bit betterspf13before adoption62fb674

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

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

line 65why, one step back
65 parent *Command

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 66–68why, one step back
66 // max lengths of commands' string lengths for use in padding
67 commandsMaxUseLen int68 commandsMaxCommandPathLen int

help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24

line 69why, one step back
69 commandsMaxNameLen int

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

line 70why, one step back
70

Organize the files a bit betterspf13before adoption62fb674

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

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b

line 72why, one step back
72 cmdErrorBuf *bytes.Buffer

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

line 73why, one step back
73

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 74why, one step back
74 args []string // actual args parsed from flags

Documentation updatespf13before adoption59bd285

line 75why, one step back
75 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 76–80why, one step back
76 usageFunc func(*Command) error // Usage can be defined by application
77 usageTemplate string // Can be defined by Application78 helpTemplate string // Can be defined by Application79 helpFunc func(*Command, []string) // Help can be defined by application80 helpCommand *Command // The help command

Adding support for --helpspf13before adoption07be814

line 81why, one step back
81 helpFlagVal bool

Organize the files a bit betterspf13before adoption62fb674

lines 82–83why, one step back
82}
83

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

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

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 88–89why, one step back
88}
89

Default usage output to stdoutEric Parisbefore adoption6de96b8

line 90why, one step back
90func (c *Command) getOut(def io.Writer) io.Writer {

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

lines 91–97why, one step back
91 if c.output != nil {
92 return *c.output93 }9495 if c.HasParent() {96 return c.parent.Out()97 } else {

Default usage output to stdoutEric Parisbefore adoption6de96b8

line 98why, one step back
98 return def

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

lines 99–101why, one step back
99 }
100}101

Default usage output to stdoutEric Parisbefore adoption6de96b8

lines 102–109why, one step back
102func (c *Command) Out() io.Writer {
103 return c.getOut(os.Stderr)104}105106func (c *Command) getOutOrStdout() io.Writer {107 return c.getOut(os.Stdout)108}109

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

lines 110–164why, one step back
110// SetOutput sets the destination for usage and error messages.
111// If output is nil, os.Stderr is used.112func (c *Command) SetOutput(output io.Writer) {113 c.output = &output114}115116// Usage can be defined by application117func (c *Command) SetUsageFunc(f func(*Command) error) {118 c.usageFunc = f119}120121// Can be defined by Application122func (c *Command) SetUsageTemplate(s string) {123 c.usageTemplate = s124}125126// Can be defined by Application127func (c *Command) SetHelpFunc(f func(*Command, []string)) {128 c.helpFunc = f129}130131func (c *Command) SetHelpCommand(cmd *Command) {132 c.helpCommand = cmd133}134135// Can be defined by Application136func (c *Command) SetHelpTemplate(s string) {137 c.helpTemplate = s138}139140func (c *Command) UsageFunc() (f func(*Command) error) {141 if c.usageFunc != nil {142 return c.usageFunc143 }144145 if c.HasParent() {146 return c.parent.UsageFunc()147 } else {148 return func(c *Command) error {149 err := tmpl(c.Out(), c.UsageTemplate(), c)150 return err151 }152 }153}154func (c *Command) HelpFunc() func(*Command, []string) {155 if c.helpFunc != nil {156 return c.helpFunc157 }158159 if c.HasParent() {160 return c.parent.HelpFunc()161 } else {162 return func(c *Command, args []string) {163 if len(args) == 0 {164 // Help called without any topic, calling on root

Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f

line 165why, one step back
165 c.Root().Help()

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

lines 166–183why, one step back
166 return
167 }168169 cmd, _, e := c.Root().Find(args)170 if cmd == nil || e != nil {171 c.Printf("Unknown help topic %#q.", args)172173 c.Root().Usage()174 } else {175 err := cmd.Help()176 if err != nil {177 c.Println(err)178 }179 }180 }181 }182}183

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 184–195why, one step back
184var minUsagePadding int = 25
185186func (c *Command) UsagePadding() int {187 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {188 return minUsagePadding189 } else {190 return c.parent.commandsMaxUseLen191 }192}193194var minCommandPathPadding int = 11195

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 196why, one step back
196//

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 197–204why, one step back
197func (c *Command) CommandPathPadding() int {
198 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {199 return minCommandPathPadding200 } else {201 return c.parent.commandsMaxCommandPathLen202 }203}204

help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24

lines 205–214why, one step back
205var minNamePadding int = 11
206207func (c *Command) NamePadding() int {208 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {209 return minNamePadding210 } else {211 return c.parent.commandsMaxNameLen212 }213}214

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

lines 215–225why, one step back
215func (c *Command) UsageTemplate() string {
216 if c.usageTemplate != "" {217 return c.usageTemplate218 }219220 if c.HasParent() {221 return c.parent.UsageTemplate()222 } else {223 return `{{ $cmd := . }}224Usage: {{if .Runnable}}225 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 226–228why, one step back
226 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
227228Aliases:

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 229–230why, one step back
229 {{.NameAndAliases}}
230{{end}}{{if .HasExample}}

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 231why, one step back
231

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 232–233why, one step back
232Examples:
233{{ .Example }}

Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177

line 234why, one step back
234{{end}}{{ if .HasRunnableSubCommands}}

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 235why, one step back
235

Deprecated subcommandsEric Parisbefore adoptionc3e48f9

line 236why, one step back
236Available Commands: {{range .Commands}}{{if and (.Runnable) (not .Deprecated)}}

help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24

line 237why, one step back
237 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}

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

line 238why, one step back
238{{end}}

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 239–240why, one step back
239{{ if .HasLocalFlags}}Flags:
240{{.LocalFlags.FlagUsages}}{{end}}

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 241why, one step back
241{{ if .HasInheritedFlags}}Global Flags:

Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177

line 242why, one step back
242{{.InheritedFlags.FlagUsages}}{{end}}{{if or (.HasHelpSubCommands) (.HasRunnableSiblings)}}

Merge pull request #88 from eparis/subhelptestEric Parisbefore adoptionb78326b

line 243why, one step back
243Additional help topics:

Deprecated subcommandsEric Parisbefore adoptionc3e48f9

line 244why, one step back
244{{if .HasHelpSubCommands}}{{range .Commands}}{{if and (not .Runnable) (not .Deprecated)}} {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasRunnableSiblings }}{{range .Parent.Commands}}{{if and (not .Runnable) (not .Deprecated)}}{{if not (eq .Name $cmd.Name) }}

Remove "::" from output. Fixed #4spf13before adoption1a6c5d1

line 245why, one step back
245 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{end}}

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

line 246why, one step back
246{{end}}{{ if .HasSubCommands }}

Minor English correctionKartik Singhalbefore adoptionc36f627

line 247why, one step back
247Use "{{.Root.Name}} help [command]" for more information about a command.

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

line 248why, one step back
248{{end}}`

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

lines 249–259why, one step back
249 }
250}251252func (c *Command) HelpTemplate() string {253 if c.helpTemplate != "" {254 return c.helpTemplate255 }256257 if c.HasParent() {258 return c.parent.HelpTemplate()259 } else {

Help uses Short message if Long is not availableEdgard Castrobefore adoption384c059

line 260why, one step back
260 return `{{with or .Long .Short }}{{. | trim}}{{end}}

Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f

line 261why, one step back
261{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}

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

lines 262–265why, one step back
262`
263 }264}265

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 266–272why, one step back
266// Really only used when casting a command to a commander
267func (c *Command) resetChildrensParents() {268 for _, x := range c.commands {269 x.parent = c270 }271}272

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

lines 273–283why, one step back
273// Test if the named flag is a boolean flag.
274func isBooleanFlag(name string, f *flag.FlagSet) bool {275 flag := f.Lookup(name)276 if flag == nil {277 return false278 }279 return flag.Value.Type() == "bool"280}281282// Test if the named flag is a boolean flag.283func isBooleanShortFlag(name string, f *flag.FlagSet) bool {

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

lines 284–289why, one step back
284 result := false
285 f.VisitAll(func(f *flag.Flag) {286 if f.Shorthand == name && f.Value.Type() == "bool" {287 result = true288 }289 })

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

lines 290–293why, one step back
290 return result
291}292293func stripFlags(args []string, c *Command) []string {

Support for flags before commandsspf13before adoption10a8494

lines 294–296why, one step back
294 if len(args) < 1 {
295 return args296 }

Merge pull request #70 from brendandburns/masterBjørn Erik Pedersenbefore adoption6264dc6

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

Support for flags before commandsspf13before adoption10a8494

lines 298–301why, one step back
298
299 commands := []string{}300301 inQuote := false

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

line 302why, one step back
302 inFlag := false

Support for flags before commandsspf13before adoption10a8494

lines 303–309why, one step back
303 for _, y := range args {
304 if !inQuote {305 switch {306 case strings.HasPrefix(y, "\""):307 inQuote = true308 case strings.Contains(y, "=\""):309 inQuote = true

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

lines 310–316why, one step back
310 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
311 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'312 inFlag = !isBooleanFlag(y[2:], c.Flags())313 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):314 inFlag = true315 case inFlag:316 inFlag = false

Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1

lines 317–318why, one step back
317 case y == "":
318 // strip empty commands, as the go tests expect this to be ok....

Support for flags before commandsspf13before adoption10a8494

lines 319–320why, one step back
319 case !strings.HasPrefix(y, "-"):
320 commands = append(commands, y)

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

line 321why, one step back
321 inFlag = false

Support for flags before commandsspf13before adoption10a8494

lines 322–332why, one step back
322 }
323 }324325 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {326 inQuote = false327 }328 }329330 return commands331}332

Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555

lines 333–341why, one step back
333// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
334// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).335func argsMinusFirstX(args []string, x string) []string {336 for i, y := range args {337 if x == y {338 ret := []string{}339 ret = append(ret, args[:i]...)340 ret = append(ret, args[i+1:]...)341 return ret

Support for flags before commandsspf13before adoption10a8494

lines 342–343why, one step back
342 }
343 }

Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555

line 344why, one step back
344 return args

Support for flags before commandsspf13before adoption10a8494

lines 345–346why, one step back
345}
346

Organize the files a bit betterspf13before adoption62fb674

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

Add support for help commandspf13before adoptionfb2146e

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

Finding command based on args cleaned upspf13before adoption55ff474

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

Organize the files a bit betterspf13before adoption62fb674

lines 350–353why, one step back
350 if c == nil {
351 return nil, nil, fmt.Errorf("Called find() on a nil Command")352 }353

Finding command based on args cleaned upspf13before adoption55ff474

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

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

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

Finding command based on args cleaned upspf13before adoption55ff474

lines 356–361why, one step back
356 }
357358 var innerfind func(*Command, []string) (*Command, []string)359360 innerfind = func(c *Command, args []string) (*Command, []string) {361 if len(args) > 0 && c.HasSubCommands() {

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

line 362why, one step back
362 argsWOflags := stripFlags(args, c)

Support for flags before commandsspf13before adoption10a8494

line 363why, one step back
363 if len(argsWOflags) > 0 {

adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac

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

Support for flags before commandsspf13before adoption10a8494

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

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

line 366why, one step back
366 if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match

Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555

line 367why, one step back
367 return innerfind(cmd, argsMinusFirstX(args, argsWOflags[0]))

Making prefix matching opt in.spf13before adoptionb1e90a7

line 368why, one step back
368 } else if EnablePrefixMatching {

adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac

lines 369–376why, one step back
369 if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match
370 matches = append(matches, cmd)371 }372 for _, x := range cmd.Aliases {373 if strings.HasPrefix(x, argsWOflags[0]) {374 matches = append(matches, cmd)375 }376 }

Support for flags before commandsspf13before adoption10a8494

line 377why, one step back
377 }

adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac

lines 378–381why, one step back
378 }
379380 // only accept a single prefix match - multiple matches would be ambiguous381 if len(matches) == 1 {

Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555

line 382why, one step back
382 return innerfind(matches[0], argsMinusFirstX(args, argsWOflags[0]))

Finding command based on args cleaned upspf13before adoption55ff474

line 383why, one step back
383 }

Organize the files a bit betterspf13before adoption62fb674

lines 384–385why, one step back
384 }
385 }

Finding command based on args cleaned upspf13before adoption55ff474

lines 386–387why, one step back
386
387 return c, args

Organize the files a bit betterspf13before adoption62fb674

line 388why, one step back
388 }

Finding command based on args cleaned upspf13before adoption55ff474

lines 389–391why, one step back
389
390 commandFound, a := innerfind(c, arrs)391

Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1

lines 392–393why, one step back
392 // If we matched on the root, but we asked for a subcommand, return an error
393 if commandFound.Name() == c.Name() && len(stripFlags(arrs, c)) > 0 && commandFound.Name() != arrs[0] {

Merge pull request #83 from adammck/fix_double_output_on_unknown_commandEric Parisbefore adoption09b49c3

line 394why, one step back
394 return nil, a, fmt.Errorf("unknown command %q", a[0])

Organize the files a bit betterspf13before adoption62fb674

lines 395–396why, one step back
395 }
396

Finding command based on args cleaned upspf13before adoption55ff474

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

Organize the files a bit betterspf13before adoption62fb674

lines 398–399why, one step back
398}
399

Add support for help commandspf13before adoptionfb2146e

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

Organize the files a bit betterspf13before adoption62fb674

lines 401–409why, one step back
401 var findRoot func(*Command) *Command
402403 findRoot = func(x *Command) *Command {404 if x.HasParent() {405 return findRoot(x.parent)406 } else {407 return x408 }409 }

Add support for help commandspf13before adoptionfb2146e

lines 410–413why, one step back
410
411 return findRoot(c)412}413

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

line 414why, one step back
414func (c *Command) execute(a []string) (err error) {

Organize the files a bit betterspf13before adoption62fb674

lines 415–416why, one step back
415 if c == nil {
416 return fmt.Errorf("Called Execute() on a nil Command")

Deprecated subcommandsEric Parisbefore adoptionc3e48f9

lines 417–420why, one step back
417 }
418419 if len(c.Deprecated) > 0 {420 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)

Organize the files a bit betterspf13before adoption62fb674

lines 421–422why, one step back
421 }
422

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

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

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

lines 424–427why, one step back
424 if err == flag.ErrHelp {
425 c.Help()426 return nil427 }

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

line 428why, one step back
428 if err != nil {

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b

line 429why, one step back
429 // We're writing subcommand usage to root command's error buffer to have it displayed to the user

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9

lines 430–432why, one step back
430 r := c.Root()
431 if r.cmdErrorBuf == nil {432 r.cmdErrorBuf = new(bytes.Buffer)

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b

lines 433–434why, one step back
433 }
434 // for writing the usage to the buffer we need to switch the output temporarily

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9

lines 435–437why, one step back
435 // since Out() returns root output, you also need to revert that on root
436 out := r.Out()437 r.SetOutput(r.cmdErrorBuf)

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b

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

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9

line 439why, one step back
439 r.SetOutput(out)

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

lines 440–441why, one step back
440 return err
441 } else {

In execute(), check if command is Runnable()Anthony Fokbefore adoption4745f1f

lines 442–444why, one step back
442 // If help is called, regardless of other flags, we print that.
443 // Print help also if c.Run is nil.444 if c.helpFlagVal || !c.Runnable() {

Adding support for --helpspf13before adoption07be814

lines 445–448why, one step back
445 c.Help()
446 return nil447 }448

Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3

line 449why, one step back
449 c.preRun()

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

lines 450–452why, one step back
450 argWoFlags := c.Flags().Args()
451 c.Run(c, argWoFlags)452 return nil

Organize the files a bit betterspf13before adoption62fb674

lines 453–455why, one step back
453 }
454}455

Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3

line 456why, one step back
456func (c *Command) preRun() {

Adding "OnInitialize()" method instead of directly setting a property. Now can have multiple initializers.spf13before adoption864687a

lines 457–459why, one step back
457 for _, x := range initializers {
458 x()459 }

Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3

lines 460–461why, one step back
460}
461

Support for flags before commandsspf13before adoption10a8494

lines 462–473why, one step back
462func (c *Command) errorMsgFromParse() string {
463 s := c.flagErrorBuf.String()464465 x := strings.Split(s, "\n")466467 if len(x) > 0 {468 return x[0]469 } else {470 return ""471 }472}473

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

lines 474–481why, one step back
474// Call execute to use the args (os.Args[1:] by default)
475// and run through the command tree finding appropriate matches476// for commands and then corresponding flags.477func (c *Command) Execute() (err error) {478479 // Regardless of what command execute is called on, run on Root only480 if c.HasParent() {481 return c.Root().Execute()

Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29

lines 482–489why, one step back
482 }
483484 if EnableWindowsMouseTrap && runtime.GOOS == "windows" {485 if mousetrap.StartedByExplorer() {486 c.Print(MousetrapHelpText)487 time.Sleep(5 * time.Second)488 os.Exit(1)489 }

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

lines 490–508why, one step back
490 }
491492 // initialize help as the last point possible to allow for user493 // overriding494 c.initHelp()495496 var args []string497498 if len(c.args) == 0 {499 args = os.Args[1:]500 } else {501 args = c.args502 }503504 if len(args) == 0 {505 // Only the executable is called and the root is runnable, run it506 if c.Runnable() {507 err = c.execute([]string(nil))508 } else {

Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f

line 509why, one step back
509 c.Help()

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

lines 510–511why, one step back
510 }
511 } else {

Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1

line 512why, one step back
512 cmd, flags, e := c.Find(args)

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

line 513why, one step back
513 if e != nil {

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e

line 514why, one step back
514 err = e

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

line 515why, one step back
515 } else {

Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1

line 516why, one step back
516 err = cmd.execute(flags)

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

lines 517–520why, one step back
517 }
518 }519520 if err != nil {

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

lines 521–522why, one step back
521 if err == flag.ErrHelp {
522 c.Help()

Merge pull request #83 from adammck/fix_double_output_on_unknown_commandEric Parisbefore adoption09b49c3

line 523why, one step back
523

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

lines 524–525why, one step back
524 } else {
525 c.Println("Error:", err.Error())

Merge pull request #83 from adammck/fix_double_output_on_unknown_commandEric Parisbefore adoption09b49c3

line 526why, one step back
526 c.Printf("Run '%v help' for usage.\n", c.Root().Name())

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

line 527why, one step back
527 }

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

lines 528–534why, one step back
528 }
529530 return531}532533func (c *Command) initHelp() {534 if c.helpCommand == nil {

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

lines 535–538why, one step back
535 if !c.HasSubCommands() {
536 return537 }538

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

lines 539–549why, one step back
539 c.helpCommand = &Command{
540 Use: "help [command]",541 Short: "Help about any command",542 Long: `Help provides help for any command in the application.543 Simply type ` + c.Name() + ` help [path to command] for full details.`,544 Run: c.HelpFunc(),545 }546 }547 c.AddCommand(c.helpCommand)548}549

Organize the files a bit betterspf13before adoption62fb674

lines 550–552why, one step back
550// Used for testing
551func (c *Command) ResetCommands() {552 c.commands = nil

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

line 553why, one step back
553 c.helpCommand = nil

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9

lines 554–555why, one step back
554 c.cmdErrorBuf = new(bytes.Buffer)
555 c.cmdErrorBuf.Reset()

Organize the files a bit betterspf13before adoption62fb674

lines 556–557why, one step back
556}
557

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 558why, one step back
558//Commands returns a slice of child commands.

Organize the files a bit betterspf13before adoption62fb674

lines 559–562why, one step back
559func (c *Command) Commands() []*Command {
560 return c.commands561}562

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 563why, one step back
563// AddCommand adds one or more commands to this parent command.

Organize the files a bit betterspf13before adoption62fb674

lines 564–569why, one step back
564func (c *Command) AddCommand(cmds ...*Command) {
565 for i, x := range cmds {566 if cmds[i] == c {567 panic("Command can't be a child of itself")568 }569 cmds[i].parent = c

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 570–577why, one step back
570 // update max lengths
571 usageLen := len(x.Use)572 if usageLen > c.commandsMaxUseLen {573 c.commandsMaxUseLen = usageLen574 }575 commandPathLen := len(x.CommandPath())576 if commandPathLen > c.commandsMaxCommandPathLen {577 c.commandsMaxCommandPathLen = commandPathLen

help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24

lines 578–581why, one step back
578 }
579 nameLen := len(x.Name())580 if nameLen > c.commandsMaxNameLen {581 c.commandsMaxNameLen = nameLen

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

line 582why, one step back
582 }

Organize the files a bit betterspf13before adoption62fb674

lines 583–586why, one step back
583 c.commands = append(c.commands, x)
584 }585}586

Add Command's RemoveCommand methodÉtienne Vallette d'Osiabefore adoptionf479c92

lines 587–620why, one step back
587// AddCommand removes one or more commands from a parent command.
588func (c *Command) RemoveCommand(cmds ...*Command) {589 commands := []*Command{}590main:591 for _, command := range c.commands {592 for _, cmd := range cmds {593 if command == cmd {594 command.parent = nil595 continue main596 }597 }598 commands = append(commands, command)599 }600 c.commands = commands601 // recompute all lengths602 c.commandsMaxUseLen = 0603 c.commandsMaxCommandPathLen = 0604 c.commandsMaxNameLen = 0605 for _, command := range c.commands {606 usageLen := len(command.Use)607 if usageLen > c.commandsMaxUseLen {608 c.commandsMaxUseLen = usageLen609 }610 commandPathLen := len(command.CommandPath())611 if commandPathLen > c.commandsMaxCommandPathLen {612 c.commandsMaxCommandPathLen = commandPathLen613 }614 nameLen := len(command.Name())615 if nameLen > c.commandsMaxNameLen {616 c.commandsMaxNameLen = nameLen617 }618 }619}620

Organize the files a bit betterspf13before adoption62fb674

lines 621–622why, one step back
621// Convenience method to Print to the defined output
622func (c *Command) Print(i ...interface{}) {

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

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

Organize the files a bit betterspf13before adoption62fb674

lines 624–639why, one step back
624}
625626// Convenience method to Println to the defined output627func (c *Command) Println(i ...interface{}) {628 str := fmt.Sprintln(i...)629 c.Print(str)630}631632// Convenience method to Printf to the defined output633func (c *Command) Printf(format string, i ...interface{}) {634 str := fmt.Sprintf(format, i...)635 c.Print(str)636}637638// Output the usage for the command639// Used when a user provides invalid input

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

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

Organize the files a bit betterspf13before adoption62fb674

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

Help improvementsspf13before adoption2d02c31

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

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

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

Help improvementsspf13before adoption2d02c31

lines 644–651why, one step back
644 return err
645}646647// Output the help for the command648// Used when a user calls help [command]649// by the default HelpFunc in the commander650func (c *Command) Help() error {651 c.mergePersistentFlags()

Default usage output to stdoutEric Parisbefore adoption6de96b8

line 652why, one step back
652 err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)

Organize the files a bit betterspf13before adoption62fb674

lines 653–655why, one step back
653 return err
654}655

fix trailing <nil> on help outputspf13before adoption3958385

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

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

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

fix trailing <nil> on help outputspf13before adoption3958385

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

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

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

fix trailing <nil> on help outputspf13before adoption3958385

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

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

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

fix trailing <nil> on help outputspf13before adoption3958385

lines 662–664why, one step back
662 return bb.String()
663}664

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 665why, one step back
665// CommandPath returns the full path to this command.

Organize the files a bit betterspf13before adoption62fb674

lines 666–740why, one step back
666func (c *Command) CommandPath() string {
667 str := c.Name()668 x := c669 for x.HasParent() {670 str = x.parent.Name() + " " + str671 x = x.parent672 }673 return str674}675676//The full usage for a given command (including parents)677func (c *Command) UseLine() string {678 str := ""679 if c.HasParent() {680 str = c.parent.CommandPath() + " "681 }682 return str + c.Use683}684685// For use in determining which flags have been assigned to which commands686// and which persist687func (c *Command) DebugFlags() {688 c.Println("DebugFlags called on", c.Name())689 var debugflags func(*Command)690691 debugflags = func(x *Command) {692 if x.HasFlags() || x.HasPersistentFlags() {693 c.Println(x.Name())694 }695 if x.HasFlags() {696 x.flags.VisitAll(func(f *flag.Flag) {697 if x.HasPersistentFlags() {698 if x.persistentFlag(f.Name) == nil {699 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")700 } else {701 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")702 }703 } else {704 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")705 }706 })707 }708 if x.HasPersistentFlags() {709 x.pflags.VisitAll(func(f *flag.Flag) {710 if x.HasFlags() {711 if x.flags.Lookup(f.Name) == nil {712 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")713 }714 } else {715 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")716 }717 })718 }719 c.Println(x.flagErrorBuf)720 if x.HasSubCommands() {721 for _, y := range x.commands {722 debugflags(y)723 }724 }725 }726727 debugflags(c)728}729730// Name returns the command's name: the first word in the use line.731func (c *Command) Name() string {732 if c.name != "" {733 return c.name734 }735 name := c.Use736 i := strings.Index(name, " ")737 if i >= 0 {738 name = name[:i]739 }740 return name

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 741–754why, one step back
741}
742743// Determine if a given string is an alias of the command.744func (c *Command) HasAlias(s string) bool {745 for _, a := range c.Aliases {746 if a == s {747 return true748 }749 }750 return false751}752753func (c *Command) NameAndAliases() string {754 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 755–758why, one step back
755}
756757func (c *Command) HasExample() bool {758 return len(c.Example) > 0

Organize the files a bit betterspf13before adoption62fb674

lines 759–768why, one step back
759}
760761// Determine if the command is itself runnable762func (c *Command) Runnable() bool {763 return c.Run != nil764}765766// Determine if the command has children commands767func (c *Command) HasSubCommands() bool {768 return len(c.commands) > 0

Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177

lines 769–799why, one step back
769}
770771func (c *Command) HasRunnableSiblings() bool {772 if !c.HasParent() {773 return false774 }775 for _, sub := range c.parent.commands {776 if sub.Runnable() {777 return true778 }779 }780 return false781}782783func (c *Command) HasHelpSubCommands() bool {784 for _, sub := range c.commands {785 if !sub.Runnable() {786 return true787 }788 }789 return false790}791792// Determine if the command has runnable children commands793func (c *Command) HasRunnableSubCommands() bool {794 for _, sub := range c.commands {795 if sub.Runnable() {796 return true797 }798 }799 return false

Organize the files a bit betterspf13before adoption62fb674

lines 800–806why, one step back
800}
801802// Determine if the command is a child command803func (c *Command) HasParent() bool {804 return c.parent != nil805}806

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 807why, one step back
807// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)

Organize the files a bit betterspf13before adoption62fb674

lines 808–814why, one step back
808func (c *Command) Flags() *flag.FlagSet {
809 if c.flags == nil {810 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)811 if c.flagErrorBuf == nil {812 c.flagErrorBuf = new(bytes.Buffer)813 }814 c.flags.SetOutput(c.flagErrorBuf)

changed help flag setup to use PersistenFlags so -h will be supportedJoel Scoblebefore adoption83b58a2

line 815why, one step back
815 c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name())

Organize the files a bit betterspf13before adoption62fb674

lines 816–819why, one step back
816 }
817 return c.flags818}819

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 820–824why, one step back
820// Get the local FlagSet specifically set in the current command
821func (c *Command) LocalFlags() *flag.FlagSet {822 c.mergePersistentFlags()823824 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 825–826why, one step back
825 c.lflags.VisitAll(func(f *flag.Flag) {
826 local.AddFlag(f)

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 827–830why, one step back
827 })
828 return local829}830

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

lines 831–834why, one step back
831// All Flags which were inherited from parents commands
832func (c *Command) InheritedFlags() *flag.FlagSet {833 c.mergePersistentFlags()834

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 835–836why, one step back
835 inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
836 local := c.LocalFlags()

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

line 837why, one step back
837

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 838why, one step back
838 var rmerge func(x *Command)

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

line 839why, one step back
839

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 840–851why, one step back
840 rmerge = func(x *Command) {
841 if x.HasPersistentFlags() {842 x.PersistentFlags().VisitAll(func(f *flag.Flag) {843 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {844 inherited.AddFlag(f)845 }846 })847 }848 if x.HasParent() {849 rmerge(x.parent)850 }851 }

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

lines 852–856why, one step back
852
853 if c.HasParent() {854 rmerge(c.parent)855 }856

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 857why, one step back
857 return inherited

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

lines 858–859why, one step back
858}
859

new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5

lines 860–861why, one step back
860// All Flags which were not inherited from parent commands
861func (c *Command) NonInheritedFlags() *flag.FlagSet {

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 862why, one step back
862 return c.LocalFlags()

new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5

lines 863–864why, one step back
863}
864

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 865why, one step back
865// Get the Persistent FlagSet specifically set in the current command

Organize the files a bit betterspf13before adoption62fb674

lines 866–886why, one step back
866func (c *Command) PersistentFlags() *flag.FlagSet {
867 if c.pflags == nil {868 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)869 if c.flagErrorBuf == nil {870 c.flagErrorBuf = new(bytes.Buffer)871 }872 c.pflags.SetOutput(c.flagErrorBuf)873 }874 return c.pflags875}876877// For use in testing878func (c *Command) ResetFlags() {879 c.flagErrorBuf = new(bytes.Buffer)880 c.flagErrorBuf.Reset()881 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)882 c.flags.SetOutput(c.flagErrorBuf)883 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)884 c.pflags.SetOutput(c.flagErrorBuf)885}886

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 887why, one step back
887// Does the command contain any flags (local plus persistent from the entire structure)

Organize the files a bit betterspf13before adoption62fb674

lines 888–896why, one step back
888func (c *Command) HasFlags() bool {
889 return c.Flags().HasFlags()890}891892// Does the command contain persistent flags893func (c *Command) HasPersistentFlags() bool {894 return c.PersistentFlags().HasFlags()895}896

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 897–901why, one step back
897// Does the command has flags specifically declared locally
898func (c *Command) HasLocalFlags() bool {899 return c.LocalFlags().HasFlags()900}901

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 902–905why, one step back
902func (c *Command) HasInheritedFlags() bool {
903 return c.InheritedFlags().HasFlags()904}905

Organize the files a bit betterspf13before adoption62fb674

lines 906–932why, one step back
906// Climbs up the command tree looking for matching flag
907func (c *Command) Flag(name string) (flag *flag.Flag) {908 flag = c.Flags().Lookup(name)909910 if flag == nil {911 flag = c.persistentFlag(name)912 }913914 return915}916917// recursively find matching persistent flag918func (c *Command) persistentFlag(name string) (flag *flag.Flag) {919 if c.HasPersistentFlags() {920 flag = c.PersistentFlags().Lookup(name)921 }922923 if flag == nil && c.HasParent() {924 flag = c.parent.persistentFlag(name)925 }926 return927}928929// Parses persistent flag tree & local flags930func (c *Command) ParseFlags(args []string) (err error) {931 c.mergePersistentFlags()932 err = c.Flags().Parse(args)

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e

line 933why, one step back
933 return

Organize the files a bit betterspf13before adoption62fb674

lines 934–935why, one step back
934}
935

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 936–939why, one step back
936func (c *Command) Parent() *Command {
937 return c.parent938}939

Organize the files a bit betterspf13before adoption62fb674

lines 940–942why, one step back
940func (c *Command) mergePersistentFlags() {
941 var rmerge func(x *Command)942

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 943–955why, one step back
943 // Save the set of local flags
944 if c.lflags == nil {945 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)946 if c.flagErrorBuf == nil {947 c.flagErrorBuf = new(bytes.Buffer)948 }949 c.lflags.SetOutput(c.flagErrorBuf)950 addtolocal := func(f *flag.Flag) {951 c.lflags.AddFlag(f)952 }953 c.Flags().VisitAll(addtolocal)954 c.PersistentFlags().VisitAll(addtolocal)955 }

Organize the files a bit betterspf13before adoption62fb674

lines 956–970why, one step back
956 rmerge = func(x *Command) {
957 if x.HasPersistentFlags() {958 x.PersistentFlags().VisitAll(func(f *flag.Flag) {959 if c.Flags().Lookup(f.Name) == nil {960 c.Flags().AddFlag(f)961 }962 })963 }964 if x.HasParent() {965 rmerge(x.parent)966 }967 }968969 rmerge(c)970}