Skip to content
Myr

command.go

This file

Path

command.go

1,197 lines · 31.1 KiB · Go

Last changed by

always show help if requested, even if SilenceErrors is enabledSascha Holzleiterbefore adoption2bd8a73

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–21why, one step back
16package cobra
1718import (19 "bytes"20 "fmt"21 "io"

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

line 22why, one step back
22 "os"

Limit the verbose test workaround to "cobra.test" onlyAnthony Fokbefore adoptione576205

line 23why, one step back
23 "path/filepath"

Organize the files a bit betterspf13before adoption62fb674

line 24why, one step back
24 "strings"

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Organize the files a bit betterspf13before adoption62fb674

lines 27–37why, 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 string

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

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

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

lines 40–41why, one step back
40 // An array of command names for which this command will be suggested - similar to aliases but only suggests.
41 SuggestFor []string

Organize the files a bit betterspf13before adoption62fb674

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

New "example" section of commandsEric Parisbefore adoptionbf480fe

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

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

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

Merge pull request #90 from eparis/deprecated-subcommandsEric Parisbefore adoption9cf0f37

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

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 54–55why, one step back
54 // Is this command hidden and should NOT show up in the list of available commands?
55 Hidden bool

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

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

Organize the files a bit betterspf13before adoption62fb674

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

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

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

Organize the files a bit betterspf13before adoption62fb674

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

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e

lines 62–65why, one step back
62 // SilenceErrors is an option to quiet errors down stream
63 SilenceErrors bool64 // Silence Usage is an option to silence usage when an error occurs.65 SilenceUsage bool

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

lines 66–74why, one step back
66 // The *Run functions are executed in the following order:
67 // * PersistentPreRun()68 // * PreRun()69 // * Run()70 // * PostRun()71 // * PersistentPostRun()72 // All functions get the same args, the arguments after the command name73 // PersistentPreRun: children of this command will inherit and execute74 PersistentPreRun func(cmd *Command, args []string)

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 75–76why, one step back
75 // PersistentPreRunE: PersistentPreRun but returns an error
76 PersistentPreRunE func(cmd *Command, args []string) error

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

lines 77–78why, one step back
77 // PreRun: children of this command will not inherit.
78 PreRun func(cmd *Command, args []string)

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 79–80why, one step back
79 // PreRunE: PreRun but returns an error
80 PreRunE func(cmd *Command, args []string) error

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

line 81why, one step back
81 // Run: Typically the actual work function. Most commands will only implement this

Organize the files a bit betterspf13before adoption62fb674

line 82why, one step back
82 Run func(cmd *Command, args []string)

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 83–84why, one step back
83 // RunE: Run but returns an error
84 RunE func(cmd *Command, args []string) error

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

lines 85–86why, one step back
85 // PostRun: run after the Run command.
86 PostRun func(cmd *Command, args []string)

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 87–88why, one step back
87 // PostRunE: PostRun but returns an error
88 PostRunE func(cmd *Command, args []string) error

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

lines 89–90why, one step back
89 // PersistentPostRun: children of this command will inherit and execute after PostRun
90 PersistentPostRun func(cmd *Command, args []string)

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 91–92why, one step back
91 // PersistentPostRunE: PersistentPostRun but returns an error
92 PersistentPostRunE func(cmd *Command, args []string) error

add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a

lines 93–94why, one step back
93 // DisableAutoGenTag remove
94 DisableAutoGenTag bool

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

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

Organize the files a bit betterspf13before adoption62fb674

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

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

line 98why, one step back
98 parent *Command

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 99–101why, one step back
99 // max lengths of commands' string lengths for use in padding
100 commandsMaxUseLen int101 commandsMaxCommandPathLen int

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

line 102why, one step back
102 commandsMaxNameLen int

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

line 103why, one step back
103

Organize the files a bit betterspf13before adoption62fb674

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

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

line 105why, one step back
105

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Documentation updatespf13before adoption59bd285

line 107why, one step back
107 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 108–112why, one step back
108 usageFunc func(*Command) error // Usage can be defined by application
109 usageTemplate string // Can be defined by Application110 helpTemplate string // Can be defined by Application111 helpFunc func(*Command, []string) // Help can be defined by application112 helpCommand *Command // The help command

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

lines 113–114why, one step back
113 // The global normalization function that we can use on every pFlag set and children commands
114 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName

Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311

lines 115–119why, one step back
115
116 // Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages117 DisableSuggestions bool118 // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0119 SuggestionsMinimumDistance int

Organize the files a bit betterspf13before adoption62fb674

lines 120–121why, one step back
120}
121

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

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

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 126–127why, one step back
126}
127

Default usage output to stdoutEric Parisbefore adoption6de96b8

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

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

lines 129–135why, one step back
129 if c.output != nil {
130 return *c.output131 }132133 if c.HasParent() {134 return c.parent.Out()135 } else {

Default usage output to stdoutEric Parisbefore adoption6de96b8

line 136why, one step back
136 return def

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

lines 137–139why, one step back
137 }
138}139

Default usage output to stdoutEric Parisbefore adoption6de96b8

lines 140–147why, one step back
140func (c *Command) Out() io.Writer {
141 return c.getOut(os.Stderr)142}143144func (c *Command) getOutOrStdout() io.Writer {145 return c.getOut(os.Stdout)146}147

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

