Skip to content
Myr

command.go

This file

Path

command.go

1,115 lines · 28.4 KiB · Go

Last changed by

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

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"

Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29

line 23why, one step back
23 "runtime"

Organize the files a bit betterspf13before adoption62fb674

line 24why, one step back
24 "strings"

Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29

line 25why, one step back
25 "time"

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Organize the files a bit betterspf13before adoption62fb674

lines 29–39why, one step back
29)
3031// Command is just that, a command for your application.32// eg. 'go run' ... 'run' is the command. Cobra requires33// you to define the usage and description as part of your command34// definition to ensure usability.35type Command struct {36 // Name is the command name, usually the executable's name.37 name string38 // The one-line usage message.39 Use string

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 40–41why, one step back
40 // An array of aliases that can be used instead of the first word in Use.
41 Aliases []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 #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

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

Organize the files a bit betterspf13before adoption62fb674

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

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

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

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

Organize the files a bit betterspf13before adoption62fb674

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

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

line 92why, one step back
92 parent *Command

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 93–95why, one step back
93 // max lengths of commands' string lengths for use in padding
94 commandsMaxUseLen int95 commandsMaxCommandPathLen int

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

line 96why, one step back
96 commandsMaxNameLen int

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

line 97why, one step back
97

Organize the files a bit betterspf13before adoption62fb674

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

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

line 99why, one step back
99

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Documentation updatespf13before adoption59bd285

line 101why, one step back
101 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 102–106why, one step back
102 usageFunc func(*Command) error // Usage can be defined by application
103 usageTemplate string // Can be defined by Application104 helpTemplate string // Can be defined by Application105 helpFunc func(*Command, []string) // Help can be defined by application106 helpCommand *Command // The help command

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

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

Organize the files a bit betterspf13before adoption62fb674

lines 109–110why, one step back
109}
110

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

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

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 115–116why, one step back
115}
116

Default usage output to stdoutEric Parisbefore adoption6de96b8

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

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

