Skip to content
Myr

command.go

This file

Path

command.go

1,257 lines · 33.8 KiB · Go

Last changed by

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

History of this file

Take it

The walk stopped after 200 commits: lines older than 10a8494 point at it.

Support for flags before commandsspf13before adoption10a8494

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.

Support for flags before commandsspf13before adoption10a8494

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

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

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

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 24why, one step back
24 "sort"

Support for flags before commandsspf13before adoption10a8494

line 25why, one step back
25 "strings"

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Support for flags before commandsspf13before adoption10a8494

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

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

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

Support for flags before commandsspf13before adoption10a8494

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

New "example" section of commandsEric Parisbefore adoptionbf480fe

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

Merge pull request #257 from sttts/sttts-noun-aliasesEric Parisbefore adoption60267ae

line 49why, one step back
49 // List of all valid non-flag arguments that are accepted in bash completions

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

line 50why, one step back
50 ValidArgs []string

Merge pull request #257 from sttts/sttts-noun-aliasesEric Parisbefore adoption60267ae

lines 51–53why, one step back
51 // List of aliases for ValidArgs. These are not suggested to the user in the bash
52 // completion, but accepted if entered manually.53 ArgAliases []string

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

lines 54–55why, one step back
54 // Custom functions used by the bash autocompletion generator
55 BashCompletionFunction string

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

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

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

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

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

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

Support for flags before commandsspf13before adoption10a8494

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

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

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

Support for flags before commandsspf13before adoption10a8494

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

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

lines 66–69why, one step back
66 // SilenceErrors is an option to quiet errors down stream
67 SilenceErrors bool68 // Silence Usage is an option to silence usage when an error occurs.69 SilenceUsage bool

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

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

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

Support for flags before commandsspf13before adoption10a8494

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

lines 97–98why, one step back
97 // DisableAutoGenTag remove
98 DisableAutoGenTag bool

Support for flags before commandsspf13before adoption10a8494

lines 99–105why, one step back
99 // Commands is the list of commands supported by this program.
100 commands []*Command101 // Parent Command for this command102 parent *Command103 // max lengths of commands' string lengths for use in padding104 commandsMaxUseLen int105 commandsMaxCommandPathLen int

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

line 106why, one step back
106 commandsMaxNameLen int

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

lines 107–108why, one step back
107 // is commands slice are sorted or not
108 commandsAreSorted bool

Support for flags before commandsspf13before adoption10a8494

lines 109–111why, one step back
109
110 flagErrorBuf *bytes.Buffer111

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

line 113why, one step back
113 output *io.Writer // out writer if set in SetOutput(w)

Support for flags before commandsspf13before adoption10a8494

lines 114–118why, one step back
114 usageFunc func(*Command) error // Usage can be defined by application
115 usageTemplate string // Can be defined by Application116 helpTemplate string // Can be defined by Application117 helpFunc func(*Command, []string) // Help can be defined by application118 helpCommand *Command // The help command

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

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

Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311

lines 121–125why, one step back
121
122 // Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages123 DisableSuggestions bool124 // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0125 SuggestionsMinimumDistance int

Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048

lines 126–128why, one step back
126
127 // Disable the flag parsing. If this is true all flags will be passed to the command as arguments.128 DisableFlagParsing bool

Support for flags before commandsspf13before adoption10a8494

lines 129–142why, one step back
129}
130131// os.Args[1:] by default, if desired, can be overridden132// particularly useful when testing.133func (c *Command) SetArgs(a []string) {134 c.args = a135}136137// SetOutput sets the destination for usage and error messages.138// If output is nil, os.Stderr is used.139func (c *Command) SetOutput(output io.Writer) {140 c.output = &output141}142

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 143why, one step back
143// Usage can be defined by application.

Support for flags before commandsspf13before adoption10a8494

lines 144–147why, one step back
144func (c *Command) SetUsageFunc(f func(*Command) error) {
145 c.usageFunc = f146}147

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 148why, one step back
148// Can be defined by Application.

Support for flags before commandsspf13before adoption10a8494

lines 149–152why, one step back
149func (c *Command) SetUsageTemplate(s string) {
150 c.usageTemplate = s151}152

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 153why, one step back
153// Can be defined by Application.

Support for flags before commandsspf13before adoption10a8494

lines 154–161why, one step back
154func (c *Command) SetHelpFunc(f func(*Command, []string)) {
155 c.helpFunc = f156}157158func (c *Command) SetHelpCommand(cmd *Command) {159 c.helpCommand = cmd160}161

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 162why, one step back
162// Can be defined by Application.

Support for flags before commandsspf13before adoption10a8494

lines 163–166why, one step back
163func (c *Command) SetHelpTemplate(s string) {
164 c.helpTemplate = s165}166

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

lines 167–178why, one step back
167// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
168// The user should not have a cyclic dependency on commands.169func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {170 c.Flags().SetNormalizeFunc(n)171 c.PersistentFlags().SetNormalizeFunc(n)172 c.globNormFunc = n173174 for _, command := range c.commands {175 command.SetGlobalNormalizationFunc(n)176 }177}178

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

line 179why, one step back
179func (c *Command) OutOrStdout() io.Writer {

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 180–182why, one step back
180 return c.getOut(os.Stdout)
181}182

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