lines 148–177why, one step back
148// SetOutput sets the destination for usage and error messages.
149// If output is nil, os.Stderr is used.150func (c *Command) SetOutput(output io.Writer) {151 c.output = &output152}153154// Usage can be defined by application155func (c *Command) SetUsageFunc(f func(*Command) error) {156 c.usageFunc = f157}158159// Can be defined by Application160func (c *Command) SetUsageTemplate(s string) {161 c.usageTemplate = s162}163164// Can be defined by Application165func (c *Command) SetHelpFunc(f func(*Command, []string)) {166 c.helpFunc = f167}168169func (c *Command) SetHelpCommand(cmd *Command) {170 c.helpCommand = cmd171}172173// Can be defined by Application174func (c *Command) SetHelpTemplate(s string) {175 c.helpTemplate = s176}177

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

lines 178–189why, one step back
178// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
179// The user should not have a cyclic dependency on commands.180func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {181 c.Flags().SetNormalizeFunc(n)182 c.PersistentFlags().SetNormalizeFunc(n)183 c.globNormFunc = n184185 for _, command := range c.commands {186 command.SetGlobalNormalizationFunc(n)187 }188}189

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

lines 190–199why, one step back
190func (c *Command) UsageFunc() (f func(*Command) error) {
191 if c.usageFunc != nil {192 return c.usageFunc193 }194195 if c.HasParent() {196 return c.parent.UsageFunc()197 } else {198 return func(c *Command) error {199 err := tmpl(c.Out(), c.UsageTemplate(), c)

Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7

lines 200–202why, one step back
200 if err != nil {
201 fmt.Print(err)202 }

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

lines 203–206why, one step back
203 return err
204 }205 }206}

Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170

lines 207–209why, one step back
207
208// HelpFunc returns either the function set by SetHelpFunc for this command209// or a parent, or it returns a function which calls c.Help()

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

line 210why, one step back
210func (c *Command) HelpFunc() func(*Command, []string) {

Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170

lines 211–216why, one step back
211 cmd := c
212 for cmd != nil {213 if cmd.helpFunc != nil {214 return cmd.helpFunc215 }216 cmd = cmd.parent

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

line 217why, one step back
217 }

Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170

lines 218–221why, one step back
218 return func(*Command, []string) {
219 err := c.Help()220 if err != nil {221 c.Println(err)

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

lines 222–225why, one step back
222 }
223 }224}225

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 226–237why, one step back
226var minUsagePadding int = 25
227228func (c *Command) UsagePadding() int {229 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {230 return minUsagePadding231 } else {232 return c.parent.commandsMaxUseLen233 }234}235236var minCommandPathPadding int = 11237

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 238why, one step back
238//

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 239–246why, one step back
239func (c *Command) CommandPathPadding() int {
240 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {241 return minCommandPathPadding242 } else {243 return c.parent.commandsMaxCommandPathLen244 }245}246

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

lines 247–256why, one step back
247var minNamePadding int = 11
248249func (c *Command) NamePadding() int {250 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {251 return minNamePadding252 } else {253 return c.parent.commandsMaxNameLen254 }255}256

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

lines 257–264why, one step back
257func (c *Command) UsageTemplate() string {
258 if c.usageTemplate != "" {259 return c.usageTemplate260 }261262 if c.HasParent() {263 return c.parent.UsageTemplate()264 } else {

Merge pull request #153 from eparis/remove-useless-assignmentEric Parisbefore adoptioneeec8e3

line 265why, one step back
265 return `Usage:{{if .Runnable}}

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

line 266why, one step back
266 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 267–269why, one step back
267 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
268269Aliases:

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 270–271why, one step back
270 {{.NameAndAliases}}
271{{end}}{{if .HasExample}}

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 272why, one step back
272

New "example" section of commandsEric Parisbefore adoptionbf480fe

line 273why, one step back
273Examples:

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

line 274why, one step back
274{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 275why, one step back
275

Merge pull request #148 from tamird/trailing-spacesEric Parisbefore adoption42498ec

line 276why, one step back
276Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

lines 277–279why, one step back
277 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}}
278279Flags:

Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7

line 280why, one step back
280{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasInheritedFlags}}

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

lines 281–282why, one step back
281
282Global Flags:

Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7

line 283why, one step back
283{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 284why, one step back
284

Merge pull request #148 from tamird/trailing-spacesEric Parisbefore adoption42498ec

line 285why, one step back
285Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}

Merge pull request #137 from eparis/fix-help-templateEric Parisbefore adoption99d2c51

line 286why, one step back
286 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 287why, one step back
287

Merge pull request #154 from eparis/fix-trailing-newlineEric Parisbefore adoptionb28774d

lines 288–289why, one step back
288Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
289`

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

lines 290–300why, one step back
290 }
291}292293func (c *Command) HelpTemplate() string {294 if c.helpTemplate != "" {295 return c.helpTemplate296 }297298 if c.HasParent() {299 return c.parent.HelpTemplate()300 } else {

Merge pull request #151 from eparis/no-newline-without-shortEric Parisbefore adoption85bb343

lines 301–303why, one step back
301 return `{{with or .Long .Short }}{{. | trim}}
302303{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`

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

lines 304–306why, one step back
304 }
305}306

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 307–313why, one step back
307// Really only used when casting a command to a commander
308func (c *Command) resetChildrensParents() {309 for _, x := range c.commands {310 x.parent = c311 }312}313

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

lines 314–324why, one step back
314// Test if the named flag is a boolean flag.
315func isBooleanFlag(name string, f *flag.FlagSet) bool {316 flag := f.Lookup(name)317 if flag == nil {318 return false319 }320 return flag.Value.Type() == "bool"321}322323// Test if the named flag is a boolean flag.324func isBooleanShortFlag(name string, f *flag.FlagSet) bool {

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