lines 118–124why, one step back
118 if c.output != nil {
119 return *c.output120 }121122 if c.HasParent() {123 return c.parent.Out()124 } else {

Default usage output to stdoutEric Parisbefore adoption6de96b8

line 125why, one step back
125 return def

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

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

Default usage output to stdoutEric Parisbefore adoption6de96b8

lines 129–136why, one step back
129func (c *Command) Out() io.Writer {
130 return c.getOut(os.Stderr)131}132133func (c *Command) getOutOrStdout() io.Writer {134 return c.getOut(os.Stdout)135}136

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

lines 137–166why, one step back
137// 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}142143// Usage can be defined by application144func (c *Command) SetUsageFunc(f func(*Command) error) {145 c.usageFunc = f146}147148// Can be defined by Application149func (c *Command) SetUsageTemplate(s string) {150 c.usageTemplate = s151}152153// Can be defined by Application154func (c *Command) SetHelpFunc(f func(*Command, []string)) {155 c.helpFunc = f156}157158func (c *Command) SetHelpCommand(cmd *Command) {159 c.helpCommand = cmd160}161162// Can be defined by Application163func (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

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

lines 179–188why, one step back
179func (c *Command) UsageFunc() (f func(*Command) error) {
180 if c.usageFunc != nil {181 return c.usageFunc182 }183184 if c.HasParent() {185 return c.parent.UsageFunc()186 } else {187 return func(c *Command) error {188 err := tmpl(c.Out(), c.UsageTemplate(), c)

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

lines 189–191why, one step back
189 if err != nil {
190 fmt.Print(err)191 }

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

lines 192–195why, one step back
192 return err
193 }194 }195}

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

lines 196–198why, one step back
196
197// HelpFunc returns either the function set by SetHelpFunc for this command198// 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 199why, one step back
199func (c *Command) HelpFunc() func(*Command, []string) {

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

lines 200–205why, one step back
200 cmd := c
201 for cmd != nil {202 if cmd.helpFunc != nil {203 return cmd.helpFunc204 }205 cmd = cmd.parent

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

line 206why, one step back
206 }

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

lines 207–210why, one step back
207 return func(*Command, []string) {
208 err := c.Help()209 if err != nil {210 c.Println(err)

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

lines 211–214why, one step back
211 }
212 }213}214

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 215–226why, one step back
215var minUsagePadding int = 25
216217func (c *Command) UsagePadding() int {218 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {219 return minUsagePadding220 } else {221 return c.parent.commandsMaxUseLen222 }223}224225var minCommandPathPadding int = 11226

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 227why, one step back
227//

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 228–235why, one step back
228func (c *Command) CommandPathPadding() int {
229 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {230 return minCommandPathPadding231 } else {232 return c.parent.commandsMaxCommandPathLen233 }234}235

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

lines 236–245why, one step back
236var minNamePadding int = 11
237238func (c *Command) NamePadding() int {239 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {240 return minNamePadding241 } else {242 return c.parent.commandsMaxNameLen243 }244}245

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

lines 246–253why, one step back
246func (c *Command) UsageTemplate() string {
247 if c.usageTemplate != "" {248 return c.usageTemplate249 }250251 if c.HasParent() {252 return c.parent.UsageTemplate()253 } else {

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

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

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

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

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 256–258why, one step back
256 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
257258Aliases:

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 259–260why, one step back
259 {{.NameAndAliases}}
260{{end}}{{if .HasExample}}

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 261why, one step back
261

New "example" section of commandsEric Parisbefore adoptionbf480fe

line 262why, one step back
262Examples:

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

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

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 264why, one step back
264

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

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

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

lines 266–268why, one step back
266 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}}
267268Flags:

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

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

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

lines 270–271why, one step back
270
271Global Flags:

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

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

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 273why, one step back
273

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

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

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

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

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 276why, one step back
276

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

line 277why, one step back
277Use "{{.CommandPath}} [command] --help" for more information about a command.

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

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

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

lines 279–289why, one step back
279 }
280}281282func (c *Command) HelpTemplate() string {283 if c.helpTemplate != "" {284 return c.helpTemplate285 }286287 if c.HasParent() {288 return c.parent.HelpTemplate()289 } else {

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

lines 290–292why, one step back
290 return `{{with or .Long .Short }}{{. | trim}}
291292{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`

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

lines 293–295why, one step back
293 }
294}295

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 296–302why, one step back
296// Really only used when casting a command to a commander
297func (c *Command) resetChildrensParents() {298 for _, x := range c.commands {299 x.parent = c300 }301}302

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

lines 303–313why, one step back
303// Test if the named flag is a boolean flag.
304func isBooleanFlag(name string, f *flag.FlagSet) bool {305 flag := f.Lookup(name)306 if flag == nil {307 return false308 }309 return flag.Value.Type() == "bool"310}311312// Test if the named flag is a boolean flag.313func isBooleanShortFlag(name string, f *flag.FlagSet) bool {

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

lines 314–319why, one step back
314 result := false
315 f.VisitAll(func(f *flag.Flag) {316 if f.Shorthand == name && f.Value.Type() == "bool" {317 result = true318 }319 })

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

lines 320–323why, one step back
320 return result
321}322323func stripFlags(args []string, c *Command) []string {

Support for flags before commandsspf13before adoption10a8494

lines 324–326why, one step back
324 if len(args) < 1 {
325 return args326 }

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

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

Support for flags before commandsspf13before adoption10a8494

lines 328–331why, one step back
328
329 commands := []string{}330331 inQuote := false

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

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

Support for flags before commandsspf13before adoption10a8494

lines 333–339why, one step back
333 for _, y := range args {
334 if !inQuote {335 switch {336 case strings.HasPrefix(y, "\""):337 inQuote = true338 case strings.Contains(y, "=\""):339 inQuote = true

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

lines 340–346why, one step back
340 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
341 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'342 inFlag = !isBooleanFlag(y[2:], c.Flags())343 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):344 inFlag = true345 case inFlag:346 inFlag = false

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

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

Support for flags before commandsspf13before adoption10a8494

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

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

line 351why, one step back
351 inFlag = false

Support for flags before commandsspf13before adoption10a8494

lines 352–362why, one step back
352 }
353 }354355 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {356 inQuote = false357 }358 }359360 return commands361}362

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

