command.go
This file
Path
command.go
970 lines · 23.6 KiB · Go
Last changed by
Deprecated subcommandsEric Parisbefore adoptionc3e48f9
History of this fileTake it
Organize the files a bit betterspf13before adoption62fb674
lines 1–13why, one step back1// 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.13Code commentaryAhsanul Haquebefore adoptione1e66f7
lines 14–15why, one step back14//Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.15//In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.Organize the files a bit betterspf13before adoption62fb674
lines 16–20why, one step back16package cobra1718import (19 "bytes"20 "fmt"Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29
lines 21–22why, one step back21 "github.com/inconshreveable/mousetrap"22 flag "github.com/spf13/pflag"Organize the files a bit betterspf13before adoption62fb674
line 23why, one step back23 "io"Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 24why, one step back24 "os"Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29
line 25why, one step back25 "runtime"Organize the files a bit betterspf13before adoption62fb674
line 26why, one step back26 "strings"Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29
line 27why, one step back27 "time"Organize the files a bit betterspf13before adoption62fb674
lines 28–38why, one step back28)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 stringReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 39–40why, one step back39 // An array of aliases that can be used instead of the first word in Use.40 Aliases []stringOrganize the files a bit betterspf13before adoption62fb674
lines 41–44why, one step back41 // The short description shown in the 'help' output.42 Short string43 // The long message shown in the 'help <this-command>' output.44 Long stringNew "example" section of commandsEric Parisbefore adoptionbf480fe
lines 45–46why, one step back45 // Examples of how to use the command46 Example stringMerge pull request #69 from eparis/command-annotationsEric Parisbefore adoptionc746d30
lines 47–50why, one step back47 // List of all valid non-flag arguments, used for bash completions *TODO* actually validate these48 ValidArgs []string49 // Custom functions used by the bash autocompletion generator50 BashCompletionFunction stringDeprecated subcommandsEric Parisbefore adoptionc3e48f9
lines 51–52why, one step back51 // Is this command deprecated and should print this string when used?52 Deprecated stringRestores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 53why, one step back53 // Full set of flagsOrganize the files a bit betterspf13before adoption62fb674
line 54why, one step back54 flags *flag.FlagSetRestores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 55why, one step back55 // Set of flags childrens of this command will inheritOrganize the files a bit betterspf13before adoption62fb674
line 56why, one step back56 pflags *flag.FlagSetExplicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 57–58why, one step back57 // Flags that are declared specifically by this command (not inherited).58 lflags *flag.FlagSetOrganize the files a bit betterspf13before adoption62fb674
lines 59–61why, one step back59 // Run runs the command.60 // The args are the arguments after the command name.61 Run func(cmd *Command, args []string)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 62why, one step back62 // Commands is the list of commands supported by this program.Organize the files a bit betterspf13before adoption62fb674
lines 63–64why, one step back63 commands []*Command64 // Parent Command for this commandRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 65why, one step back65 parent *CommandMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 66–68why, one step back66 // max lengths of commands' string lengths for use in padding67 commandsMaxUseLen int68 commandsMaxCommandPathLen inthelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 69why, one step back69 commandsMaxNameLen intRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 70why, one step back70Organize the files a bit betterspf13before adoption62fb674
line 71why, one step back71 flagErrorBuf *bytes.BufferSubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 72why, one step back72 cmdErrorBuf *bytes.BufferRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 73why, one step back73Code commentaryAhsanul Haquebefore adoptione1e66f7
line 74why, one step back74 args []string // actual args parsed from flagsDocumentation updatespf13before adoption59bd285
line 75why, one step back75 output *io.Writer // nil means stderr; use Out() method insteadRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 76–80why, one step back76 usageFunc func(*Command) error // Usage can be defined by application77 usageTemplate string // Can be defined by Application78 helpTemplate string // Can be defined by Application79 helpFunc func(*Command, []string) // Help can be defined by application80 helpCommand *Command // The help commandAdding support for --helpspf13before adoption07be814
line 81why, one step back81 helpFlagVal boolOrganize the files a bit betterspf13before adoption62fb674
lines 82–83why, one step back82}83Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 84–87why, one step back84// os.Args[1:] by default, if desired, can be overridden85// particularly useful when testing.86func (c *Command) SetArgs(a []string) {87 c.args = aAdd ability to cast a command to a commanderspf13before adoption74ce44d
lines 88–89why, one step back88}89Default usage output to stdoutEric Parisbefore adoption6de96b8
line 90why, one step back90func (c *Command) getOut(def io.Writer) io.Writer {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 91–97why, one step back91 if c.output != nil {92 return *c.output93 }9495 if c.HasParent() {96 return c.parent.Out()97 } else {Default usage output to stdoutEric Parisbefore adoption6de96b8
line 98why, one step back98 return defRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 99–101why, one step back99 }100}101Default usage output to stdoutEric Parisbefore adoption6de96b8
lines 102–109why, one step back102func (c *Command) Out() io.Writer {103 return c.getOut(os.Stderr)104}105106func (c *Command) getOutOrStdout() io.Writer {107 return c.getOut(os.Stdout)108}109Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 110–164why, one step back110// SetOutput sets the destination for usage and error messages.111// If output is nil, os.Stderr is used.112func (c *Command) SetOutput(output io.Writer) {113 c.output = &output114}115116// Usage can be defined by application117func (c *Command) SetUsageFunc(f func(*Command) error) {118 c.usageFunc = f119}120121// Can be defined by Application122func (c *Command) SetUsageTemplate(s string) {123 c.usageTemplate = s124}125126// Can be defined by Application127func (c *Command) SetHelpFunc(f func(*Command, []string)) {128 c.helpFunc = f129}130131func (c *Command) SetHelpCommand(cmd *Command) {132 c.helpCommand = cmd133}134135// Can be defined by Application136func (c *Command) SetHelpTemplate(s string) {137 c.helpTemplate = s138}139140func (c *Command) UsageFunc() (f func(*Command) error) {141 if c.usageFunc != nil {142 return c.usageFunc143 }144145 if c.HasParent() {146 return c.parent.UsageFunc()147 } else {148 return func(c *Command) error {149 err := tmpl(c.Out(), c.UsageTemplate(), c)150 return err151 }152 }153}154func (c *Command) HelpFunc() func(*Command, []string) {155 if c.helpFunc != nil {156 return c.helpFunc157 }158159 if c.HasParent() {160 return c.parent.HelpFunc()161 } else {162 return func(c *Command, args []string) {163 if len(args) == 0 {164 // Help called without any topic, calling on rootPrint Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 165why, one step back165 c.Root().Help()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 166–183why, one step back166 return167 }168169 cmd, _, e := c.Root().Find(args)170 if cmd == nil || e != nil {171 c.Printf("Unknown help topic %#q.", args)172173 c.Root().Usage()174 } else {175 err := cmd.Help()176 if err != nil {177 c.Println(err)178 }179 }180 }181 }182}183Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 184–195why, one step back184var minUsagePadding int = 25185186func (c *Command) UsagePadding() int {187 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {188 return minUsagePadding189 } else {190 return c.parent.commandsMaxUseLen191 }192}193194var minCommandPathPadding int = 11195Code commentaryAhsanul Haquebefore adoptione1e66f7
line 196why, one step back196//Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 197–204why, one step back197func (c *Command) CommandPathPadding() int {198 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {199 return minCommandPathPadding200 } else {201 return c.parent.commandsMaxCommandPathLen202 }203}204help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 205–214why, one step back205var minNamePadding int = 11206207func (c *Command) NamePadding() int {208 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {209 return minNamePadding210 } else {211 return c.parent.commandsMaxNameLen212 }213}214Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 215–225why, one step back215func (c *Command) UsageTemplate() string {216 if c.usageTemplate != "" {217 return c.usageTemplate218 }219220 if c.HasParent() {221 return c.parent.UsageTemplate()222 } else {223 return `{{ $cmd := . }}224Usage: {{if .Runnable}}225 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 226–228why, one step back226 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}227228Aliases:New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 229–230why, one step back229 {{.NameAndAliases}}230{{end}}{{if .HasExample}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 231why, one step back231New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 232–233why, one step back232Examples:233{{ .Example }}Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 234why, one step back234{{end}}{{ if .HasRunnableSubCommands}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 235why, one step back235Deprecated subcommandsEric Parisbefore adoptionc3e48f9
line 236why, one step back236Available Commands: {{range .Commands}}{{if and (.Runnable) (not .Deprecated)}}help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 237why, one step back237 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 238why, one step back238{{end}}Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 239–240why, one step back239{{ if .HasLocalFlags}}Flags:240{{.LocalFlags.FlagUsages}}{{end}}Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 241why, one step back241{{ if .HasInheritedFlags}}Global Flags:Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 242why, one step back242{{.InheritedFlags.FlagUsages}}{{end}}{{if or (.HasHelpSubCommands) (.HasRunnableSiblings)}}Merge pull request #88 from eparis/subhelptestEric Parisbefore adoptionb78326b
line 243why, one step back243Additional help topics:Deprecated subcommandsEric Parisbefore adoptionc3e48f9
line 244why, one step back244{{if .HasHelpSubCommands}}{{range .Commands}}{{if and (not .Runnable) (not .Deprecated)}} {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasRunnableSiblings }}{{range .Parent.Commands}}{{if and (not .Runnable) (not .Deprecated)}}{{if not (eq .Name $cmd.Name) }}Remove "::" from output. Fixed #4spf13before adoption1a6c5d1
line 245why, one step back245 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{end}}Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 246why, one step back246{{end}}{{ if .HasSubCommands }}Minor English correctionKartik Singhalbefore adoptionc36f627
line 247why, one step back247Use "{{.Root.Name}} help [command]" for more information about a command.Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 248why, one step back248{{end}}`Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 249–259why, one step back249 }250}251252func (c *Command) HelpTemplate() string {253 if c.helpTemplate != "" {254 return c.helpTemplate255 }256257 if c.HasParent() {258 return c.parent.HelpTemplate()259 } else {Help uses Short message if Long is not availableEdgard Castrobefore adoption384c059
line 260why, one step back260 return `{{with or .Long .Short }}{{. | trim}}{{end}}Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 261why, one step back261{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 262–265why, one step back262`263 }264}265Add ability to cast a command to a commanderspf13before adoption74ce44d
lines 266–272why, one step back266// Really only used when casting a command to a commander267func (c *Command) resetChildrensParents() {268 for _, x := range c.commands {269 x.parent = c270 }271}272Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 273–283why, one step back273// Test if the named flag is a boolean flag.274func isBooleanFlag(name string, f *flag.FlagSet) bool {275 flag := f.Lookup(name)276 if flag == nil {277 return false278 }279 return flag.Value.Type() == "bool"280}281282// Test if the named flag is a boolean flag.283func isBooleanShortFlag(name string, f *flag.FlagSet) bool {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 284–289why, one step back284 result := false285 f.VisitAll(func(f *flag.Flag) {286 if f.Shorthand == name && f.Value.Type() == "bool" {287 result = true288 }289 })Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 290–293why, one step back290 return result291}292293func stripFlags(args []string, c *Command) []string {Support for flags before commandsspf13before adoption10a8494
lines 294–296why, one step back294 if len(args) < 1 {295 return args296 }Merge pull request #70 from brendandburns/masterBjørn Erik Pedersenbefore adoption6264dc6
line 297why, one step back297 c.mergePersistentFlags()Support for flags before commandsspf13before adoption10a8494
lines 298–301why, one step back298299 commands := []string{}300301 inQuote := falseFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 302why, one step back302 inFlag := falseSupport for flags before commandsspf13before adoption10a8494
lines 303–309why, one step back303 for _, y := range args {304 if !inQuote {305 switch {306 case strings.HasPrefix(y, "\""):307 inQuote = true308 case strings.Contains(y, "=\""):309 inQuote = trueFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 310–316why, one step back310 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):311 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'312 inFlag = !isBooleanFlag(y[2:], c.Flags())313 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):314 inFlag = true315 case inFlag:316 inFlag = falseMerge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1
lines 317–318why, one step back317 case y == "":318 // strip empty commands, as the go tests expect this to be ok....Support for flags before commandsspf13before adoption10a8494
lines 319–320why, one step back319 case !strings.HasPrefix(y, "-"):320 commands = append(commands, y)Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 321why, one step back321 inFlag = falseSupport for flags before commandsspf13before adoption10a8494
lines 322–332why, one step back322 }323 }324325 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {326 inQuote = false327 }328 }329330 return commands331}332Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
lines 333–341why, one step back333// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like334// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).335func argsMinusFirstX(args []string, x string) []string {336 for i, y := range args {337 if x == y {338 ret := []string{}339 ret = append(ret, args[:i]...)340 ret = append(ret, args[i+1:]...)341 return retSupport for flags before commandsspf13before adoption10a8494
lines 342–343why, one step back342 }343 }Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
line 344why, one step back344 return argsSupport for flags before commandsspf13before adoption10a8494
lines 345–346why, one step back345}346Organize the files a bit betterspf13before adoption62fb674
line 347why, one step back347// find the target command given the args and command treeAdd support for help commandspf13before adoptionfb2146e
line 348why, one step back348// Meant to be run on the highest node. Only searches down.Finding command based on args cleaned upspf13before adoption55ff474
line 349why, one step back349func (c *Command) Find(arrs []string) (*Command, []string, error) {Organize the files a bit betterspf13before adoption62fb674
lines 350–353why, one step back350 if c == nil {351 return nil, nil, fmt.Errorf("Called find() on a nil Command")352 }353Finding command based on args cleaned upspf13before adoption55ff474
line 354why, one step back354 if len(arrs) == 0 {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 355why, one step back355 return c.Root(), arrs, nilFinding command based on args cleaned upspf13before adoption55ff474
lines 356–361why, one step back356 }357358 var innerfind func(*Command, []string) (*Command, []string)359360 innerfind = func(c *Command, args []string) (*Command, []string) {361 if len(args) > 0 && c.HasSubCommands() {Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 362why, one step back362 argsWOflags := stripFlags(args, c)Support for flags before commandsspf13before adoption10a8494
line 363why, one step back363 if len(argsWOflags) > 0 {adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
line 364why, one step back364 matches := make([]*Command, 0)Support for flags before commandsspf13before adoption10a8494
line 365why, one step back365 for _, cmd := range c.commands {Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
line 366why, one step back366 if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias matchMerge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
line 367why, one step back367 return innerfind(cmd, argsMinusFirstX(args, argsWOflags[0]))Making prefix matching opt in.spf13before adoptionb1e90a7
line 368why, one step back368 } else if EnablePrefixMatching {adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
lines 369–376why, one step back369 if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match370 matches = append(matches, cmd)371 }372 for _, x := range cmd.Aliases {373 if strings.HasPrefix(x, argsWOflags[0]) {374 matches = append(matches, cmd)375 }376 }Support for flags before commandsspf13before adoption10a8494
line 377why, one step back377 }adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
lines 378–381why, one step back378 }379380 // only accept a single prefix match - multiple matches would be ambiguous381 if len(matches) == 1 {Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
line 382why, one step back382 return innerfind(matches[0], argsMinusFirstX(args, argsWOflags[0]))Finding command based on args cleaned upspf13before adoption55ff474
line 383why, one step back383 }Organize the files a bit betterspf13before adoption62fb674
lines 384–385why, one step back384 }385 }Finding command based on args cleaned upspf13before adoption55ff474
lines 386–387why, one step back386387 return c, argsOrganize the files a bit betterspf13before adoption62fb674
line 388why, one step back388 }Finding command based on args cleaned upspf13before adoption55ff474
lines 389–391why, one step back389390 commandFound, a := innerfind(c, arrs)391Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1
lines 392–393why, one step back392 // If we matched on the root, but we asked for a subcommand, return an error393 if commandFound.Name() == c.Name() && len(stripFlags(arrs, c)) > 0 && commandFound.Name() != arrs[0] {Merge pull request #83 from adammck/fix_double_output_on_unknown_commandEric Parisbefore adoption09b49c3
line 394why, one step back394 return nil, a, fmt.Errorf("unknown command %q", a[0])Organize the files a bit betterspf13before adoption62fb674
lines 395–396why, one step back395 }396Finding command based on args cleaned upspf13before adoption55ff474
line 397why, one step back397 return commandFound, a, nilOrganize the files a bit betterspf13before adoption62fb674
lines 398–399why, one step back398}399Add support for help commandspf13before adoptionfb2146e
line 400why, one step back400func (c *Command) Root() *Command {Organize the files a bit betterspf13before adoption62fb674
lines 401–409why, one step back401 var findRoot func(*Command) *Command402403 findRoot = func(x *Command) *Command {404 if x.HasParent() {405 return findRoot(x.parent)406 } else {407 return x408 }409 }Add support for help commandspf13before adoptionfb2146e
lines 410–413why, one step back410411 return findRoot(c)412}413fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 414why, one step back414func (c *Command) execute(a []string) (err error) {Organize the files a bit betterspf13before adoption62fb674
lines 415–416why, one step back415 if c == nil {416 return fmt.Errorf("Called Execute() on a nil Command")Deprecated subcommandsEric Parisbefore adoptionc3e48f9
lines 417–420why, one step back417 }418419 if len(c.Deprecated) > 0 {420 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)Organize the files a bit betterspf13before adoption62fb674
lines 421–422why, one step back421 }422fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 423why, one step back423 err = c.ParseFlags(a)Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 424–427why, one step back424 if err == flag.ErrHelp {425 c.Help()426 return nil427 }fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 428why, one step back428 if err != nil {Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 429why, one step back429 // We're writing subcommand usage to root command's error buffer to have it displayed to the userSubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
lines 430–432why, one step back430 r := c.Root()431 if r.cmdErrorBuf == nil {432 r.cmdErrorBuf = new(bytes.Buffer)Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
lines 433–434why, one step back433 }434 // for writing the usage to the buffer we need to switch the output temporarilySubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
lines 435–437why, one step back435 // since Out() returns root output, you also need to revert that on root436 out := r.Out()437 r.SetOutput(r.cmdErrorBuf)Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 438why, one step back438 c.Usage()Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
line 439why, one step back439 r.SetOutput(out)fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 440–441why, one step back440 return err441 } else {In execute(), check if command is Runnable()Anthony Fokbefore adoption4745f1f
lines 442–444why, one step back442 // If help is called, regardless of other flags, we print that.443 // Print help also if c.Run is nil.444 if c.helpFlagVal || !c.Runnable() {Adding support for --helpspf13before adoption07be814
lines 445–448why, one step back445 c.Help()446 return nil447 }448Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 449why, one step back449 c.preRun()fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 450–452why, one step back450 argWoFlags := c.Flags().Args()451 c.Run(c, argWoFlags)452 return nilOrganize the files a bit betterspf13before adoption62fb674
lines 453–455why, one step back453 }454}455Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 456why, one step back456func (c *Command) preRun() {Adding "OnInitialize()" method instead of directly setting a property. Now can have multiple initializers.spf13before adoption864687a
lines 457–459why, one step back457 for _, x := range initializers {458 x()459 }Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 460–461why, one step back460}461Support for flags before commandsspf13before adoption10a8494
lines 462–473why, one step back462func (c *Command) errorMsgFromParse() string {463 s := c.flagErrorBuf.String()464465 x := strings.Split(s, "\n")466467 if len(x) > 0 {468 return x[0]469 } else {470 return ""471 }472}473Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 474–481why, one step back474// Call execute to use the args (os.Args[1:] by default)475// and run through the command tree finding appropriate matches476// for commands and then corresponding flags.477func (c *Command) Execute() (err error) {478479 // Regardless of what command execute is called on, run on Root only480 if c.HasParent() {481 return c.Root().Execute()Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29
lines 482–489why, one step back482 }483484 if EnableWindowsMouseTrap && runtime.GOOS == "windows" {485 if mousetrap.StartedByExplorer() {486 c.Print(MousetrapHelpText)487 time.Sleep(5 * time.Second)488 os.Exit(1)489 }Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 490–508why, one step back490 }491492 // initialize help as the last point possible to allow for user493 // overriding494 c.initHelp()495496 var args []string497498 if len(c.args) == 0 {499 args = os.Args[1:]500 } else {501 args = c.args502 }503504 if len(args) == 0 {505 // Only the executable is called and the root is runnable, run it506 if c.Runnable() {507 err = c.execute([]string(nil))508 } else {Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 509why, one step back509 c.Help()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 510–511why, one step back510 }511 } else {Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1
line 512why, one step back512 cmd, flags, e := c.Find(args)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 513why, one step back513 if e != nil {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e
line 514why, one step back514 err = eRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 515why, one step back515 } else {Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1
line 516why, one step back516 err = cmd.execute(flags)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 517–520why, one step back517 }518 }519520 if err != nil {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 521–522why, one step back521 if err == flag.ErrHelp {522 c.Help()Merge pull request #83 from adammck/fix_double_output_on_unknown_commandEric Parisbefore adoption09b49c3
line 523why, one step back523Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 524–525why, one step back524 } else {525 c.Println("Error:", err.Error())Merge pull request #83 from adammck/fix_double_output_on_unknown_commandEric Parisbefore adoption09b49c3
line 526why, one step back526 c.Printf("Run '%v help' for usage.\n", c.Root().Name())Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
line 527why, one step back527 }Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 528–534why, one step back528 }529530 return531}532533func (c *Command) initHelp() {534 if c.helpCommand == nil {Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
lines 535–538why, one step back535 if !c.HasSubCommands() {536 return537 }538Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 539–549why, one step back539 c.helpCommand = &Command{540 Use: "help [command]",541 Short: "Help about any command",542 Long: `Help provides help for any command in the application.543 Simply type ` + c.Name() + ` help [path to command] for full details.`,544 Run: c.HelpFunc(),545 }546 }547 c.AddCommand(c.helpCommand)548}549Organize the files a bit betterspf13before adoption62fb674
lines 550–552why, one step back550// Used for testing551func (c *Command) ResetCommands() {552 c.commands = nilMerge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 553why, one step back553 c.helpCommand = nilSubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
lines 554–555why, one step back554 c.cmdErrorBuf = new(bytes.Buffer)555 c.cmdErrorBuf.Reset()Organize the files a bit betterspf13before adoption62fb674
lines 556–557why, one step back556}557Code commentaryAhsanul Haquebefore adoptione1e66f7
line 558why, one step back558//Commands returns a slice of child commands.Organize the files a bit betterspf13before adoption62fb674
lines 559–562why, one step back559func (c *Command) Commands() []*Command {560 return c.commands561}562Code commentaryAhsanul Haquebefore adoptione1e66f7
line 563why, one step back563// AddCommand adds one or more commands to this parent command.Organize the files a bit betterspf13before adoption62fb674
lines 564–569why, one step back564func (c *Command) AddCommand(cmds ...*Command) {565 for i, x := range cmds {566 if cmds[i] == c {567 panic("Command can't be a child of itself")568 }569 cmds[i].parent = cMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 570–577why, one step back570 // update max lengths571 usageLen := len(x.Use)572 if usageLen > c.commandsMaxUseLen {573 c.commandsMaxUseLen = usageLen574 }575 commandPathLen := len(x.CommandPath())576 if commandPathLen > c.commandsMaxCommandPathLen {577 c.commandsMaxCommandPathLen = commandPathLenhelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 578–581why, one step back578 }579 nameLen := len(x.Name())580 if nameLen > c.commandsMaxNameLen {581 c.commandsMaxNameLen = nameLenMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
line 582why, one step back582 }Organize the files a bit betterspf13before adoption62fb674
lines 583–586why, one step back583 c.commands = append(c.commands, x)584 }585}586Add Command's RemoveCommand methodÉtienne Vallette d'Osiabefore adoptionf479c92
lines 587–620why, one step back587// AddCommand removes one or more commands from a parent command.588func (c *Command) RemoveCommand(cmds ...*Command) {589 commands := []*Command{}590main:591 for _, command := range c.commands {592 for _, cmd := range cmds {593 if command == cmd {594 command.parent = nil595 continue main596 }597 }598 commands = append(commands, command)599 }600 c.commands = commands601 // recompute all lengths602 c.commandsMaxUseLen = 0603 c.commandsMaxCommandPathLen = 0604 c.commandsMaxNameLen = 0605 for _, command := range c.commands {606 usageLen := len(command.Use)607 if usageLen > c.commandsMaxUseLen {608 c.commandsMaxUseLen = usageLen609 }610 commandPathLen := len(command.CommandPath())611 if commandPathLen > c.commandsMaxCommandPathLen {612 c.commandsMaxCommandPathLen = commandPathLen613 }614 nameLen := len(command.Name())615 if nameLen > c.commandsMaxNameLen {616 c.commandsMaxNameLen = nameLen617 }618 }619}620Organize the files a bit betterspf13before adoption62fb674
lines 621–622why, one step back621// Convenience method to Print to the defined output622func (c *Command) Print(i ...interface{}) {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 623why, one step back623 fmt.Fprint(c.Out(), i...)Organize the files a bit betterspf13before adoption62fb674
lines 624–639why, one step back624}625626// Convenience method to Println to the defined output627func (c *Command) Println(i ...interface{}) {628 str := fmt.Sprintln(i...)629 c.Print(str)630}631632// Convenience method to Printf to the defined output633func (c *Command) Printf(format string, i ...interface{}) {634 str := fmt.Sprintf(format, i...)635 c.Print(str)636}637638// Output the usage for the command639// Used when a user provides invalid inputRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 640why, one step back640// Can be defined by user by overriding UsageFuncOrganize the files a bit betterspf13before adoption62fb674
line 641why, one step back641func (c *Command) Usage() error {Help improvementsspf13before adoption2d02c31
line 642why, one step back642 c.mergePersistentFlags()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 643why, one step back643 err := c.UsageFunc()(c)Help improvementsspf13before adoption2d02c31
lines 644–651why, one step back644 return err645}646647// Output the help for the command648// Used when a user calls help [command]649// by the default HelpFunc in the commander650func (c *Command) Help() error {651 c.mergePersistentFlags()Default usage output to stdoutEric Parisbefore adoption6de96b8
line 652why, one step back652 err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)Organize the files a bit betterspf13before adoption62fb674
lines 653–655why, one step back653 return err654}655fix trailing <nil> on help outputspf13before adoption3958385
line 656why, one step back656func (c *Command) UsageString() string {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 657why, one step back657 tmpOutput := c.outputfix trailing <nil> on help outputspf13before adoption3958385
line 658why, one step back658 bb := new(bytes.Buffer)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 659why, one step back659 c.SetOutput(bb)fix trailing <nil> on help outputspf13before adoption3958385
line 660why, one step back660 c.Usage()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 661why, one step back661 c.output = tmpOutputfix trailing <nil> on help outputspf13before adoption3958385
lines 662–664why, one step back662 return bb.String()663}664Code commentaryAhsanul Haquebefore adoptione1e66f7
line 665why, one step back665// CommandPath returns the full path to this command.Organize the files a bit betterspf13before adoption62fb674
lines 666–740why, one step back666func (c *Command) CommandPath() string {667 str := c.Name()668 x := c669 for x.HasParent() {670 str = x.parent.Name() + " " + str671 x = x.parent672 }673 return str674}675676//The full usage for a given command (including parents)677func (c *Command) UseLine() string {678 str := ""679 if c.HasParent() {680 str = c.parent.CommandPath() + " "681 }682 return str + c.Use683}684685// For use in determining which flags have been assigned to which commands686// and which persist687func (c *Command) DebugFlags() {688 c.Println("DebugFlags called on", c.Name())689 var debugflags func(*Command)690691 debugflags = func(x *Command) {692 if x.HasFlags() || x.HasPersistentFlags() {693 c.Println(x.Name())694 }695 if x.HasFlags() {696 x.flags.VisitAll(func(f *flag.Flag) {697 if x.HasPersistentFlags() {698 if x.persistentFlag(f.Name) == nil {699 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")700 } else {701 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")702 }703 } else {704 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")705 }706 })707 }708 if x.HasPersistentFlags() {709 x.pflags.VisitAll(func(f *flag.Flag) {710 if x.HasFlags() {711 if x.flags.Lookup(f.Name) == nil {712 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")713 }714 } else {715 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")716 }717 })718 }719 c.Println(x.flagErrorBuf)720 if x.HasSubCommands() {721 for _, y := range x.commands {722 debugflags(y)723 }724 }725 }726727 debugflags(c)728}729730// Name returns the command's name: the first word in the use line.731func (c *Command) Name() string {732 if c.name != "" {733 return c.name734 }735 name := c.Use736 i := strings.Index(name, " ")737 if i >= 0 {738 name = name[:i]739 }740 return nameReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 741–754why, one step back741}742743// Determine if a given string is an alias of the command.744func (c *Command) HasAlias(s string) bool {745 for _, a := range c.Aliases {746 if a == s {747 return true748 }749 }750 return false751}752753func (c *Command) NameAndAliases() string {754 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 755–758why, one step back755}756757func (c *Command) HasExample() bool {758 return len(c.Example) > 0Organize the files a bit betterspf13before adoption62fb674
lines 759–768why, one step back759}760761// Determine if the command is itself runnable762func (c *Command) Runnable() bool {763 return c.Run != nil764}765766// Determine if the command has children commands767func (c *Command) HasSubCommands() bool {768 return len(c.commands) > 0Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 769–799why, one step back769}770771func (c *Command) HasRunnableSiblings() bool {772 if !c.HasParent() {773 return false774 }775 for _, sub := range c.parent.commands {776 if sub.Runnable() {777 return true778 }779 }780 return false781}782783func (c *Command) HasHelpSubCommands() bool {784 for _, sub := range c.commands {785 if !sub.Runnable() {786 return true787 }788 }789 return false790}791792// Determine if the command has runnable children commands793func (c *Command) HasRunnableSubCommands() bool {794 for _, sub := range c.commands {795 if sub.Runnable() {796 return true797 }798 }799 return falseOrganize the files a bit betterspf13before adoption62fb674
lines 800–806why, one step back800}801802// Determine if the command is a child command803func (c *Command) HasParent() bool {804 return c.parent != nil805}806Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 807why, one step back807// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)Organize the files a bit betterspf13before adoption62fb674
lines 808–814why, one step back808func (c *Command) Flags() *flag.FlagSet {809 if c.flags == nil {810 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)811 if c.flagErrorBuf == nil {812 c.flagErrorBuf = new(bytes.Buffer)813 }814 c.flags.SetOutput(c.flagErrorBuf)changed help flag setup to use PersistenFlags so -h will be supportedJoel Scoblebefore adoption83b58a2
line 815why, one step back815 c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name())Organize the files a bit betterspf13before adoption62fb674
lines 816–819why, one step back816 }817 return c.flags818}819Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 820–824why, one step back820// Get the local FlagSet specifically set in the current command821func (c *Command) LocalFlags() *flag.FlagSet {822 c.mergePersistentFlags()823824 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 825–826why, one step back825 c.lflags.VisitAll(func(f *flag.Flag) {826 local.AddFlag(f)Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 827–830why, one step back827 })828 return local829}830new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 831–834why, one step back831// All Flags which were inherited from parents commands832func (c *Command) InheritedFlags() *flag.FlagSet {833 c.mergePersistentFlags()834Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 835–836why, one step back835 inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)836 local := c.LocalFlags()new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 837why, one step back837Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 838why, one step back838 var rmerge func(x *Command)new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 839why, one step back839Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 840–851why, one step back840 rmerge = func(x *Command) {841 if x.HasPersistentFlags() {842 x.PersistentFlags().VisitAll(func(f *flag.Flag) {843 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {844 inherited.AddFlag(f)845 }846 })847 }848 if x.HasParent() {849 rmerge(x.parent)850 }851 }new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 852–856why, one step back852853 if c.HasParent() {854 rmerge(c.parent)855 }856Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 857why, one step back857 return inheritednew InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 858–859why, one step back858}859new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 860–861why, one step back860// All Flags which were not inherited from parent commands861func (c *Command) NonInheritedFlags() *flag.FlagSet {Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 862why, one step back862 return c.LocalFlags()new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 863–864why, one step back863}864Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 865why, one step back865// Get the Persistent FlagSet specifically set in the current commandOrganize the files a bit betterspf13before adoption62fb674
lines 866–886why, one step back866func (c *Command) PersistentFlags() *flag.FlagSet {867 if c.pflags == nil {868 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)869 if c.flagErrorBuf == nil {870 c.flagErrorBuf = new(bytes.Buffer)871 }872 c.pflags.SetOutput(c.flagErrorBuf)873 }874 return c.pflags875}876877// For use in testing878func (c *Command) ResetFlags() {879 c.flagErrorBuf = new(bytes.Buffer)880 c.flagErrorBuf.Reset()881 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)882 c.flags.SetOutput(c.flagErrorBuf)883 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)884 c.pflags.SetOutput(c.flagErrorBuf)885}886Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 887why, one step back887// Does the command contain any flags (local plus persistent from the entire structure)Organize the files a bit betterspf13before adoption62fb674
lines 888–896why, one step back888func (c *Command) HasFlags() bool {889 return c.Flags().HasFlags()890}891892// Does the command contain persistent flags893func (c *Command) HasPersistentFlags() bool {894 return c.PersistentFlags().HasFlags()895}896Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 897–901why, one step back897// Does the command has flags specifically declared locally898func (c *Command) HasLocalFlags() bool {899 return c.LocalFlags().HasFlags()900}901Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 902–905why, one step back902func (c *Command) HasInheritedFlags() bool {903 return c.InheritedFlags().HasFlags()904}905Organize the files a bit betterspf13before adoption62fb674
lines 906–932why, one step back906// Climbs up the command tree looking for matching flag907func (c *Command) Flag(name string) (flag *flag.Flag) {908 flag = c.Flags().Lookup(name)909910 if flag == nil {911 flag = c.persistentFlag(name)912 }913914 return915}916917// recursively find matching persistent flag918func (c *Command) persistentFlag(name string) (flag *flag.Flag) {919 if c.HasPersistentFlags() {920 flag = c.PersistentFlags().Lookup(name)921 }922923 if flag == nil && c.HasParent() {924 flag = c.parent.persistentFlag(name)925 }926 return927}928929// Parses persistent flag tree & local flags930func (c *Command) ParseFlags(args []string) (err error) {931 c.mergePersistentFlags()932 err = c.Flags().Parse(args)Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e
line 933why, one step back933 returnOrganize the files a bit betterspf13before adoption62fb674
lines 934–935why, one step back934}935Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 936–939why, one step back936func (c *Command) Parent() *Command {937 return c.parent938}939Organize the files a bit betterspf13before adoption62fb674
lines 940–942why, one step back940func (c *Command) mergePersistentFlags() {941 var rmerge func(x *Command)942Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 943–955why, one step back943 // Save the set of local flags944 if c.lflags == nil {945 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)946 if c.flagErrorBuf == nil {947 c.flagErrorBuf = new(bytes.Buffer)948 }949 c.lflags.SetOutput(c.flagErrorBuf)950 addtolocal := func(f *flag.Flag) {951 c.lflags.AddFlag(f)952 }953 c.Flags().VisitAll(addtolocal)954 c.PersistentFlags().VisitAll(addtolocal)955 }Organize the files a bit betterspf13before adoption62fb674
lines 956–970why, one step back956 rmerge = func(x *Command) {957 if x.HasPersistentFlags() {958 x.PersistentFlags().VisitAll(func(f *flag.Flag) {959 if c.Flags().Lookup(f.Name) == nil {960 c.Flags().AddFlag(f)961 }962 })963 }964 if x.HasParent() {965 rmerge(x.parent)966 }967 }968969 rmerge(c)970}