line 183why, one step back
183func (c *Command) OutOrStderr() io.Writer {

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 184–197why, one step back
184 return c.getOut(os.Stderr)
185}186187func (c *Command) getOut(def io.Writer) io.Writer {188 if c.output != nil {189 return *c.output190 }191 if c.HasParent() {192 return c.parent.getOut(def)193 }194 return def195}196197// UsageFunc returns either the function set by SetUsageFunc for this command

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 198why, one step back
198// or a parent, or it returns a default usage function.

Support for flags before commandsspf13before adoption10a8494

lines 199–205why, one step back
199func (c *Command) UsageFunc() (f func(*Command) error) {
200 if c.usageFunc != nil {201 return c.usageFunc202 }203204 if c.HasParent() {205 return c.parent.UsageFunc()

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

lines 206–207why, one step back
206 }
207 return func(c *Command) error {

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

lines 208–209why, one step back
208 c.mergePersistentFlags()
209 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

line 211why, one step back
211 c.Println(err)

Support for flags before commandsspf13before adoption10a8494

line 212why, one step back
212 }

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 213why, one step back
213 return err

Support for flags before commandsspf13before adoption10a8494

lines 214–215why, one step back
214 }
215}

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

line 216why, one step back
216

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

lines 217–219why, one step back
217// Usage puts out the usage for the command.
218// Used when a user provides invalid input.219// Can be defined by user by overriding UsageFunc.

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

lines 220–223why, one step back
220func (c *Command) Usage() error {
221 return c.UsageFunc()(c)222}223

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

line 224why, one step back
224// HelpFunc returns either the function set by SetHelpFunc for this command

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 225why, one step back
225// or a parent, or it returns a function with default help behavior.

Support for flags before commandsspf13before adoption10a8494

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

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

lines 227–232why, one step back
227 cmd := c
228 for cmd != nil {229 if cmd.helpFunc != nil {230 return cmd.helpFunc231 }232 cmd = cmd.parent

Support for flags before commandsspf13before adoption10a8494

line 233why, one step back
233 }

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

line 234why, one step back
234 return func(*Command, []string) {

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

lines 235–236why, one step back
235 c.mergePersistentFlags()
236 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)

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

lines 237–238why, one step back
237 if err != nil {
238 c.Println(err)

Support for flags before commandsspf13before adoption10a8494

lines 239–242why, one step back
239 }
240 }241}242

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

lines 243–245why, one step back
243// Help puts out the help for the command.
244// Used when a user calls help [command].245// Can be defined by user by overriding HelpFunc.

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

lines 246–250why, one step back
246func (c *Command) Help() error {
247 c.HelpFunc()(c, []string{})248 return nil249}250

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 251–254why, one step back
251func (c *Command) UsageString() string {
252 tmpOutput := c.output253 bb := new(bytes.Buffer)254 c.SetOutput(bb)

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 256–259why, one step back
256 c.output = tmpOutput
257 return bb.String()258}259

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 260why, one step back
260var minUsagePadding = 25

Support for flags before commandsspf13before adoption10a8494