lines 325–330why, one step back
325 result := false
326 f.VisitAll(func(f *flag.Flag) {327 if f.Shorthand == name && f.Value.Type() == "bool" {328 result = true329 }330 })

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

lines 331–334why, one step back
331 return result
332}333334func stripFlags(args []string, c *Command) []string {

Support for flags before commandsspf13before adoption10a8494

lines 335–337why, one step back
335 if len(args) < 1 {
336 return args337 }

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

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

Support for flags before commandsspf13before adoption10a8494

lines 339–342why, one step back
339
340 commands := []string{}341342 inQuote := false

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

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

Support for flags before commandsspf13before adoption10a8494

lines 344–350why, one step back
344 for _, y := range args {
345 if !inQuote {346 switch {347 case strings.HasPrefix(y, "\""):348 inQuote = true349 case strings.Contains(y, "=\""):350 inQuote = true

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

lines 351–357why, one step back
351 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
352 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'353 inFlag = !isBooleanFlag(y[2:], c.Flags())354 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):355 inFlag = true356 case inFlag:357 inFlag = false

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

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

Support for flags before commandsspf13before adoption10a8494

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

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

line 362why, one step back
362 inFlag = false

Support for flags before commandsspf13before adoption10a8494

lines 363–373why, one step back
363 }
364 }365366 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {367 inQuote = false368 }369 }370371 return commands372}373

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

lines 374–382why, one step back
374// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
375// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).376func argsMinusFirstX(args []string, x string) []string {377 for i, y := range args {378 if x == y {379 ret := []string{}380 ret = append(ret, args[:i]...)381 ret = append(ret, args[i+1:]...)382 return ret

Support for flags before commandsspf13before adoption10a8494

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

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

line 385why, one step back
385 return args

Support for flags before commandsspf13before adoption10a8494

lines 386–387why, one step back
386}
387

Organize the files a bit betterspf13before adoption62fb674

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

Add support for help commandspf13before adoptionfb2146e

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

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Organize the files a bit betterspf13before adoption62fb674

lines 391–394why, one step back
391 if c == nil {
392 return nil, nil, fmt.Errorf("Called find() on a nil Command")393 }394

Finding command based on args cleaned upspf13before adoption55ff474

lines 395–396why, one step back
395 var innerfind func(*Command, []string) (*Command, []string)
396

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

line 397why, one step back
397 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 398–414why, one step back
398 argsWOflags := stripFlags(innerArgs, c)
399 if len(argsWOflags) == 0 {400 return c, innerArgs401 }402 nextSubCmd := argsWOflags[0]403 matches := make([]*Command, 0)404 for _, cmd := range c.commands {405 if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match406 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))407 }408 if EnablePrefixMatching {409 if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match410 matches = append(matches, cmd)411 }412 for _, x := range cmd.Aliases {413 if strings.HasPrefix(x, nextSubCmd) {414 matches = append(matches, cmd)

Support for flags before commandsspf13before adoption10a8494

line 415why, one step back
415 }

adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac

line 416why, one step back
416 }

Organize the files a bit betterspf13before adoption62fb674

lines 417–418why, one step back
417 }
418 }

Finding command based on args cleaned upspf13before adoption55ff474

line 419why, one step back
419

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 420–424why, one step back
420 // only accept a single prefix match - multiple matches would be ambiguous
421 if len(matches) == 1 {422 return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))423 }424

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

line 425why, one step back
425 return c, innerArgs

Organize the files a bit betterspf13before adoption62fb674

line 426why, one step back
426 }

Finding command based on args cleaned upspf13before adoption55ff474

line 427why, one step back
427

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

line 428why, one step back
428 commandFound, a := innerfind(c, args)

Merge pull request #119 from eparis/bogus-bad-commandEric Parisbefore adoption66816bc

line 429why, one step back
429 argsWOflags := stripFlags(a, commandFound)

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 430–434why, one step back
430
431 // no subcommand, always take args432 if !commandFound.HasSubCommands() {433 return commandFound, a, nil434 }

Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311

line 435why, one step back
435

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

line 436why, one step back
436 // root command with subcommands, do subcommand checking

Merge pull request #119 from eparis/bogus-bad-commandEric Parisbefore adoption66816bc

line 437why, one step back
437 if commandFound == c && len(argsWOflags) > 0 {

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

line 438why, one step back
438 suggestionsString := ""

Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311

lines 439–442why, one step back
439 if !c.DisableSuggestions {
440 if c.SuggestionsMinimumDistance <= 0 {441 c.SuggestionsMinimumDistance = 2442 }

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

lines 443–446why, one step back
443 if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {
444 suggestionsString += "\n\nDid you mean this?\n"445 for _, s := range suggestions {446 suggestionsString += fmt.Sprintf("\t%v\n", s)

Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311

lines 447–449why, one step back
447 }
448 }449 }

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

line 450why, one step back
450 return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)

Organize the files a bit betterspf13before adoption62fb674

lines 451–452why, one step back
451 }
452

Finding command based on args cleaned upspf13before adoption55ff474

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

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