lines 363–371why, one step back
363// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
364// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).365func argsMinusFirstX(args []string, x string) []string {366 for i, y := range args {367 if x == y {368 ret := []string{}369 ret = append(ret, args[:i]...)370 ret = append(ret, args[i+1:]...)371 return ret

Support for flags before commandsspf13before adoption10a8494

lines 372–373why, one step back
372 }
373 }

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

line 374why, one step back
374 return args

Support for flags before commandsspf13before adoption10a8494

lines 375–376why, one step back
375}
376

Organize the files a bit betterspf13before adoption62fb674

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

Add support for help commandspf13before adoptionfb2146e

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

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Organize the files a bit betterspf13before adoption62fb674

lines 380–383why, one step back
380 if c == nil {
381 return nil, nil, fmt.Errorf("Called find() on a nil Command")382 }383

Finding command based on args cleaned upspf13before adoption55ff474

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

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 387–403why, one step back
387 argsWOflags := stripFlags(innerArgs, c)
388 if len(argsWOflags) == 0 {389 return c, innerArgs390 }391 nextSubCmd := argsWOflags[0]392 matches := make([]*Command, 0)393 for _, cmd := range c.commands {394 if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match395 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))396 }397 if EnablePrefixMatching {398 if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match399 matches = append(matches, cmd)400 }401 for _, x := range cmd.Aliases {402 if strings.HasPrefix(x, nextSubCmd) {403 matches = append(matches, cmd)

Support for flags before commandsspf13before adoption10a8494

line 404why, one step back
404 }

adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac

line 405why, one step back
405 }

Organize the files a bit betterspf13before adoption62fb674

lines 406–407why, one step back
406 }
407 }

Finding command based on args cleaned upspf13before adoption55ff474

line 408why, one step back
408

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 409–413why, one step back
409 // only accept a single prefix match - multiple matches would be ambiguous
410 if len(matches) == 1 {411 return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))412 }413

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

Organize the files a bit betterspf13before adoption62fb674

line 415why, one step back
415 }

Finding command based on args cleaned upspf13before adoption55ff474

line 416why, one step back
416

Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d

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

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

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

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 419–424why, one step back
419
420 // no subcommand, always take args421 if !commandFound.HasSubCommands() {422 return commandFound, a, nil423 }424 // root command with subcommands, do subcommand checking

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

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

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

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

Organize the files a bit betterspf13before adoption62fb674

lines 427–428why, one step back
427 }
428

Finding command based on args cleaned upspf13before adoption55ff474

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

Organize the files a bit betterspf13before adoption62fb674

lines 430–431why, one step back
430}
431

Add support for help commandspf13before adoptionfb2146e

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

Organize the files a bit betterspf13before adoption62fb674

lines 433–441why, one step back
433 var findRoot func(*Command) *Command
434435 findRoot = func(x *Command) *Command {436 if x.HasParent() {437 return findRoot(x.parent)438 } else {439 return x440 }441 }

Add support for help commandspf13before adoptionfb2146e

lines 442–445why, one step back
442
443 return findRoot(c)444}445

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

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

Organize the files a bit betterspf13before adoption62fb674

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

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

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

Organize the files a bit betterspf13before adoption62fb674

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

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

lines 455–458why, one step back
455 // initialize help flag as the last point possible to allow for user
456 // overriding457 c.initHelpFlag()458

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