lines 261–265why, one step back
261
262func (c *Command) UsagePadding() int {263 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {264 return minUsagePadding265 }

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 266why, one step back
266 return c.parent.commandsMaxUseLen

Support for flags before commandsspf13before adoption10a8494

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

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 269why, one step back
269var minCommandPathPadding = 11

Support for flags before commandsspf13before adoption10a8494

line 270why, one step back
270

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 271why, one step back
271//

Support for flags before commandsspf13before adoption10a8494

lines 272–275why, one step back
272func (c *Command) CommandPathPadding() int {
273 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {274 return minCommandPathPadding275 }

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 276why, one step back
276 return c.parent.commandsMaxCommandPathLen

Support for flags before commandsspf13before adoption10a8494

lines 277–278why, one step back
277}
278

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 279why, one step back
279var minNamePadding = 11

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

lines 280–284why, one step back
280
281func (c *Command) NamePadding() int {282 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {283 return minNamePadding284 }

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 285why, one step back
285 return c.parent.commandsMaxNameLen

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

lines 286–287why, one step back
286}
287

Support for flags before commandsspf13before adoption10a8494

lines 288–294why, one step back
288func (c *Command) UsageTemplate() string {
289 if c.usageTemplate != "" {290 return c.usageTemplate291 }292293 if c.HasParent() {294 return c.parent.UsageTemplate()

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

lines 295–296why, one step back
295 }
296 return `Usage:{{if .Runnable}}

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

line 297why, one step back
297 {{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 298–300why, one step back
298 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
299300Aliases:

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 301–302why, one step back
301 {{.NameAndAliases}}
302{{end}}{{if .HasExample}}

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 303why, one step back
303

New "example" section of commandsEric Parisbefore adoptionbf480fe

line 304why, one step back
304Examples:

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

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

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 306why, one step back
306

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

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

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

line 308why, one step back
308 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableLocalFlags}}

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

lines 309–310why, one step back
309
310Flags:

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

line 311why, one step back
311{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableInheritedFlags}}

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

lines 312–313why, one step back
312
313Global Flags:

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

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

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 315why, one step back
315

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

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

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

line 317why, one step back
317 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }}

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 318why, one step back
318

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

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

Support for flags before commandsspf13before adoption10a8494

lines 321–329why, one step back
321}
322323func (c *Command) HelpTemplate() string {324 if c.helpTemplate != "" {325 return c.helpTemplate326 }327328 if c.HasParent() {329 return c.parent.HelpTemplate()

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

lines 330–331why, one step back
330 }
331 return `{{with or .Long .Short }}{{. | trim}}

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

lines 332–333why, one step back
332
333{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`

Support for flags before commandsspf13before adoption10a8494

lines 334–335why, one step back
334}
335

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 336why, one step back
336// Really only used when casting a command to a commander.

Support for flags before commandsspf13before adoption10a8494

lines 337–342why, one step back
337func (c *Command) resetChildrensParents() {
338 for _, x := range c.commands {339 x.parent = c340 }341}342

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

lines 343–353why, one step back
343// Test if the named flag is a boolean flag.
344func isBooleanFlag(name string, f *flag.FlagSet) bool {345 flag := f.Lookup(name)346 if flag == nil {347 return false348 }349 return flag.Value.Type() == "bool"350}351352// Test if the named flag is a boolean flag.353func isBooleanShortFlag(name string, f *flag.FlagSet) bool {

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

lines 354–359why, one step back
354 result := false
355 f.VisitAll(func(f *flag.Flag) {356 if f.Shorthand == name && f.Value.Type() == "bool" {357 result = true358 }359 })

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

lines 360–363why, one step back
360 return result
361}362363func stripFlags(args []string, c *Command) []string {

Support for flags before commandsspf13before adoption10a8494

lines 364–366why, one step back
364 if len(args) < 1 {
365 return args366 }

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

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

Support for flags before commandsspf13before adoption10a8494

lines 368–371why, one step back
368
369 commands := []string{}370371 inQuote := false

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

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

Support for flags before commandsspf13before adoption10a8494

lines 373–379why, one step back
373 for _, y := range args {
374 if !inQuote {375 switch {376 case strings.HasPrefix(y, "\""):377 inQuote = true378 case strings.Contains(y, "=\""):379 inQuote = true

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

lines 380–386why, one step back
380 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
381 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'382 inFlag = !isBooleanFlag(y[2:], c.Flags())383 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):384 inFlag = true385 case inFlag:386 inFlag = false

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

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

Support for flags before commandsspf13before adoption10a8494

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

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

line 391why, one step back
391 inFlag = false

Support for flags before commandsspf13before adoption10a8494

lines 392–402why, one step back
392 }
393 }394395 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {396 inQuote = false397 }398 }399400 return commands401}402

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

lines 403–411why, one step back
403// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
404// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).405func argsMinusFirstX(args []string, x string) []string {406 for i, y := range args {407 if x == y {408 ret := []string{}409 ret = append(ret, args[:i]...)410 ret = append(ret, args[i+1:]...)411 return ret

Support for flags before commandsspf13before adoption10a8494

lines 412–413why, one step back
412 }
413 }

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

line 414why, one step back
414 return args

Support for flags before commandsspf13before adoption10a8494

lines 415–418why, one step back
415}
416417// find the target command given the args and command tree418// Meant to be run on the highest node. Only searches down.

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Support for flags before commandsspf13before adoption10a8494

lines 420–425why, one step back
420 if c == nil {
421 return nil, nil, fmt.Errorf("Called find() on a nil Command")422 }423424 var innerfind func(*Command, []string) (*Command, []string)425

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 427–443why, one step back
427 argsWOflags := stripFlags(innerArgs, c)
428 if len(argsWOflags) == 0 {429 return c, innerArgs430 }431 nextSubCmd := argsWOflags[0]432 matches := make([]*Command, 0)433 for _, cmd := range c.commands {434 if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match435 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))436 }437 if EnablePrefixMatching {438 if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match439 matches = append(matches, cmd)440 }441 for _, x := range cmd.Aliases {442 if strings.HasPrefix(x, nextSubCmd) {443 matches = append(matches, cmd)

Support for flags before commandsspf13before adoption10a8494

line 444why, one step back
444 }

adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac

line 445why, one step back
445 }

Support for flags before commandsspf13before adoption10a8494

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

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 449–453why, one step back
449 // only accept a single prefix match - multiple matches would be ambiguous
450 if len(matches) == 1 {451 return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))452 }453

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Support for flags before commandsspf13before adoption10a8494

lines 455–456why, one step back
455 }
456

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

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

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

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 459–463why, one step back
459
460 // no subcommand, always take args461 if !commandFound.HasSubCommands() {462 return commandFound, a, nil463 }

Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311

line 464why, one step back
464

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

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

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

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

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

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

Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311

lines 468–471why, one step back
468 if !c.DisableSuggestions {
469 if c.SuggestionsMinimumDistance <= 0 {470 c.SuggestionsMinimumDistance = 2471 }

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

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

Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311

lines 476–478why, one step back
476 }
477 }478 }

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

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

Support for flags before commandsspf13before adoption10a8494

lines 480–482why, one step back
480 }
481482 return commandFound, a, nil

Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673

lines 483–502why, one step back
483}
484485func (c *Command) SuggestionsFor(typedName string) []string {486 suggestions := []string{}487 for _, cmd := range c.commands {488 if cmd.IsAvailableCommand() {489 levenshteinDistance := ld(typedName, cmd.Name(), true)490 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance491 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))492 if suggestByLevenshtein || suggestByPrefix {493 suggestions = append(suggestions, cmd.Name())494 }495 for _, explicitSuggestion := range cmd.SuggestFor {496 if strings.EqualFold(typedName, explicitSuggestion) {497 suggestions = append(suggestions, cmd.Name())498 }499 }500 }501 }502 return suggestions

Support for flags before commandsspf13before adoption10a8494

lines 503–504why, one step back
503}
504

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

lines 505–519why, one step back
505func (c *Command) VisitParents(fn func(*Command)) {
506 var traverse func(*Command) *Command507508 traverse = func(x *Command) *Command {509 if x != c {510 fn(x)511 }512 if x.HasParent() {513 return traverse(x.parent)514 }515 return x516 }517 traverse(c)518}519

Support for flags before commandsspf13before adoption10a8494

lines 520–526why, one step back
520func (c *Command) Root() *Command {
521 var findRoot func(*Command) *Command522523 findRoot = func(x *Command) *Command {524 if x.HasParent() {525 return findRoot(x.parent)526 }

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

line 527why, one step back
527 return x

Support for flags before commandsspf13before adoption10a8494

lines 528–532why, one step back
528 }
529530 return findRoot(c)531}532

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

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

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

lines 537–540why, one step back
537func (c *Command) ArgsLenAtDash() int {
538 return c.Flags().ArgsLenAtDash()539}540

Support for flags before commandsspf13before adoption10a8494

lines 541–543why, one step back
541func (c *Command) execute(a []string) (err error) {
542 if c == nil {543 return fmt.Errorf("Called Execute() on a nil Command")

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

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

Support for flags before commandsspf13before adoption10a8494

lines 548–549why, one step back
548 }
549

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

lines 550–553why, one step back
550 // initialize help flag as the last point possible to allow for user
551 // overriding552 c.initHelpFlag()553

Support for flags before commandsspf13before adoption10a8494

lines 554–556why, one step back
554 err = c.ParseFlags(a)
555 if err != nil {556 return err

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

line 557why, one step back
557 }

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

line 558why, one step back
558 // 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 559why, one step back
559 // 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 560–566why, one step back
560 helpVal, err := c.Flags().GetBool("help")
561 if err != nil {562 // should be impossible to get here as we always declare a help563 // flag in initHelpFlag()564 c.Println("\"help\" flag declared as non-bool. Please correct your code")565 return err566 }

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

line 567why, one step back
567

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

line 568why, one step back
568 if helpVal || !c.Runnable() {

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

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

Support for flags before commandsspf13before adoption10a8494

line 570why, one step back
570 }

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

lines 571–572why, one step back
571
572 c.preRun()

Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048

line 573why, one step back
573

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

line 574why, one step back
574 argWoFlags := c.Flags().Args()

Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048

lines 575–577why, one step back
575 if c.DisableFlagParsing {
576 argWoFlags = a577 }

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

line 578why, one step back
578

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

Merge pull request #164 from vikstrous/fix_bugEric Parisbefore adoptiond732ab3

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 582–585why, one step back
582 return err
583 }584 break585 } else if p.PersistentPreRun != nil {

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

lines 586–588why, one step back
586 p.PersistentPreRun(c, argWoFlags)
587 break588 }

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

line 589why, one step back
589 }

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 590–594why, one step back
590 if c.PreRunE != nil {
591 if err := c.PreRunE(c, argWoFlags); err != nil {592 return err593 }594 } else if c.PreRun != nil {

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

lines 595–597why, one step back
595 c.PreRun(c, argWoFlags)
596 }597

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 598–609why, one step back
598 if c.RunE != nil {
599 if err := c.RunE(c, argWoFlags); err != nil {600 return err601 }602 } else {603 c.Run(c, argWoFlags)604 }605 if c.PostRunE != nil {606 if err := c.PostRunE(c, argWoFlags); err != nil {607 return err608 }609 } else if c.PostRun != nil {

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

lines 610–611why, one step back
610 c.PostRun(c, argWoFlags)
611 }

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 613–618why, one step back
613 if p.PersistentPostRunE != nil {
614 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {615 return err616 }617 break618 } else if p.PersistentPostRun != nil {

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

lines 619–621why, one step back
619 p.PersistentPostRun(c, argWoFlags)
620 break621 }

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

lines 622–623why, one step back
622 }
623

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

line 624why, one step back
624 return nil

Support for flags before commandsspf13before adoption10a8494

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

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

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

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

lines 628–630why, one step back
628 for _, x := range initializers {
629 x()630 }

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

lines 631–632why, one step back
631}
632

Support for flags before commandsspf13before adoption10a8494

lines 633–640why, one step back
633func (c *Command) errorMsgFromParse() string {
634 s := c.flagErrorBuf.String()635636 x := strings.Split(s, "\n")637638 if len(x) > 0 {639 return x[0]640 }

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 641why, one step back
641 return ""

Support for flags before commandsspf13before adoption10a8494

lines 642–646why, one step back
642}
643644// Call execute to use the args (os.Args[1:] by default)645// and run through the command tree finding appropriate matches646// for commands and then corresponding flags.

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

lines 647–650why, one step back
647func (c *Command) Execute() error {
648 _, err := c.ExecuteC()649 return err650}

Support for flags before commandsspf13before adoption10a8494

line 651why, one step back
651

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

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

Support for flags before commandsspf13before adoption10a8494

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

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

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

Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29

lines 657–658why, one step back
657 }
658

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

lines 659–661why, one step back
659 // windows hook
660 if preExecHookFn != nil {661 preExecHookFn(c)

Support for flags before commandsspf13before adoption10a8494

lines 662–665why, one step back
662 }
663664 // initialize help as the last point possible to allow for user665 // overriding

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

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

Support for flags before commandsspf13before adoption10a8494

lines 667–669why, one step back
667
668 var args []string669

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

line 670why, one step back
670 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155

Use nil instead of len for arg check.Jonathan Reynabefore adoption1ef0913

line 671why, one step back
671 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {

Support for flags before commandsspf13before adoption10a8494

lines 672–676why, one step back
672 args = os.Args[1:]
673 } else {674 args = c.args675 }676

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

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

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 678–682why, one step back
678 if err != nil {
679 // If found parse to a subcommand and then failed, talk about the subcommand680 if cmd != nil {681 c = cmd682 }

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

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

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

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

Support for flags before commandsspf13before adoption10a8494

line 688why, one step back
688 }

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

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

Support for flags before commandsspf13before adoption10a8494

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

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

lines 691–697why, one step back
691 // Always show help if requested, even if SilenceErrors is in
692 // effect693 if err == flag.ErrHelp {694 cmd.HelpFunc()(cmd, args)695 return cmd, nil696 }697

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

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

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

lines 702–707why, one step back
702 }
703704 // If root command has SilentUsage flagged,705 // all subcommands should respect it706 if !cmd.SilenceUsage && !c.SilenceUsage {707 c.Println(cmd.UsageString())

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

line 708why, one step back
708 }

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

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

Support for flags before commandsspf13before adoption10a8494

line 710why, one step back
710 }

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

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

Support for flags before commandsspf13before adoption10a8494

lines 712–713why, one step back
712}
713

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

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

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

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

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

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

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

line 717why, one step back
717 }

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

lines 718–720why, one step back
718}
719720func (c *Command) initHelpCmd() {

Support for flags before commandsspf13before adoption10a8494

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

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

lines 722–725why, one step back
722 if !c.HasSubCommands() {
723 return724 }725

Support for flags before commandsspf13before adoption10a8494

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

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

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

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

lines 733–737why, one step back
733
734 Run: func(c *Command, args []string) {735 cmd, _, e := c.Root().Find(args)736 if cmd == nil || e != nil {737 c.Printf("Unknown help topic %#q.", args)

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

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

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

line 739why, one step back
739 } else {

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

line 740why, one step back
740 cmd.Help()

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

lines 741–742why, one step back
741 }
742 },

Support for flags before commandsspf13before adoption10a8494

lines 743–747why, one step back
743 }
744 }745 c.AddCommand(c.helpCommand)746}747

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 748why, one step back
748// Used for testing.

Support for flags before commandsspf13before adoption10a8494

lines 749–750why, one step back
749func (c *Command) ResetCommands() {
750 c.commands = nil

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

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

Support for flags before commandsspf13before adoption10a8494

lines 752–753why, one step back
752}
753

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 754why, one step back
754// Sorts commands by their names.

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

lines 755–761why, one step back
755type commandSorterByName []*Command
756757func (c commandSorterByName) Len() int { return len(c) }758func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }759func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }760761// Commands returns a sorted slice of child commands.

Support for flags before commandsspf13before adoption10a8494

line 762why, one step back
762func (c *Command) Commands() []*Command {

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 763why, one step back
763 // do not sort commands if it already sorted or sorting was disabled

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

line 764why, one step back
764 if EnableCommandSorting && !c.commandsAreSorted {

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

lines 765–767why, one step back
765 sort.Sort(commandSorterByName(c.commands))
766 c.commandsAreSorted = true767 }

Support for flags before commandsspf13before adoption10a8494

lines 768–770why, one step back
768 return c.commands
769}770

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Support for flags before commandsspf13before adoption10a8494

lines 772–785why, one step back
772func (c *Command) AddCommand(cmds ...*Command) {
773 for i, x := range cmds {774 if cmds[i] == c {775 panic("Command can't be a child of itself")776 }777 cmds[i].parent = c778 // update max lengths779 usageLen := len(x.Use)780 if usageLen > c.commandsMaxUseLen {781 c.commandsMaxUseLen = usageLen782 }783 commandPathLen := len(x.CommandPath())784 if commandPathLen > c.commandsMaxCommandPathLen {785 c.commandsMaxCommandPathLen = commandPathLen

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

lines 786–789why, one step back
786 }
787 nameLen := len(x.Name())788 if nameLen > c.commandsMaxNameLen {789 c.commandsMaxNameLen = nameLen

Support for flags before commandsspf13before adoption10a8494

line 790why, one step back
790 }

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

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

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

lines 792–794why, one step back
792 if c.globNormFunc != nil {
793 x.SetGlobalNormalizationFunc(c.globNormFunc)794 }

Support for flags before commandsspf13before adoption10a8494

line 795why, one step back
795 c.commands = append(c.commands, x)

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 796why, one step back
796 c.commandsAreSorted = false

Support for flags before commandsspf13before adoption10a8494

lines 797–799why, one step back
797 }
798}799

Merge pull request #278 from kevintpeng/patch-1Eric Parisbefore adoptionf368244

line 800why, one step back
800// RemoveCommand removes one or more commands from a parent command.

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

lines 801–833why, one step back
801func (c *Command) RemoveCommand(cmds ...*Command) {
802 commands := []*Command{}803main:804 for _, command := range c.commands {805 for _, cmd := range cmds {806 if command == cmd {807 command.parent = nil808 continue main809 }810 }811 commands = append(commands, command)812 }813 c.commands = commands814 // recompute all lengths815 c.commandsMaxUseLen = 0816 c.commandsMaxCommandPathLen = 0817 c.commandsMaxNameLen = 0818 for _, command := range c.commands {819 usageLen := len(command.Use)820 if usageLen > c.commandsMaxUseLen {821 c.commandsMaxUseLen = usageLen822 }823 commandPathLen := len(command.CommandPath())824 if commandPathLen > c.commandsMaxCommandPathLen {825 c.commandsMaxCommandPathLen = commandPathLen826 }827 nameLen := len(command.Name())828 if nameLen > c.commandsMaxNameLen {829 c.commandsMaxNameLen = nameLen830 }831 }832}833

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 834why, one step back
834// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.

Support for flags before commandsspf13before adoption10a8494

line 835why, one step back
835func (c *Command) Print(i ...interface{}) {

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

line 836why, one step back
836 fmt.Fprint(c.OutOrStderr(), i...)

Support for flags before commandsspf13before adoption10a8494

lines 837–838why, one step back
837}
838

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 839why, one step back
839// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.

Support for flags before commandsspf13before adoption10a8494

lines 840–844why, one step back
840func (c *Command) Println(i ...interface{}) {
841 str := fmt.Sprintln(i...)842 c.Print(str)843}844

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 845why, one step back
845// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.

Support for flags before commandsspf13before adoption10a8494

lines 846–850why, one step back
846func (c *Command) Printf(format string, i ...interface{}) {
847 str := fmt.Sprintf(format, i...)848 c.Print(str)849}850

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Support for flags before commandsspf13before adoption10a8494

lines 852–861why, one step back
852func (c *Command) CommandPath() string {
853 str := c.Name()854 x := c855 for x.HasParent() {856 str = x.parent.Name() + " " + str857 x = x.parent858 }859 return str860}861

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 862why, one step back
862// UseLine puts out the full usage for a given command (including parents).

Support for flags before commandsspf13before adoption10a8494

lines 863–871why, one step back
863func (c *Command) UseLine() string {
864 str := ""865 if c.HasParent() {866 str = c.parent.CommandPath() + " "867 }868 return str + c.Use869}870871// For use in determining which flags have been assigned to which commands

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 872why, one step back
872// and which persist.

Support for flags before commandsspf13before adoption10a8494

lines 873–926why, one step back
873func (c *Command) DebugFlags() {
874 c.Println("DebugFlags called on", c.Name())875 var debugflags func(*Command)876877 debugflags = func(x *Command) {878 if x.HasFlags() || x.HasPersistentFlags() {879 c.Println(x.Name())880 }881 if x.HasFlags() {882 x.flags.VisitAll(func(f *flag.Flag) {883 if x.HasPersistentFlags() {884 if x.persistentFlag(f.Name) == nil {885 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")886 } else {887 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")888 }889 } else {890 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")891 }892 })893 }894 if x.HasPersistentFlags() {895 x.pflags.VisitAll(func(f *flag.Flag) {896 if x.HasFlags() {897 if x.flags.Lookup(f.Name) == nil {898 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")899 }900 } else {901 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")902 }903 })904 }905 c.Println(x.flagErrorBuf)906 if x.HasSubCommands() {907 for _, y := range x.commands {908 debugflags(y)909 }910 }911 }912913 debugflags(c)914}915916// Name returns the command's name: the first word in the use line.917func (c *Command) Name() string {918 if c.name != "" {919 return c.name920 }921 name := c.Use922 i := strings.Index(name, " ")923 if i >= 0 {924 name = name[:i]925 }926 return name

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 927–928why, one step back
927}
928

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 929why, one step back
929// HasAlias determines if a given string is an alias of the command.

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 930–940why, one step back
930func (c *Command) HasAlias(s string) bool {
931 for _, a := range c.Aliases {932 if a == s {933 return true934 }935 }936 return false937}938939func (c *Command) NameAndAliases() string {940 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 941–944why, one step back
941}
942943func (c *Command) HasExample() bool {944 return len(c.Example) > 0

Support for flags before commandsspf13before adoption10a8494

lines 945–946why, one step back
945}
946

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 947why, one step back
947// Runnable determines if the command is itself runnable.

Support for flags before commandsspf13before adoption10a8494

line 948why, one step back
948func (c *Command) Runnable() bool {

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

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

Support for flags before commandsspf13before adoption10a8494

lines 950–951why, one step back
950}
951

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 952why, one step back
952// HasSubCommands determines if the command has children commands.

Support for flags before commandsspf13before adoption10a8494

lines 953–954why, one step back
953func (c *Command) HasSubCommands() bool {
954 return len(c.commands) > 0

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

lines 955–956why, one step back
955}
956

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

line 957why, one step back
957// IsAvailableCommand determines if a command is available as a non-help command

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 958why, one step back
958// (this includes all non deprecated/hidden commands).

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

line 959why, one step back
959func (c *Command) IsAvailableCommand() bool {

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

lines 960–962why, one step back
960 if len(c.Deprecated) != 0 || c.Hidden {
961 return false962 }

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

line 963why, one step back
963

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

lines 964–967why, one step back
964 if c.HasParent() && c.Parent().helpCommand == c {
965 return false966 }967

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

lines 968–972why, one step back
968 if c.Runnable() || c.HasAvailableSubCommands() {
969 return true970 }971972 return false

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

lines 973–976why, one step back
973}
974975// IsHelpCommand determines if a command is a 'help' command; a help command is976// determined by the fact that it is NOT runnable/hidden/deprecated, and has no

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 977why, one step back
977// sub commands that are runnable/hidden/deprecated.

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

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

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

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

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

lines 982–983why, one step back
982 return false
983 }

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

lines 984–985why, one step back
984
985 // 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 986–989why, one step back
986 for _, sub := range c.commands {
987 if !sub.IsHelpCommand() {988 return false989 }

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

line 990why, one step back
990 }

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

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

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 993why, one step back
993 return true

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

lines 994–995why, one step back
994}
995

Merge pull request #327 from bogem/fixesEric Parisbefore adoption1f47171

line 996why, one step back
996// HasHelpSubCommands determines if a command has any available 'help' sub commands

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

line 997why, one step back
997// that need to be shown in the usage/help default template under 'additional help

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 998why, one step back
998// topics'.

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

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

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

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

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

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

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

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

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

lines 1004–1006why, one step back
1004 return true
1005 }1006 }

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

lines 1007–1008why, one step back
1007
1008 // 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 1009–1011why, one step back
1009 return false
1010}1011

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

line 1012why, one step back
1012// HasAvailableSubCommands determines if a command has available sub commands that

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1013why, one step back
1013// need to be shown in the usage/help default template under 'available commands'.

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

lines 1014–1017why, one step back
1014func (c *Command) HasAvailableSubCommands() bool {
10151016 // return true on the first found available (non deprecated/help/hidden)1017 // sub command

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

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

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

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

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

lines 1020–1022why, one step back
1020 return true
1021 }1022 }

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

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

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

line 1026why, one step back
1026 return false

Support for flags before commandsspf13before adoption10a8494

lines 1027–1028why, one step back
1027}
1028

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1029why, one step back
1029// HasParent determines if the command is a child command.

Support for flags before commandsspf13before adoption10a8494

lines 1030–1031why, one step back
1030func (c *Command) HasParent() bool {
1031 return c.parent != nil

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

lines 1032–1033why, one step back
1032}
1033

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1034why, one step back
1034// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists.

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

lines 1035–1036why, one step back
1035func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
1036 return c.globNormFunc

Support for flags before commandsspf13before adoption10a8494

lines 1037–1038why, one step back
1037}
1038

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

lines 1039–1040why, one step back
1039// Flage returns the complete FlagSet that applies
1040// to this command (local and persistent declared here and by all parents).

Support for flags before commandsspf13before adoption10a8494

lines 1041–1051why, one step back
1041func (c *Command) Flags() *flag.FlagSet {
1042 if c.flags == nil {1043 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1044 if c.flagErrorBuf == nil {1045 c.flagErrorBuf = new(bytes.Buffer)1046 }1047 c.flags.SetOutput(c.flagErrorBuf)1048 }1049 return c.flags1050}1051

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1052why, one step back
1052// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.

Merge pull request #288 from eparis/flags-vs-commandsEric Parisbefore adoptionc21ee9d

lines 1053–1064why, one step back
1053func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
1054 persistentFlags := c.PersistentFlags()10551056 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1057 c.LocalFlags().VisitAll(func(f *flag.Flag) {1058 if persistentFlags.Lookup(f.Name) == nil {1059 out.AddFlag(f)1060 }1061 })1062 return out1063}1064

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1065why, one step back
1065// LocalFlags returns the local FlagSet specifically set in the current command.

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1066–1069why, one step back
1066func (c *Command) LocalFlags() *flag.FlagSet {
1067 c.mergePersistentFlags()10681069 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 1072why, one step back
1072 })

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

lines 1073–1079why, one step back
1073 if !c.HasParent() {
1074 flag.CommandLine.VisitAll(func(f *flag.Flag) {1075 if local.Lookup(f.Name) == nil {1076 local.AddFlag(f)1077 }1078 })1079 }

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1080–1082why, one step back
1080 return local
1081}1082

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1083why, one step back
1083// InheritedFlags returns all flags which were inherited from parents commands.

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

lines 1084–1086why, one step back
1084func (c *Command) InheritedFlags() *flag.FlagSet {
1085 c.mergePersistentFlags()1086

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

line 1089why, one step back
1089

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

line 1091why, one step back
1091

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 1092–1103why, one step back
1092 rmerge = func(x *Command) {
1093 if x.HasPersistentFlags() {1094 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1095 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1096 inherited.AddFlag(f)1097 }1098 })1099 }1100 if x.HasParent() {1101 rmerge(x.parent)1102 }1103 }

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

lines 1104–1108why, one step back
1104
1105 if c.HasParent() {1106 rmerge(c.parent)1107 }1108

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 1109why, one step back
1109 return inherited

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

lines 1110–1111why, one step back
1110}
1111

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1112why, one step back
1112// NonInheritedFlags returns all flags which were not inherited from parent commands.

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

line 1113why, one step back
1113func (c *Command) NonInheritedFlags() *flag.FlagSet {

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

lines 1115–1116why, one step back
1115}
1116

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1117why, one step back
1117// PersistentFlags returns the persistent FlagSet specifically set in the current command.

Support for flags before commandsspf13before adoption10a8494

lines 1118–1128why, one step back
1118func (c *Command) PersistentFlags() *flag.FlagSet {
1119 if c.pflags == nil {1120 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1121 if c.flagErrorBuf == nil {1122 c.flagErrorBuf = new(bytes.Buffer)1123 }1124 c.pflags.SetOutput(c.flagErrorBuf)1125 }1126 return c.pflags1127}1128

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1129why, one step back
1129// ResetFlags is used in testing.

Support for flags before commandsspf13before adoption10a8494

lines 1130–1138why, one step back
1130func (c *Command) ResetFlags() {
1131 c.flagErrorBuf = new(bytes.Buffer)1132 c.flagErrorBuf.Reset()1133 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1134 c.flags.SetOutput(c.flagErrorBuf)1135 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1136 c.pflags.SetOutput(c.flagErrorBuf)1137}1138

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Support for flags before commandsspf13before adoption10a8494

lines 1140–1143why, one step back
1140func (c *Command) HasFlags() bool {
1141 return c.Flags().HasFlags()1142}1143

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1144why, one step back
1144// Does the command contain persistent flags.

Support for flags before commandsspf13before adoption10a8494

lines 1145–1148why, one step back
1145func (c *Command) HasPersistentFlags() bool {
1146 return c.PersistentFlags().HasFlags()1147}1148

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1149why, one step back
1149// Does the command has flags specifically declared locally.

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1150–1153why, one step back
1150func (c *Command) HasLocalFlags() bool {
1151 return c.LocalFlags().HasFlags()1152}1153

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1154why, one step back
1154// Does the command have flags inherited from its parent command.

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 1155–1156why, one step back
1155func (c *Command) HasInheritedFlags() bool {
1156 return c.InheritedFlags().HasFlags()

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1157–1159why, one step back
1157}
11581159// Does the command contain any flags (local plus persistent from the entire

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1160why, one step back
1160// structure) which are not hidden or deprecated.

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1161–1164why, one step back
1161func (c *Command) HasAvailableFlags() bool {
1162 return c.Flags().HasAvailableFlags()1163}1164

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1165why, one step back
1165// Does the command contain persistent flags which are not hidden or deprecated.

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1166–1170why, one step back
1166func (c *Command) HasAvailablePersistentFlags() bool {
1167 return c.PersistentFlags().HasAvailableFlags()1168}11691170// Does the command has flags specifically declared locally which are not hidden

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1171why, one step back
1171// or deprecated.

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1172–1176why, one step back
1172func (c *Command) HasAvailableLocalFlags() bool {
1173 return c.LocalFlags().HasAvailableFlags()1174}11751176// Does the command have flags inherited from its parent command which are

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1177why, one step back
1177// not hidden or deprecated.

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1178–1179why, one step back
1178func (c *Command) HasAvailableInheritedFlags() bool {
1179 return c.InheritedFlags().HasAvailableFlags()

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 1180–1181why, one step back
1180}
1181

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1182why, one step back
1182// Flag climbs up the command tree looking for matching flag.

Support for flags before commandsspf13before adoption10a8494

lines 1183–1192why, one step back
1183func (c *Command) Flag(name string) (flag *flag.Flag) {
1184 flag = c.Flags().Lookup(name)11851186 if flag == nil {1187 flag = c.persistentFlag(name)1188 }11891190 return1191}1192

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1193why, one step back
1193// Recursively find matching persistent flag.

Support for flags before commandsspf13before adoption10a8494

lines 1194–1204why, one step back
1194func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
1195 if c.HasPersistentFlags() {1196 flag = c.PersistentFlags().Lookup(name)1197 }11981199 if flag == nil && c.HasParent() {1200 flag = c.parent.persistentFlag(name)1201 }1202 return1203}1204

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1205why, one step back
1205// ParseFlags parses persistent flag tree and local flags.

Support for flags before commandsspf13before adoption10a8494

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

Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048

lines 1207–1209why, one step back
1207 if c.DisableFlagParsing {
1208 return nil1209 }

Support for flags before commandsspf13before adoption10a8494

lines 1210–1211why, one step back
1210 c.mergePersistentFlags()
1211 err = c.Flags().Parse(args)

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

line 1212why, one step back
1212 return

Support for flags before commandsspf13before adoption10a8494

lines 1213–1214why, one step back
1213}
1214

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1215why, one step back
1215// Parent returns a commands parent command.

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1216–1219why, one step back
1216func (c *Command) Parent() *Command {
1217 return c.parent1218}1219

Support for flags before commandsspf13before adoption10a8494

lines 1220–1222why, one step back
1220func (c *Command) mergePersistentFlags() {
1221 var rmerge func(x *Command)1222

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 1223–1235why, one step back
1223 // Save the set of local flags
1224 if c.lflags == nil {1225 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1226 if c.flagErrorBuf == nil {1227 c.flagErrorBuf = new(bytes.Buffer)1228 }1229 c.lflags.SetOutput(c.flagErrorBuf)1230 addtolocal := func(f *flag.Flag) {1231 c.lflags.AddFlag(f)1232 }1233 c.Flags().VisitAll(addtolocal)1234 c.PersistentFlags().VisitAll(addtolocal)1235 }

Support for flags before commandsspf13before adoption10a8494

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

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

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

Merge pull request #75 from eparis/CommandLineEric Parisbefore adoption2d5fab0

lines 1238–1243why, one step back
1238 flag.CommandLine.VisitAll(func(f *flag.Flag) {
1239 if x.PersistentFlags().Lookup(f.Name) == nil {1240 x.PersistentFlags().AddFlag(f)1241 }1242 })1243 }

Support for flags before commandsspf13before adoption10a8494

lines 1244–1257why, one step back
1244 if x.HasPersistentFlags() {
1245 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1246 if c.Flags().Lookup(f.Name) == nil {1247 c.Flags().AddFlag(f)1248 }1249 })1250 }1251 if x.HasParent() {1252 rmerge(x.parent)1253 }1254 }12551256 rmerge(c)1257}