lines 454–473why, one step back
454}
455456func (c *Command) SuggestionsFor(typedName string) []string {457 suggestions := []string{}458 for _, cmd := range c.commands {459 if cmd.IsAvailableCommand() {460 levenshteinDistance := ld(typedName, cmd.Name(), true)461 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance462 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))463 if suggestByLevenshtein || suggestByPrefix {464 suggestions = append(suggestions, cmd.Name())465 }466 for _, explicitSuggestion := range cmd.SuggestFor {467 if strings.EqualFold(typedName, explicitSuggestion) {468 suggestions = append(suggestions, cmd.Name())469 }470 }471 }472 }473 return suggestions

Organize the files a bit betterspf13before adoption62fb674

lines 474–475why, one step back
474}
475

add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a

lines 476–490why, one step back
476func (c *Command) VisitParents(fn func(*Command)) {
477 var traverse func(*Command) *Command478479 traverse = func(x *Command) *Command {480 if x != c {481 fn(x)482 }483 if x.HasParent() {484 return traverse(x.parent)485 }486 return x487 }488 traverse(c)489}490

Add support for help commandspf13before adoptionfb2146e

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

Organize the files a bit betterspf13before adoption62fb674

lines 492–497why, one step back
492 var findRoot func(*Command) *Command
493494 findRoot = func(x *Command) *Command {495 if x.HasParent() {496 return findRoot(x.parent)497 }

add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a

line 498why, one step back
498 return x

Organize the files a bit betterspf13before adoption62fb674

line 499why, one step back
499 }

Add support for help commandspf13before adoptionfb2146e

lines 500–503why, one step back
500
501 return findRoot(c)502}503

Merge pull request #167 from siddharthist/docs/ArgsLenAtDashEric Parisbefore adoption8b2293c

lines 504–507why, one step back
504// ArgsLenAtDash will return the length of f.Args at the moment when a -- was
505// found during arg parsing. This allows your program to know which args were506// before the -- and which came after. (Description from507// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).

Merge pull request #160 from eparis/len-at-dashEric Parisbefore adoption53d9650

lines 508–511why, one step back
508func (c *Command) ArgsLenAtDash() int {
509 return c.Flags().ArgsLenAtDash()510}511

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

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

Organize the files a bit betterspf13before adoption62fb674

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

Merge pull request #90 from eparis/deprecated-subcommandsEric Parisbefore adoption9cf0f37

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

Organize the files a bit betterspf13before adoption62fb674

lines 519–520why, one step back
519 }
520

Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f

lines 521–524why, one step back
521 // initialize help flag as the last point possible to allow for user
522 // overriding523 c.initHelpFlag()524

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

lines 525–527why, one step back
525 err = c.ParseFlags(a)
526 if err != nil {527 return err

Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e

line 528why, one step back
528 }

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

line 529why, one step back
529 // If help is called, regardless of other flags, return we want help

Merge pull request #139 from alexanderguy/RunE-is-runnableBjørn Erik Pedersenbefore adoption1ba88c4

line 530why, one step back
530 // Also say we need help if the command isn't runnable.

Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f

lines 531–538why, one step back
531 helpVal, err := c.Flags().GetBool("help")
532 if err != nil {533 // should be impossible to get here as we always declare a help534 // flag in initHelpFlag()535 c.Println("\"help\" flag declared as non-bool. Please correct your code")536 return err537 }538 if helpVal || !c.Runnable() {

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

line 539why, one step back
539 return flag.ErrHelp

Organize the files a bit betterspf13before adoption62fb674

line 540why, one step back
540 }

Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e

lines 541–543why, one step back
541
542 c.preRun()543 argWoFlags := c.Flags().Args()

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

line 544why, one step back
544

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

line 545why, one step back
545 for p := c; p != nil; p = p.Parent() {

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

line 546why, one step back
546 if p.PersistentPreRunE != nil {

Merge pull request #164 from vikstrous/fix_bugEric Parisbefore adoptiond732ab3

line 547why, one step back
547 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 548–551why, one step back
548 return err
549 }550 break551 } else if p.PersistentPreRun != nil {

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

lines 552–554why, one step back
552 p.PersistentPreRun(c, argWoFlags)
553 break554 }

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

line 555why, one step back
555 }

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 556–560why, one step back
556 if c.PreRunE != nil {
557 if err := c.PreRunE(c, argWoFlags); err != nil {558 return err559 }560 } else if c.PreRun != nil {

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

lines 561–563why, one step back
561 c.PreRun(c, argWoFlags)
562 }563

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 564–575why, one step back
564 if c.RunE != nil {
565 if err := c.RunE(c, argWoFlags); err != nil {566 return err567 }568 } else {569 c.Run(c, argWoFlags)570 }571 if c.PostRunE != nil {572 if err := c.PostRunE(c, argWoFlags); err != nil {573 return err574 }575 } else if c.PostRun != nil {

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

lines 576–577why, one step back
576 c.PostRun(c, argWoFlags)
577 }

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

line 578why, one step back
578 for p := c; p != nil; p = p.Parent() {

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 579–584why, one step back
579 if p.PersistentPostRunE != nil {
580 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {581 return err582 }583 break584 } else if p.PersistentPostRun != nil {

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

lines 585–587why, one step back
585 p.PersistentPostRun(c, argWoFlags)
586 break587 }

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

lines 588–589why, one step back
588 }
589

Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e

line 590why, one step back
590 return nil

Organize the files a bit betterspf13before adoption62fb674

lines 591–592why, one step back
591}
592

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

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

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

lines 594–596why, one step back
594 for _, x := range initializers {
595 x()596 }

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

lines 597–598why, one step back
597}
598

Support for flags before commandsspf13before adoption10a8494