lines 459–461why, one step back
459 err = c.ParseFlags(a)
460 if err != nil {461 return err

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

line 462why, one step back
462 }

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

line 463why, one step back
463 // 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 464why, one step back
464 // 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 465–472why, one step back
465 helpVal, err := c.Flags().GetBool("help")
466 if err != nil {467 // should be impossible to get here as we always declare a help468 // flag in initHelpFlag()469 c.Println("\"help\" flag declared as non-bool. Please correct your code")470 return err471 }472 if helpVal || !c.Runnable() {

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

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

Organize the files a bit betterspf13before adoption62fb674

line 474why, one step back
474 }

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

lines 475–477why, one step back
475
476 c.preRun()477 argWoFlags := c.Flags().Args()

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

line 478why, one step back
478

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 480–485why, one step back
480 if p.PersistentPreRunE != nil {
481 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {482 return err483 }484 break485 } else if p.PersistentPreRun != nil {

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

lines 486–488why, one step back
486 p.PersistentPreRun(c, argWoFlags)
487 break488 }

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

line 489why, one step back
489 }

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 490–494why, one step back
490 if c.PreRunE != nil {
491 if err := c.PreRunE(c, argWoFlags); err != nil {492 return err493 }494 } else if c.PreRun != nil {

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

lines 495–497why, one step back
495 c.PreRun(c, argWoFlags)
496 }497

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 498–509why, one step back
498 if c.RunE != nil {
499 if err := c.RunE(c, argWoFlags); err != nil {500 return err501 }502 } else {503 c.Run(c, argWoFlags)504 }505 if c.PostRunE != nil {506 if err := c.PostRunE(c, argWoFlags); err != nil {507 return err508 }509 } else if c.PostRun != nil {

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

lines 510–511why, one step back
510 c.PostRun(c, argWoFlags)
511 }

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

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

Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674

lines 513–518why, one step back
513 if p.PersistentPostRunE != nil {
514 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {515 return err516 }517 break518 } else if p.PersistentPostRun != nil {

Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14

lines 519–521why, one step back
519 p.PersistentPostRun(c, argWoFlags)
520 break521 }

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

lines 522–523why, one step back
522 }
523

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

line 524why, one step back
524 return nil

Organize the files a bit betterspf13before adoption62fb674

lines 525–526why, one step back
525}
526

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

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

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

lines 528–530why, one step back
528 for _, x := range initializers {
529 x()530 }

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

lines 531–532why, one step back
531}
532

Support for flags before commandsspf13before adoption10a8494

lines 533–544why, one step back
533func (c *Command) errorMsgFromParse() string {
534 s := c.flagErrorBuf.String()535536 x := strings.Split(s, "\n")537538 if len(x) > 0 {539 return x[0]540 } else {541 return ""542 }543}544

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

lines 545–552why, one step back
545// Call execute to use the args (os.Args[1:] by default)
546// and run through the command tree finding appropriate matches547// for commands and then corresponding flags.548func (c *Command) Execute() (err error) {549550 // Regardless of what command execute is called on, run on Root only551 if c.HasParent() {552 return c.Root().Execute()

Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29

lines 553–560why, one step back
553 }
554555 if EnableWindowsMouseTrap && runtime.GOOS == "windows" {556 if mousetrap.StartedByExplorer() {557 c.Print(MousetrapHelpText)558 time.Sleep(5 * time.Second)559 os.Exit(1)560 }

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

lines 561–564why, one step back
561 }
562563 // initialize help as the last point possible to allow for user564 // overriding

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

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

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

lines 566–574why, one step back
566
567 var args []string568569 if len(c.args) == 0 {570 args = os.Args[1:]571 } else {572 args = c.args573 }574

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

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

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 576–583why, one step back
576 if err != nil {
577 // If found parse to a subcommand and then failed, talk about the subcommand578 if cmd != nil {579 c = cmd580 }581 c.Println("Error:", err.Error())582 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())583 return err

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

lines 584–585why, one step back
584 }
585

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

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

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

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

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

line 588why, one step back
588 if err == flag.ErrHelp {

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

line 589why, one step back
589 cmd.HelpFunc()(cmd, args)

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

line 590why, one step back
590 return nil

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

line 591why, one step back
591 }

Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710

lines 592–593why, one step back
592 c.Println(cmd.UsageString())
593 c.Println("Error:", err.Error())

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

lines 594–598why, one step back
594 }
595596 return597}598

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

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

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

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

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

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

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

line 602why, one step back
602 }

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

lines 603–605why, one step back
603}
604605func (c *Command) initHelpCmd() {

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

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

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

lines 607–610why, one step back
607 if !c.HasSubCommands() {
608 return609 }610

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

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

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

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

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

lines 618–628why, one step back
618
619 Run: func(c *Command, args []string) {620 cmd, _, e := c.Root().Find(args)621 if cmd == nil || e != nil {622 c.Printf("Unknown help topic %#q.", args)623 c.Root().Usage()624 } else {625 helpFunc := cmd.HelpFunc()626 helpFunc(cmd, args)627 }628 },

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

lines 629–633why, one step back
629 }
630 }631 c.AddCommand(c.helpCommand)632}633

Organize the files a bit betterspf13before adoption62fb674

lines 634–636why, one step back
634// Used for testing
635func (c *Command) ResetCommands() {636 c.commands = nil

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

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

Organize the files a bit betterspf13before adoption62fb674

lines 638–639why, one step back
638}
639

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Organize the files a bit betterspf13before adoption62fb674

lines 641–644why, one step back
641func (c *Command) Commands() []*Command {
642 return c.commands643}644

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Organize the files a bit betterspf13before adoption62fb674

lines 646–651why, one step back
646func (c *Command) AddCommand(cmds ...*Command) {
647 for i, x := range cmds {648 if cmds[i] == c {649 panic("Command can't be a child of itself")650 }651 cmds[i].parent = c

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 652–659why, one step back
652 // update max lengths
653 usageLen := len(x.Use)654 if usageLen > c.commandsMaxUseLen {655 c.commandsMaxUseLen = usageLen656 }657 commandPathLen := len(x.CommandPath())658 if commandPathLen > c.commandsMaxCommandPathLen {659 c.commandsMaxCommandPathLen = commandPathLen

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

lines 660–663why, one step back
660 }
661 nameLen := len(x.Name())662 if nameLen > c.commandsMaxNameLen {663 c.commandsMaxNameLen = nameLen

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

line 664why, one step back
664 }

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

lines 665–668why, one step back
665 // If glabal normalization function exists, update all children
666 if c.globNormFunc != nil {667 x.SetGlobalNormalizationFunc(c.globNormFunc)668 }

Organize the files a bit betterspf13before adoption62fb674

lines 669–672why, one step back
669 c.commands = append(c.commands, x)
670 }671}672

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

lines 673–706why, one step back
673// AddCommand removes one or more commands from a parent command.
674func (c *Command) RemoveCommand(cmds ...*Command) {675 commands := []*Command{}676main:677 for _, command := range c.commands {678 for _, cmd := range cmds {679 if command == cmd {680 command.parent = nil681 continue main682 }683 }684 commands = append(commands, command)685 }686 c.commands = commands687 // recompute all lengths688 c.commandsMaxUseLen = 0689 c.commandsMaxCommandPathLen = 0690 c.commandsMaxNameLen = 0691 for _, command := range c.commands {692 usageLen := len(command.Use)693 if usageLen > c.commandsMaxUseLen {694 c.commandsMaxUseLen = usageLen695 }696 commandPathLen := len(command.CommandPath())697 if commandPathLen > c.commandsMaxCommandPathLen {698 c.commandsMaxCommandPathLen = commandPathLen699 }700 nameLen := len(command.Name())701 if nameLen > c.commandsMaxNameLen {702 c.commandsMaxNameLen = nameLen703 }704 }705}706

Organize the files a bit betterspf13before adoption62fb674

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

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

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

Organize the files a bit betterspf13before adoption62fb674

lines 710–725why, one step back
710}
711712// Convenience method to Println to the defined output713func (c *Command) Println(i ...interface{}) {714 str := fmt.Sprintln(i...)715 c.Print(str)716}717718// Convenience method to Printf to the defined output719func (c *Command) Printf(format string, i ...interface{}) {720 str := fmt.Sprintf(format, i...)721 c.Print(str)722}723724// Output the usage for the command725// Used when a user provides invalid input

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

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