lines 599–610why, one step back
599func (c *Command) errorMsgFromParse() string {
600 s := c.flagErrorBuf.String()601602 x := strings.Split(s, "\n")603604 if len(x) > 0 {605 return x[0]606 } else {607 return ""608 }609}610

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

lines 611–613why, one step back
611// Call execute to use the args (os.Args[1:] by default)
612// and run through the command tree finding appropriate matches613// for commands and then corresponding flags.

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

lines 614–617why, one step back
614func (c *Command) Execute() error {
615 _, err := c.ExecuteC()616 return err617}

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

line 618why, one step back
618

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

lines 619–620why, one step back
619func (c *Command) ExecuteC() (cmd *Command, err error) {
620

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

lines 621–622why, one step back
621 // Regardless of what command execute is called on, run on Root only
622 if c.HasParent() {

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

line 623why, one step back
623 return c.Root().ExecuteC()

Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29

lines 624–625why, one step back
624 }
625

Merge pull request #197 from magiconair/issue-195-mousetrap-win-onlyEric Parisbefore adoption7366561

lines 626–628why, one step back
626 // windows hook
627 if preExecHookFn != nil {628 preExecHookFn(c)

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

lines 629–632why, one step back
629 }
630631 // initialize help as the last point possible to allow for user632 // overriding

Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f

line 633why, one step back
633 c.initHelpCmd()

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

lines 634–636why, one step back
634
635 var args []string636

Limit the verbose test workaround to "cobra.test" onlyAnthony Fokbefore adoptione576205

lines 637–638why, one step back
637 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
638 if len(c.args) == 0 && filepath.Base(os.Args[0]) != "cobra.test" {

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

lines 639–643why, one step back
639 args = os.Args[1:]
640 } else {641 args = c.args642 }643

Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e

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

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 645–649why, one step back
645 if err != nil {
646 // If found parse to a subcommand and then failed, talk about the subcommand647 if cmd != nil {648 c = cmd649 }

Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e

lines 650–653why, one step back
650 if !c.SilenceErrors {
651 c.Println("Error:", err.Error())652 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())653 }

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

line 654why, one step back
654 return c, err

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

line 655why, one step back
655 }

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

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

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

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

always show help if requested, even if SilenceErrors is enabledSascha Holzleiterbefore adoption2bd8a73

lines 658–664why, one step back
658 // Always show help if requested, even if SilenceErrors is in
659 // effect660 if err == flag.ErrHelp {661 cmd.HelpFunc()(cmd, args)662 return cmd, nil663 }664

Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e

lines 665–668why, one step back
665 // If root command has SilentErrors flagged,
666 // all subcommands should respect it667 if !cmd.SilenceErrors && !c.SilenceErrors {668 c.Println("Error:", err.Error())

Merge pull request #174 from jbowes/fix-duplicate-usageEric Parisbefore adoptiona082ce4

lines 669–674why, one step back
669 }
670671 // If root command has SilentUsage flagged,672 // all subcommands should respect it673 if !cmd.SilenceUsage && !c.SilenceUsage {674 c.Println(cmd.UsageString())

Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e

line 675why, one step back
675 }

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

line 676why, one step back
676 return cmd, err

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

line 677why, one step back
677 }

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

line 678why, one step back
678 return cmd, nil

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

lines 679–680why, one step back
679}
680

Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f

line 681why, one step back
681func (c *Command) initHelpFlag() {

Merge pull request #133 from eparis/late-init-help-flagEric Parisbefore adoption4c4f2d9

line 682why, one step back
682 if c.Flags().Lookup("help") == nil {

Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f

line 683why, one step back
683 c.Flags().BoolP("help", "h", false, "help for "+c.Name())

Merge pull request #133 from eparis/late-init-help-flagEric Parisbefore adoption4c4f2d9

line 684why, one step back
684 }

Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f

lines 685–687why, one step back
685}
686687func (c *Command) initHelpCmd() {

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

line 688why, one step back
688 if c.helpCommand == nil {

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

lines 689–692why, one step back
689 if !c.HasSubCommands() {
690 return691 }692

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

lines 693–697why, one step back
693 c.helpCommand = &Command{
694 Use: "help [command]",695 Short: "Help about any command",696 Long: `Help provides help for any command in the application.697 Simply type ` + c.Name() + ` help [path to command] for full details.`,

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

lines 698–699why, one step back
698 PersistentPreRun: func(cmd *Command, args []string) {},
699 PersistentPostRun: func(cmd *Command, args []string) {},

Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170

lines 700–710why, one step back
700
701 Run: func(c *Command, args []string) {702 cmd, _, e := c.Root().Find(args)703 if cmd == nil || e != nil {704 c.Printf("Unknown help topic %#q.", args)705 c.Root().Usage()706 } else {707 helpFunc := cmd.HelpFunc()708 helpFunc(cmd, args)709 }710 },

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

lines 711–715why, one step back
711 }
712 }713 c.AddCommand(c.helpCommand)714}715

Organize the files a bit betterspf13before adoption62fb674

lines 716–718why, one step back
716// Used for testing
717func (c *Command) ResetCommands() {718 c.commands = nil

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

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

Organize the files a bit betterspf13before adoption62fb674

lines 720–721why, one step back
720}
721

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Organize the files a bit betterspf13before adoption62fb674

lines 723–726why, one step back
723func (c *Command) Commands() []*Command {
724 return c.commands725}726

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Organize the files a bit betterspf13before adoption62fb674