Organize the files a bit betterspf13before adoption62fb674

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

Help improvementsspf13before adoption2d02c31

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

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

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

Help improvementsspf13before adoption2d02c31

lines 730–737why, one step back
730 return err
731}732733// Output the help for the command734// Used when a user calls help [command]735// by the default HelpFunc in the commander736func (c *Command) Help() error {737 c.mergePersistentFlags()

Default usage output to stdoutEric Parisbefore adoption6de96b8

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

Organize the files a bit betterspf13before adoption62fb674

lines 739–741why, one step back
739 return err
740}741

fix trailing <nil> on help outputspf13before adoption3958385

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

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

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

fix trailing <nil> on help outputspf13before adoption3958385

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

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

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

fix trailing <nil> on help outputspf13before adoption3958385

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

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

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

fix trailing <nil> on help outputspf13before adoption3958385

lines 748–750why, one step back
748 return bb.String()
749}750

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Organize the files a bit betterspf13before adoption62fb674

lines 752–826why, one step back
752func (c *Command) CommandPath() string {
753 str := c.Name()754 x := c755 for x.HasParent() {756 str = x.parent.Name() + " " + str757 x = x.parent758 }759 return str760}761762//The full usage for a given command (including parents)763func (c *Command) UseLine() string {764 str := ""765 if c.HasParent() {766 str = c.parent.CommandPath() + " "767 }768 return str + c.Use769}770771// For use in determining which flags have been assigned to which commands772// and which persist773func (c *Command) DebugFlags() {774 c.Println("DebugFlags called on", c.Name())775 var debugflags func(*Command)776777 debugflags = func(x *Command) {778 if x.HasFlags() || x.HasPersistentFlags() {779 c.Println(x.Name())780 }781 if x.HasFlags() {782 x.flags.VisitAll(func(f *flag.Flag) {783 if x.HasPersistentFlags() {784 if x.persistentFlag(f.Name) == nil {785 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")786 } else {787 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")788 }789 } else {790 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")791 }792 })793 }794 if x.HasPersistentFlags() {795 x.pflags.VisitAll(func(f *flag.Flag) {796 if x.HasFlags() {797 if x.flags.Lookup(f.Name) == nil {798 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")799 }800 } else {801 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")802 }803 })804 }805 c.Println(x.flagErrorBuf)806 if x.HasSubCommands() {807 for _, y := range x.commands {808 debugflags(y)809 }810 }811 }812813 debugflags(c)814}815816// Name returns the command's name: the first word in the use line.817func (c *Command) Name() string {818 if c.name != "" {819 return c.name820 }821 name := c.Use822 i := strings.Index(name, " ")823 if i >= 0 {824 name = name[:i]825 }826 return name

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 827–840why, one step back
827}
828829// Determine if a given string is an alias of the command.830func (c *Command) HasAlias(s string) bool {831 for _, a := range c.Aliases {832 if a == s {833 return true834 }835 }836 return false837}838839func (c *Command) NameAndAliases() string {840 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 841–844why, one step back
841}
842843func (c *Command) HasExample() bool {844 return len(c.Example) > 0

Organize the files a bit betterspf13before adoption62fb674

lines 845–848why, one step back
845}
846847// Determine if the command is itself runnable848func (c *Command) Runnable() bool {

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

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

Organize the files a bit betterspf13before adoption62fb674

lines 850–854why, one step back
850}
851852// Determine if the command has children commands853func (c *Command) HasSubCommands() bool {854 return len(c.commands) > 0

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

lines 855–856why, one step back
855}
856

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

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

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

lines 860–862why, one step back
860 if len(c.Deprecated) != 0 || c.Hidden {
861 return false862 }

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

line 863why, one step back
863

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

lines 864–867why, one step back
864 if c.HasParent() && c.Parent().helpCommand == c {
865 return false866 }867

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

lines 868–872why, one step back
868 if c.Runnable() || c.HasAvailableSubCommands() {
869 return true870 }871872 return false

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

lines 873–877why, one step back
873}
874875// IsHelpCommand determines if a command is a 'help' command; a help command is876// determined by the fact that it is NOT runnable/hidden/deprecated, and has no877// sub commands that are runnable/hidden/deprecated

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

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

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

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

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

lines 882–883why, one step back
882 return false
883 }

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

lines 884–885why, one step back
884
885 // 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 886–889why, one step back
886 for _, sub := range c.commands {
887 if !sub.IsHelpCommand() {888 return false889 }

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

line 890why, one step back
890 }

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

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

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

line 893why, one step back
893 return true

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

lines 894–895why, one step back
894}
895

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

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

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

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

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

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

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

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

Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87

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

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

lines 904–906why, one step back
904 return true
905 }906 }

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

lines 907–908why, one step back
907
908 // 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 909–911why, one step back
909 return false
910}911

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

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

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

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

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

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

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

lines 920–922why, one step back
920 return true
921 }922 }

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

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

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

line 926why, one step back
926 return false

Organize the files a bit betterspf13before adoption62fb674

lines 927–931why, one step back
927}
928929// Determine if the command is a child command930func (c *Command) HasParent() bool {931 return c.parent != nil

Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04

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

Organize the files a bit betterspf13before adoption62fb674

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

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 939why, one step back
939// 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 940–950why, one step back
940func (c *Command) Flags() *flag.FlagSet {
941 if c.flags == nil {942 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)943 if c.flagErrorBuf == nil {944 c.flagErrorBuf = new(bytes.Buffer)945 }946 c.flags.SetOutput(c.flagErrorBuf)947 }948 return c.flags949}950

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 951–955why, one step back
951// Get the local FlagSet specifically set in the current command
952func (c *Command) LocalFlags() *flag.FlagSet {953 c.mergePersistentFlags()954955 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 958why, one step back
958 })

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

lines 959–965why, one step back
959 if !c.HasParent() {
960 flag.CommandLine.VisitAll(func(f *flag.Flag) {961 if local.Lookup(f.Name) == nil {962 local.AddFlag(f)963 }964 })965 }

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 966–968why, one step back
966 return local
967}968

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

lines 969–972why, one step back
969// All Flags which were inherited from parents commands
970func (c *Command) InheritedFlags() *flag.FlagSet {971 c.mergePersistentFlags()972

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

line 975why, one step back
975

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

line 977why, one step back
977

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 978–989why, one step back
978 rmerge = func(x *Command) {
979 if x.HasPersistentFlags() {980 x.PersistentFlags().VisitAll(func(f *flag.Flag) {981 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {982 inherited.AddFlag(f)983 }984 })985 }986 if x.HasParent() {987 rmerge(x.parent)988 }989 }

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

lines 990–994why, one step back
990
991 if c.HasParent() {992 rmerge(c.parent)993 }994

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 995why, one step back
995 return inherited

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

lines 996–997why, one step back
996}
997

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

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

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

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

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

lines 1001–1002why, one step back
1001}
1002

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

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

Organize the files a bit betterspf13before adoption62fb674