lines 728–733why, one step back
728func (c *Command) AddCommand(cmds ...*Command) {
729 for i, x := range cmds {730 if cmds[i] == c {731 panic("Command can't be a child of itself")732 }733 cmds[i].parent = c

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 734–741why, one step back
734 // update max lengths
735 usageLen := len(x.Use)736 if usageLen > c.commandsMaxUseLen {737 c.commandsMaxUseLen = usageLen738 }739 commandPathLen := len(x.CommandPath())740 if commandPathLen > c.commandsMaxCommandPathLen {741 c.commandsMaxCommandPathLen = commandPathLen

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

lines 742–745why, one step back
742 }
743 nameLen := len(x.Name())744 if nameLen > c.commandsMaxNameLen {745 c.commandsMaxNameLen = nameLen

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

line 746why, one step back
746 }

Merge pull request #211 from NanXiao/patch-1Eric Parisbefore adoptionea3bf16

line 747why, one step back
747 // If global normalization function exists, update all children

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

lines 748–750why, one step back
748 if c.globNormFunc != nil {
749 x.SetGlobalNormalizationFunc(c.globNormFunc)750 }

Organize the files a bit betterspf13before adoption62fb674

lines 751–754why, one step back
751 c.commands = append(c.commands, x)
752 }753}754

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

lines 755–788why, one step back
755// AddCommand removes one or more commands from a parent command.
756func (c *Command) RemoveCommand(cmds ...*Command) {757 commands := []*Command{}758main:759 for _, command := range c.commands {760 for _, cmd := range cmds {761 if command == cmd {762 command.parent = nil763 continue main764 }765 }766 commands = append(commands, command)767 }768 c.commands = commands769 // recompute all lengths770 c.commandsMaxUseLen = 0771 c.commandsMaxCommandPathLen = 0772 c.commandsMaxNameLen = 0773 for _, command := range c.commands {774 usageLen := len(command.Use)775 if usageLen > c.commandsMaxUseLen {776 c.commandsMaxUseLen = usageLen777 }778 commandPathLen := len(command.CommandPath())779 if commandPathLen > c.commandsMaxCommandPathLen {780 c.commandsMaxCommandPathLen = commandPathLen781 }782 nameLen := len(command.Name())783 if nameLen > c.commandsMaxNameLen {784 c.commandsMaxNameLen = nameLen785 }786 }787}788

Organize the files a bit betterspf13before adoption62fb674

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

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

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

Organize the files a bit betterspf13before adoption62fb674

lines 792–807why, one step back
792}
793794// Convenience method to Println to the defined output795func (c *Command) Println(i ...interface{}) {796 str := fmt.Sprintln(i...)797 c.Print(str)798}799800// Convenience method to Printf to the defined output801func (c *Command) Printf(format string, i ...interface{}) {802 str := fmt.Sprintf(format, i...)803 c.Print(str)804}805806// Output the usage for the command807// Used when a user provides invalid input

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

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

Organize the files a bit betterspf13before adoption62fb674

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

Help improvementsspf13before adoption2d02c31

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

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

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

Help improvementsspf13before adoption2d02c31

lines 812–819why, one step back
812 return err
813}814815// Output the help for the command816// Used when a user calls help [command]817// by the default HelpFunc in the commander818func (c *Command) Help() error {819 c.mergePersistentFlags()

Default usage output to stdoutEric Parisbefore adoption6de96b8

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

Organize the files a bit betterspf13before adoption62fb674

lines 821–823why, one step back
821 return err
822}823

fix trailing <nil> on help outputspf13before adoption3958385

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

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

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

fix trailing <nil> on help outputspf13before adoption3958385

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

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

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

fix trailing <nil> on help outputspf13before adoption3958385

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

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

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

fix trailing <nil> on help outputspf13before adoption3958385

lines 830–832why, one step back
830 return bb.String()
831}832

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Organize the files a bit betterspf13before adoption62fb674

lines 834–908why, one step back
834func (c *Command) CommandPath() string {
835 str := c.Name()836 x := c837 for x.HasParent() {838 str = x.parent.Name() + " " + str839 x = x.parent840 }841 return str842}843844//The full usage for a given command (including parents)845func (c *Command) UseLine() string {846 str := ""847 if c.HasParent() {848 str = c.parent.CommandPath() + " "849 }850 return str + c.Use851}852853// For use in determining which flags have been assigned to which commands854// and which persist855func (c *Command) DebugFlags() {856 c.Println("DebugFlags called on", c.Name())857 var debugflags func(*Command)858859 debugflags = func(x *Command) {860 if x.HasFlags() || x.HasPersistentFlags() {861 c.Println(x.Name())862 }863 if x.HasFlags() {864 x.flags.VisitAll(func(f *flag.Flag) {865 if x.HasPersistentFlags() {866 if x.persistentFlag(f.Name) == nil {867 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")868 } else {869 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")870 }871 } else {872 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")873 }874 })875 }876 if x.HasPersistentFlags() {877 x.pflags.VisitAll(func(f *flag.Flag) {878 if x.HasFlags() {879 if x.flags.Lookup(f.Name) == nil {880 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")881 }882 } else {883 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")884 }885 })886 }887 c.Println(x.flagErrorBuf)888 if x.HasSubCommands() {889 for _, y := range x.commands {890 debugflags(y)891 }892 }893 }894895 debugflags(c)896}897898// Name returns the command's name: the first word in the use line.899func (c *Command) Name() string {900 if c.name != "" {901 return c.name902 }903 name := c.Use904 i := strings.Index(name, " ")905 if i >= 0 {906 name = name[:i]907 }908 return name

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 909–922why, one step back
909}
910911// Determine if a given string is an alias of the command.912func (c *Command) HasAlias(s string) bool {913 for _, a := range c.Aliases {914 if a == s {915 return true916 }917 }918 return false919}920921func (c *Command) NameAndAliases() string {922 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 923–926why, one step back
923}
924925func (c *Command) HasExample() bool {926 return len(c.Example) > 0

Organize the files a bit betterspf13before adoption62fb674

lines 927–930why, one step back
927}
928929// Determine if the command is itself runnable930func (c *Command) Runnable() bool {

Merge pull request #139 from alexanderguy/RunE-is-runnableBjørn Erik Pedersenbefore adoption1ba88c4

line 931why, one step back
931 return c.Run != nil || c.RunE != nil

Organize the files a bit betterspf13before adoption62fb674

lines 932–936why, one step back
932}
933934// Determine if the command has children commands935func (c *Command) HasSubCommands() bool {936 return len(c.commands) > 0

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

lines 937–938why, one step back
937}
938

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 939–941why, one step back
939// IsAvailableCommand determines if a command is available as a non-help command
940// (this includes all non deprecated/hidden commands)941func (c *Command) IsAvailableCommand() bool {

Merge pull request #146 from eparis/is-available-reworkEric Parisbefore adoption4b86c66

lines 942–944why, one step back
942 if len(c.Deprecated) != 0 || c.Hidden {
943 return false944 }

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

line 945why, one step back
945

Merge pull request #150 from eparis/help-not-availableEric Parisbefore adoption0d9b07b

lines 946–949why, one step back
946 if c.HasParent() && c.Parent().helpCommand == c {
947 return false948 }949

Merge pull request #146 from eparis/is-available-reworkEric Parisbefore adoption4b86c66

lines 950–954why, one step back
950 if c.Runnable() || c.HasAvailableSubCommands() {
951 return true952 }953954 return false

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 955–959why, one step back
955}
956957// IsHelpCommand determines if a command is a 'help' command; a help command is958// determined by the fact that it is NOT runnable/hidden/deprecated, and has no959// sub commands that are runnable/hidden/deprecated

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 960why, one step back
960func (c *Command) IsHelpCommand() bool {

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 961–963why, one step back
961
962 // if a command is runnable, deprecated, or hidden it is not a 'help' command963 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {

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

lines 964–965why, one step back
964 return false
965 }

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 966–967why, one step back
966
967 // if any non-help sub commands are found, the command is not a 'help' command

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

lines 968–971why, one step back
968 for _, sub := range c.commands {
969 if !sub.IsHelpCommand() {970 return false971 }

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

line 972why, one step back
972 }

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 973–974why, one step back
973
974 // the command either has no sub commands, or no non-help sub commands

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 975why, one step back
975 return true

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

lines 976–977why, one step back
976}
977

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 978–980why, one step back
978// HasHelpSubCommands determines if a command has any avilable 'help' sub commands
979// that need to be shown in the usage/help default template under 'additional help980// topics'

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

line 981why, one step back
981func (c *Command) HasHelpSubCommands() bool {

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 982–983why, one step back
982
983 // return true on the first found available 'help' sub command

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

line 984why, one step back
984 for _, sub := range c.commands {

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 985why, one step back
985 if sub.IsHelpCommand() {

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

lines 986–988why, one step back
986 return true
987 }988 }

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 989–990why, one step back
989
990 // the command either has no sub commands, or no available 'help' sub commands

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

lines 991–993why, one step back
991 return false
992}993

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 994–999why, one step back
994// HasAvailableSubCommands determines if a command has available sub commands that
995// need to be shown in the usage/help default template under 'available commands'996func (c *Command) HasAvailableSubCommands() bool {997998 // return true on the first found available (non deprecated/help/hidden)999 // sub command

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

line 1000why, one step back
1000 for _, sub := range c.commands {

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

line 1001why, one step back
1001 if sub.IsAvailableCommand() {

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

lines 1002–1004why, one step back
1002 return true
1003 }1004 }

Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d

lines 1005–1007why, one step back
1005
1006 // the command either has no sub comamnds, or no available (non deprecated/help/hidden)1007 // sub commands

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

line 1008why, one step back
1008 return false

Organize the files a bit betterspf13before adoption62fb674

lines 1009–1013why, one step back
1009}
10101011// Determine if the command is a child command1012func (c *Command) HasParent() bool {1013 return c.parent != nil

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

lines 1014–1018why, one step back
1014}
10151016// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists1017func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1018 return c.globNormFunc

Organize the files a bit betterspf13before adoption62fb674

lines 1019–1020why, one step back
1019}
1020

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 1021why, one step back
1021// 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 1022–1032why, one step back
1022func (c *Command) Flags() *flag.FlagSet {
1023 if c.flags == nil {1024 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1025 if c.flagErrorBuf == nil {1026 c.flagErrorBuf = new(bytes.Buffer)1027 }1028 c.flags.SetOutput(c.flagErrorBuf)1029 }1030 return c.flags1031}1032

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1033–1037why, one step back
1033// Get the local FlagSet specifically set in the current command
1034func (c *Command) LocalFlags() *flag.FlagSet {1035 c.mergePersistentFlags()10361037 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 1040why, one step back
1040 })