lines 1004–1024why, one step back
1004func (c *Command) PersistentFlags() *flag.FlagSet {
1005 if c.pflags == nil {1006 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1007 if c.flagErrorBuf == nil {1008 c.flagErrorBuf = new(bytes.Buffer)1009 }1010 c.pflags.SetOutput(c.flagErrorBuf)1011 }1012 return c.pflags1013}10141015// For use in testing1016func (c *Command) ResetFlags() {1017 c.flagErrorBuf = new(bytes.Buffer)1018 c.flagErrorBuf.Reset()1019 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1020 c.flags.SetOutput(c.flagErrorBuf)1021 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1022 c.pflags.SetOutput(c.flagErrorBuf)1023}1024

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

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

Organize the files a bit betterspf13before adoption62fb674

lines 1026–1034why, one step back
1026func (c *Command) HasFlags() bool {
1027 return c.Flags().HasFlags()1028}10291030// Does the command contain persistent flags1031func (c *Command) HasPersistentFlags() bool {1032 return c.PersistentFlags().HasFlags()1033}1034

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1035–1039why, one step back
1035// Does the command has flags specifically declared locally
1036func (c *Command) HasLocalFlags() bool {1037 return c.LocalFlags().HasFlags()1038}1039

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 1040–1043why, one step back
1040func (c *Command) HasInheritedFlags() bool {
1041 return c.InheritedFlags().HasFlags()1042}1043

Organize the files a bit betterspf13before adoption62fb674

lines 1044–1070why, one step back
1044// Climbs up the command tree looking for matching flag
1045func (c *Command) Flag(name string) (flag *flag.Flag) {1046 flag = c.Flags().Lookup(name)10471048 if flag == nil {1049 flag = c.persistentFlag(name)1050 }10511052 return1053}10541055// recursively find matching persistent flag1056func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1057 if c.HasPersistentFlags() {1058 flag = c.PersistentFlags().Lookup(name)1059 }10601061 if flag == nil && c.HasParent() {1062 flag = c.parent.persistentFlag(name)1063 }1064 return1065}10661067// Parses persistent flag tree & local flags1068func (c *Command) ParseFlags(args []string) (err error) {1069 c.mergePersistentFlags()1070 err = c.Flags().Parse(args)

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

line 1071why, one step back
1071 return

Organize the files a bit betterspf13before adoption62fb674

lines 1072–1073why, one step back
1072}
1073

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 1074–1077why, one step back
1074func (c *Command) Parent() *Command {
1075 return c.parent1076}1077

Organize the files a bit betterspf13before adoption62fb674

lines 1078–1080why, one step back
1078func (c *Command) mergePersistentFlags() {
1079 var rmerge func(x *Command)1080

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 1081–1093why, one step back
1081 // Save the set of local flags
1082 if c.lflags == nil {1083 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1084 if c.flagErrorBuf == nil {1085 c.flagErrorBuf = new(bytes.Buffer)1086 }1087 c.lflags.SetOutput(c.flagErrorBuf)1088 addtolocal := func(f *flag.Flag) {1089 c.lflags.AddFlag(f)1090 }1091 c.Flags().VisitAll(addtolocal)1092 c.PersistentFlags().VisitAll(addtolocal)1093 }

Organize the files a bit betterspf13before adoption62fb674

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

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

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

Merge pull request #75 from eparis/CommandLineEric Parisbefore adoption2d5fab0

lines 1096–1101why, one step back
1096 flag.CommandLine.VisitAll(func(f *flag.Flag) {
1097 if x.PersistentFlags().Lookup(f.Name) == nil {1098 x.PersistentFlags().AddFlag(f)1099 }1100 })1101 }

Organize the files a bit betterspf13before adoption62fb674

lines 1102–1115why, one step back
1102 if x.HasPersistentFlags() {
1103 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1104 if c.Flags().Lookup(f.Name) == nil {1105 c.Flags().AddFlag(f)1106 }1107 })1108 }1109 if x.HasParent() {1110 rmerge(x.parent)1111 }1112 }11131114 rmerge(c)1115}