Merge pull request #127 from eparis/show-commandline-on-parentEric Parisbefore adoptiondb05184

lines 1041–1047why, one step back
1041 if !c.HasParent() {
1042 flag.CommandLine.VisitAll(func(f *flag.Flag) {1043 if local.Lookup(f.Name) == nil {1044 local.AddFlag(f)1045 }1046 })1047 }

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1048–1050why, one step back
1048 return local
1049}1050

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

lines 1051–1054why, one step back
1051// All Flags which were inherited from parents commands
1052func (c *Command) InheritedFlags() *flag.FlagSet {1053 c.mergePersistentFlags()1054

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

line 1057why, one step back
1057

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

line 1059why, one step back
1059

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 1060–1071why, one step back
1060 rmerge = func(x *Command) {
1061 if x.HasPersistentFlags() {1062 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1063 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1064 inherited.AddFlag(f)1065 }1066 })1067 }1068 if x.HasParent() {1069 rmerge(x.parent)1070 }1071 }

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

lines 1072–1076why, one step back
1072
1073 if c.HasParent() {1074 rmerge(c.parent)1075 }1076

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 1077why, one step back
1077 return inherited

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

lines 1078–1079why, one step back
1078}
1079

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

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

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

lines 1083–1084why, one step back
1083}
1084

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

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

Organize the files a bit betterspf13before adoption62fb674

lines 1086–1106why, one step back
1086func (c *Command) PersistentFlags() *flag.FlagSet {
1087 if c.pflags == nil {1088 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1089 if c.flagErrorBuf == nil {1090 c.flagErrorBuf = new(bytes.Buffer)1091 }1092 c.pflags.SetOutput(c.flagErrorBuf)1093 }1094 return c.pflags1095}10961097// For use in testing1098func (c *Command) ResetFlags() {1099 c.flagErrorBuf = new(bytes.Buffer)1100 c.flagErrorBuf.Reset()1101 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1102 c.flags.SetOutput(c.flagErrorBuf)1103 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1104 c.pflags.SetOutput(c.flagErrorBuf)1105}1106

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

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

Organize the files a bit betterspf13before adoption62fb674

lines 1108–1116why, one step back
1108func (c *Command) HasFlags() bool {
1109 return c.Flags().HasFlags()1110}11111112// Does the command contain persistent flags1113func (c *Command) HasPersistentFlags() bool {1114 return c.PersistentFlags().HasFlags()1115}1116

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1117–1121why, one step back
1117// Does the command has flags specifically declared locally
1118func (c *Command) HasLocalFlags() bool {1119 return c.LocalFlags().HasFlags()1120}1121

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 1122–1125why, one step back
1122func (c *Command) HasInheritedFlags() bool {
1123 return c.InheritedFlags().HasFlags()1124}1125

Organize the files a bit betterspf13before adoption62fb674

lines 1126–1152why, one step back
1126// Climbs up the command tree looking for matching flag
1127func (c *Command) Flag(name string) (flag *flag.Flag) {1128 flag = c.Flags().Lookup(name)11291130 if flag == nil {1131 flag = c.persistentFlag(name)1132 }11331134 return1135}11361137// recursively find matching persistent flag1138func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1139 if c.HasPersistentFlags() {1140 flag = c.PersistentFlags().Lookup(name)1141 }11421143 if flag == nil && c.HasParent() {1144 flag = c.parent.persistentFlag(name)1145 }1146 return1147}11481149// Parses persistent flag tree & local flags1150func (c *Command) ParseFlags(args []string) (err error) {1151 c.mergePersistentFlags()1152 err = c.Flags().Parse(args)

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

line 1153why, one step back
1153 return

Organize the files a bit betterspf13before adoption62fb674

lines 1154–1155why, one step back
1154}
1155

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1156–1159why, one step back
1156func (c *Command) Parent() *Command {
1157 return c.parent1158}1159

Organize the files a bit betterspf13before adoption62fb674

lines 1160–1162why, one step back
1160func (c *Command) mergePersistentFlags() {
1161 var rmerge func(x *Command)1162

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 1163–1175why, one step back
1163 // Save the set of local flags
1164 if c.lflags == nil {1165 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1166 if c.flagErrorBuf == nil {1167 c.flagErrorBuf = new(bytes.Buffer)1168 }1169 c.lflags.SetOutput(c.flagErrorBuf)1170 addtolocal := func(f *flag.Flag) {1171 c.lflags.AddFlag(f)1172 }1173 c.Flags().VisitAll(addtolocal)1174 c.PersistentFlags().VisitAll(addtolocal)1175 }

Organize the files a bit betterspf13before adoption62fb674

line 1176why, one step back
1176 rmerge = func(x *Command) {

Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

line 1177why, one step back
1177 if !x.HasParent() {

Merge pull request #75 from eparis/CommandLineEric Parisbefore adoption2d5fab0

lines 1178–1183why, one step back
1178 flag.CommandLine.VisitAll(func(f *flag.Flag) {
1179 if x.PersistentFlags().Lookup(f.Name) == nil {1180 x.PersistentFlags().AddFlag(f)1181 }1182 })1183 }

Organize the files a bit betterspf13before adoption62fb674

lines 1184–1197why, one step back
1184 if x.HasPersistentFlags() {
1185 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1186 if c.Flags().Lookup(f.Name) == nil {1187 c.Flags().AddFlag(f)1188 }1189 })1190 }1191 if x.HasParent() {1192 rmerge(x.parent)1193 }1194 }11951196 rmerge(c)1197}