command.go
This file
Path
command.go
1,257 lines · 33.8 KiB · Go
Last changed by
Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
History of this fileTake it
The walk stopped after 200 commits: lines older than 10a8494 point at it.
Support for flags before commandsspf13before adoption10a8494
lines 1–13why, one step 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.Support for flags before commandsspf13before adoption10a8494
lines 16–22why, one step back16package cobra1718import (19 "bytes"20 "fmt"21 "io"22 "os"Limit the verbose test workaround to "cobra.test" onlyAnthony Fokbefore adoptione576205
line 23why, one step back23 "path/filepath"Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
line 24why, one step back24 "sort"Support for flags before commandsspf13before adoption10a8494
line 25why, one step back25 "strings"Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
lines 26–27why, one step back2627 flag "github.com/spf13/pflag"Support for flags before commandsspf13before adoption10a8494
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 []stringMerge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
lines 41–42why, one step back41 // An array of command names for which this command will be suggested - similar to aliases but only suggests.42 SuggestFor []stringSupport for flags before commandsspf13before adoption10a8494
lines 43–46why, one step back43 // The short description shown in the 'help' output.44 Short string45 // The long message shown in the 'help <this-command>' output.46 Long stringNew "example" section of commandsEric Parisbefore adoptionbf480fe
lines 47–48why, one step back47 // Examples of how to use the command48 Example stringMerge pull request #257 from sttts/sttts-noun-aliasesEric Parisbefore adoption60267ae
line 49why, one step back49 // List of all valid non-flag arguments that are accepted in bash completionsMerge pull request #69 from eparis/command-annotationsEric Parisbefore adoptionc746d30
line 50why, one step back50 ValidArgs []stringMerge pull request #257 from sttts/sttts-noun-aliasesEric Parisbefore adoption60267ae
lines 51–53why, one step back51 // List of aliases for ValidArgs. These are not suggested to the user in the bash52 // completion, but accepted if entered manually.53 ArgAliases []stringMerge pull request #69 from eparis/command-annotationsEric Parisbefore adoptionc746d30
lines 54–55why, one step back54 // Custom functions used by the bash autocompletion generator55 BashCompletionFunction stringMerge pull request #90 from eparis/deprecated-subcommandsEric Parisbefore adoption9cf0f37
lines 56–57why, one step back56 // Is this command deprecated and should print this string when used?57 Deprecated stringMerge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 58–59why, one step back58 // Is this command hidden and should NOT show up in the list of available commands?59 Hidden boolRestores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 60why, one step back60 // Full set of flagsSupport for flags before commandsspf13before adoption10a8494
line 61why, one step back61 flags *flag.FlagSetRestores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 62why, one step back62 // Set of flags childrens of this command will inheritSupport for flags before commandsspf13before adoption10a8494
line 63why, one step back63 pflags *flag.FlagSetExplicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 64–65why, one step back64 // Flags that are declared specifically by this command (not inherited).65 lflags *flag.FlagSetMerge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e
lines 66–69why, one step back66 // SilenceErrors is an option to quiet errors down stream67 SilenceErrors bool68 // Silence Usage is an option to silence usage when an error occurs.69 SilenceUsage boolMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 70–78why, one step back70 // The *Run functions are executed in the following order:71 // * PersistentPreRun()72 // * PreRun()73 // * Run()74 // * PostRun()75 // * PersistentPostRun()76 // All functions get the same args, the arguments after the command name77 // PersistentPreRun: children of this command will inherit and execute78 PersistentPreRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 79–80why, one step back79 // PersistentPreRunE: PersistentPreRun but returns an error80 PersistentPreRunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 81–82why, one step back81 // PreRun: children of this command will not inherit.82 PreRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 83–84why, one step back83 // PreRunE: PreRun but returns an error84 PreRunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 85why, one step back85 // Run: Typically the actual work function. Most commands will only implement thisSupport for flags before commandsspf13before adoption10a8494
line 86why, one step back86 Run func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 87–88why, one step back87 // RunE: Run but returns an error88 RunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 89–90why, one step back89 // PostRun: run after the Run command.90 PostRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 91–92why, one step back91 // PostRunE: PostRun but returns an error92 PostRunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 93–94why, one step back93 // PersistentPostRun: children of this command will inherit and execute after PostRun94 PersistentPostRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 95–96why, one step back95 // PersistentPostRunE: PersistentPostRun but returns an error96 PersistentPostRunE func(cmd *Command, args []string) erroradd a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a
lines 97–98why, one step back97 // DisableAutoGenTag remove98 DisableAutoGenTag boolSupport for flags before commandsspf13before adoption10a8494
lines 99–105why, one step back99 // Commands is the list of commands supported by this program.100 commands []*Command101 // Parent Command for this command102 parent *Command103 // max lengths of commands' string lengths for use in padding104 commandsMaxUseLen int105 commandsMaxCommandPathLen inthelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 106why, one step back106 commandsMaxNameLen intMerge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
lines 107–108why, one step back107 // is commands slice are sorted or not108 commandsAreSorted boolSupport for flags before commandsspf13before adoption10a8494
lines 109–111why, one step back109110 flagErrorBuf *bytes.Buffer111Code commentaryAhsanul Haquebefore adoptione1e66f7
line 112why, one step back112 args []string // actual args parsed from flagsMerge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
line 113why, one step back113 output *io.Writer // out writer if set in SetOutput(w)Support for flags before commandsspf13before adoption10a8494
lines 114–118why, one step back114 usageFunc func(*Command) error // Usage can be defined by application115 usageTemplate string // Can be defined by Application116 helpTemplate string // Can be defined by Application117 helpFunc func(*Command, []string) // Help can be defined by application118 helpCommand *Command // The help commandAdd Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 119–120why, one step back119 // The global normalization function that we can use on every pFlag set and children commands120 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedNameMerge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311
lines 121–125why, one step back121122 // Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages123 DisableSuggestions bool124 // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0125 SuggestionsMinimumDistance intMerge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048
lines 126–128why, one step back126127 // Disable the flag parsing. If this is true all flags will be passed to the command as arguments.128 DisableFlagParsing boolSupport for flags before commandsspf13before adoption10a8494
lines 129–142why, one step back129}130131// os.Args[1:] by default, if desired, can be overridden132// particularly useful when testing.133func (c *Command) SetArgs(a []string) {134 c.args = a135}136137// SetOutput sets the destination for usage and error messages.138// If output is nil, os.Stderr is used.139func (c *Command) SetOutput(output io.Writer) {140 c.output = &output141}142Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 143why, one step back143// Usage can be defined by application.Support for flags before commandsspf13before adoption10a8494
lines 144–147why, one step back144func (c *Command) SetUsageFunc(f func(*Command) error) {145 c.usageFunc = f146}147Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 148why, one step back148// Can be defined by Application.Support for flags before commandsspf13before adoption10a8494
lines 149–152why, one step back149func (c *Command) SetUsageTemplate(s string) {150 c.usageTemplate = s151}152Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 153why, one step back153// Can be defined by Application.Support for flags before commandsspf13before adoption10a8494
lines 154–161why, one step back154func (c *Command) SetHelpFunc(f func(*Command, []string)) {155 c.helpFunc = f156}157158func (c *Command) SetHelpCommand(cmd *Command) {159 c.helpCommand = cmd160}161Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 162why, one step back162// Can be defined by Application.Support for flags before commandsspf13before adoption10a8494
lines 163–166why, one step back163func (c *Command) SetHelpTemplate(s string) {164 c.helpTemplate = s165}166Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 167–178why, one step back167// 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}178Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
line 179why, one step back179func (c *Command) OutOrStdout() io.Writer {Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
lines 180–182why, one step back180 return c.getOut(os.Stdout)181}182Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
line 183why, one step back183func (c *Command) OutOrStderr() io.Writer {Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
lines 184–197why, one step back184 return c.getOut(os.Stderr)185}186187func (c *Command) getOut(def io.Writer) io.Writer {188 if c.output != nil {189 return *c.output190 }191 if c.HasParent() {192 return c.parent.getOut(def)193 }194 return def195}196197// UsageFunc returns either the function set by SetUsageFunc for this commandMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 198why, one step back198// or a parent, or it returns a default usage function.Support for flags before commandsspf13before adoption10a8494
lines 199–205why, one step back199func (c *Command) UsageFunc() (f func(*Command) error) {200 if c.usageFunc != nil {201 return c.usageFunc202 }203204 if c.HasParent() {205 return c.parent.UsageFunc()Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
lines 206–207why, one step back206 }207 return func(c *Command) error {Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
lines 208–209why, one step back208 c.mergePersistentFlags()209 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 210why, one step back210 if err != nil {Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
line 211why, one step back211 c.Println(err)Support for flags before commandsspf13before adoption10a8494
line 212why, one step back212 }Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 213why, one step back213 return errSupport for flags before commandsspf13before adoption10a8494
lines 214–215why, one step back214 }215}Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
line 216why, one step back216Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
lines 217–219why, one step back217// Usage puts out the usage for the command.218// Used when a user provides invalid input.219// Can be defined by user by overriding UsageFunc.Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d
lines 220–223why, one step back220func (c *Command) Usage() error {221 return c.UsageFunc()(c)222}223Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
line 224why, one step back224// HelpFunc returns either the function set by SetHelpFunc for this commandMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 225why, one step back225// or a parent, or it returns a function with default help behavior.Support for flags before commandsspf13before adoption10a8494
line 226why, one step back226func (c *Command) HelpFunc() func(*Command, []string) {Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 227–232why, one step back227 cmd := c228 for cmd != nil {229 if cmd.helpFunc != nil {230 return cmd.helpFunc231 }232 cmd = cmd.parentSupport for flags before commandsspf13before adoption10a8494
line 233why, one step back233 }Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
line 234why, one step back234 return func(*Command, []string) {Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
lines 235–236why, one step back235 c.mergePersistentFlags()236 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 237–238why, one step back237 if err != nil {238 c.Println(err)Support for flags before commandsspf13before adoption10a8494
lines 239–242why, one step back239 }240 }241}242Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
lines 243–245why, one step back243// Help puts out the help for the command.244// Used when a user calls help [command].245// Can be defined by user by overriding HelpFunc.Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d
lines 246–250why, one step back246func (c *Command) Help() error {247 c.HelpFunc()(c, []string{})248 return nil249}250Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
lines 251–254why, one step back251func (c *Command) UsageString() string {252 tmpOutput := c.output253 bb := new(bytes.Buffer)254 c.SetOutput(bb)Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d
line 255why, one step back255 c.Usage()Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
lines 256–259why, one step back256 c.output = tmpOutput257 return bb.String()258}259Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 260why, one step back260var minUsagePadding = 25Support for flags before commandsspf13before adoption10a8494
lines 261–265why, one step back261262func (c *Command) UsagePadding() int {263 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {264 return minUsagePadding265 }Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 266why, one step back266 return c.parent.commandsMaxUseLenSupport for flags before commandsspf13before adoption10a8494
lines 267–268why, one step back267}268Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 269why, one step back269var minCommandPathPadding = 11Support for flags before commandsspf13before adoption10a8494
line 270why, one step back270Code commentaryAhsanul Haquebefore adoptione1e66f7
line 271why, one step back271//Support for flags before commandsspf13before adoption10a8494
lines 272–275why, one step back272func (c *Command) CommandPathPadding() int {273 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {274 return minCommandPathPadding275 }Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 276why, one step back276 return c.parent.commandsMaxCommandPathLenSupport for flags before commandsspf13before adoption10a8494
lines 277–278why, one step back277}278Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 279why, one step back279var minNamePadding = 11help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 280–284why, one step back280281func (c *Command) NamePadding() int {282 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {283 return minNamePadding284 }Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 285why, one step back285 return c.parent.commandsMaxNameLenhelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 286–287why, one step back286}287Support for flags before commandsspf13before adoption10a8494
lines 288–294why, one step back288func (c *Command) UsageTemplate() string {289 if c.usageTemplate != "" {290 return c.usageTemplate291 }292293 if c.HasParent() {294 return c.parent.UsageTemplate()Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
lines 295–296why, one step back295 }296 return `Usage:{{if .Runnable}}Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
line 297why, one step back297 {{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 298–300why, one step back298 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}299300Aliases:New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 301–302why, one step back301 {{.NameAndAliases}}302{{end}}{{if .HasExample}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 303why, one step back303New "example" section of commandsEric Parisbefore adoptionbf480fe
line 304why, one step back304Examples:Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 305why, one step back305{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 306why, one step back306Merge pull request #148 from tamird/trailing-spacesEric Parisbefore adoption42498ec
line 307why, one step back307Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
line 308why, one step back308 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableLocalFlags}}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
lines 309–310why, one step back309310Flags:Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
line 311why, one step back311{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableInheritedFlags}}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
lines 312–313why, one step back312313Global Flags:Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7
line 314why, one step back314{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 315why, one step back315Merge pull request #148 from tamird/trailing-spacesEric Parisbefore adoption42498ec
line 316why, one step back316Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
line 317why, one step back317 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 318why, one step back318Merge pull request #154 from eparis/fix-trailing-newlineEric Parisbefore adoptionb28774d
lines 319–320why, one step back319Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}320`Support for flags before commandsspf13before adoption10a8494
lines 321–329why, one step back321}322323func (c *Command) HelpTemplate() string {324 if c.helpTemplate != "" {325 return c.helpTemplate326 }327328 if c.HasParent() {329 return c.parent.HelpTemplate()Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
lines 330–331why, one step back330 }331 return `{{with or .Long .Short }}{{. | trim}}Merge pull request #151 from eparis/no-newline-without-shortEric Parisbefore adoption85bb343
lines 332–333why, one step back332333{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`Support for flags before commandsspf13before adoption10a8494
lines 334–335why, one step back334}335Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 336why, one step back336// Really only used when casting a command to a commander.Support for flags before commandsspf13before adoption10a8494
lines 337–342why, one step back337func (c *Command) resetChildrensParents() {338 for _, x := range c.commands {339 x.parent = c340 }341}342Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 343–353why, one step back343// Test if the named flag is a boolean flag.344func isBooleanFlag(name string, f *flag.FlagSet) bool {345 flag := f.Lookup(name)346 if flag == nil {347 return false348 }349 return flag.Value.Type() == "bool"350}351352// Test if the named flag is a boolean flag.353func isBooleanShortFlag(name string, f *flag.FlagSet) bool {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 354–359why, one step back354 result := false355 f.VisitAll(func(f *flag.Flag) {356 if f.Shorthand == name && f.Value.Type() == "bool" {357 result = true358 }359 })Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 360–363why, one step back360 return result361}362363func stripFlags(args []string, c *Command) []string {Support for flags before commandsspf13before adoption10a8494
lines 364–366why, one step back364 if len(args) < 1 {365 return args366 }Merge pull request #70 from brendandburns/masterBjørn Erik Pedersenbefore adoption6264dc6
line 367why, one step back367 c.mergePersistentFlags()Support for flags before commandsspf13before adoption10a8494
lines 368–371why, one step back368369 commands := []string{}370371 inQuote := falseFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 372why, one step back372 inFlag := falseSupport for flags before commandsspf13before adoption10a8494
lines 373–379why, one step back373 for _, y := range args {374 if !inQuote {375 switch {376 case strings.HasPrefix(y, "\""):377 inQuote = true378 case strings.Contains(y, "=\""):379 inQuote = trueFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 380–386why, one step back380 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):381 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'382 inFlag = !isBooleanFlag(y[2:], c.Flags())383 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):384 inFlag = true385 case inFlag:386 inFlag = falseMerge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1
lines 387–388why, one step back387 case y == "":388 // strip empty commands, as the go tests expect this to be ok....Support for flags before commandsspf13before adoption10a8494
lines 389–390why, one step back389 case !strings.HasPrefix(y, "-"):390 commands = append(commands, y)Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 391why, one step back391 inFlag = falseSupport for flags before commandsspf13before adoption10a8494
lines 392–402why, one step back392 }393 }394395 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {396 inQuote = false397 }398 }399400 return commands401}402Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
lines 403–411why, one step back403// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like404// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).405func argsMinusFirstX(args []string, x string) []string {406 for i, y := range args {407 if x == y {408 ret := []string{}409 ret = append(ret, args[:i]...)410 ret = append(ret, args[i+1:]...)411 return retSupport for flags before commandsspf13before adoption10a8494
lines 412–413why, one step back412 }413 }Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
line 414why, one step back414 return argsSupport for flags before commandsspf13before adoption10a8494
lines 415–418why, one step back415}416417// find the target command given the args and command tree418// Meant to be run on the highest node. Only searches down.Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 419why, one step back419func (c *Command) Find(args []string) (*Command, []string, error) {Support for flags before commandsspf13before adoption10a8494
lines 420–425why, one step back420 if c == nil {421 return nil, nil, fmt.Errorf("Called find() on a nil Command")422 }423424 var innerfind func(*Command, []string) (*Command, []string)425Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 426why, one step back426 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 427–443why, one step back427 argsWOflags := stripFlags(innerArgs, c)428 if len(argsWOflags) == 0 {429 return c, innerArgs430 }431 nextSubCmd := argsWOflags[0]432 matches := make([]*Command, 0)433 for _, cmd := range c.commands {434 if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match435 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))436 }437 if EnablePrefixMatching {438 if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match439 matches = append(matches, cmd)440 }441 for _, x := range cmd.Aliases {442 if strings.HasPrefix(x, nextSubCmd) {443 matches = append(matches, cmd)Support for flags before commandsspf13before adoption10a8494
line 444why, one step back444 }adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
line 445why, one step back445 }Support for flags before commandsspf13before adoption10a8494
lines 446–448why, one step back446 }447 }448Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 449–453why, one step back449 // only accept a single prefix match - multiple matches would be ambiguous450 if len(matches) == 1 {451 return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))452 }453Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 454why, one step back454 return c, innerArgsSupport for flags before commandsspf13before adoption10a8494
lines 455–456why, one step back455 }456Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 457why, one step back457 commandFound, a := innerfind(c, args)Merge pull request #119 from eparis/bogus-bad-commandEric Parisbefore adoption66816bc
line 458why, one step back458 argsWOflags := stripFlags(a, commandFound)Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 459–463why, one step back459460 // no subcommand, always take args461 if !commandFound.HasSubCommands() {462 return commandFound, a, nil463 }Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311
line 464why, one step back464Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 465why, one step back465 // root command with subcommands, do subcommand checkingMerge pull request #119 from eparis/bogus-bad-commandEric Parisbefore adoption66816bc
line 466why, one step back466 if commandFound == c && len(argsWOflags) > 0 {Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
line 467why, one step back467 suggestionsString := ""Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311
lines 468–471why, one step back468 if !c.DisableSuggestions {469 if c.SuggestionsMinimumDistance <= 0 {470 c.SuggestionsMinimumDistance = 2471 }Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
lines 472–475why, one step back472 if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {473 suggestionsString += "\n\nDid you mean this?\n"474 for _, s := range suggestions {475 suggestionsString += fmt.Sprintf("\t%v\n", s)Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311
lines 476–478why, one step back476 }477 }478 }Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
line 479why, one step back479 return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)Support for flags before commandsspf13before adoption10a8494
lines 480–482why, one step back480 }481482 return commandFound, a, nilMerge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
lines 483–502why, one step back483}484485func (c *Command) SuggestionsFor(typedName string) []string {486 suggestions := []string{}487 for _, cmd := range c.commands {488 if cmd.IsAvailableCommand() {489 levenshteinDistance := ld(typedName, cmd.Name(), true)490 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance491 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))492 if suggestByLevenshtein || suggestByPrefix {493 suggestions = append(suggestions, cmd.Name())494 }495 for _, explicitSuggestion := range cmd.SuggestFor {496 if strings.EqualFold(typedName, explicitSuggestion) {497 suggestions = append(suggestions, cmd.Name())498 }499 }500 }501 }502 return suggestionsSupport for flags before commandsspf13before adoption10a8494
lines 503–504why, one step back503}504add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a
lines 505–519why, one step back505func (c *Command) VisitParents(fn func(*Command)) {506 var traverse func(*Command) *Command507508 traverse = func(x *Command) *Command {509 if x != c {510 fn(x)511 }512 if x.HasParent() {513 return traverse(x.parent)514 }515 return x516 }517 traverse(c)518}519Support for flags before commandsspf13before adoption10a8494
lines 520–526why, one step back520func (c *Command) Root() *Command {521 var findRoot func(*Command) *Command522523 findRoot = func(x *Command) *Command {524 if x.HasParent() {525 return findRoot(x.parent)526 }add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a
line 527why, one step back527 return xSupport for flags before commandsspf13before adoption10a8494
lines 528–532why, one step back528 }529530 return findRoot(c)531}532Merge pull request #167 from siddharthist/docs/ArgsLenAtDashEric Parisbefore adoption8b2293c
lines 533–536why, one step back533// ArgsLenAtDash will return the length of f.Args at the moment when a -- was534// found during arg parsing. This allows your program to know which args were535// before the -- and which came after. (Description from536// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).Merge pull request #160 from eparis/len-at-dashEric Parisbefore adoption53d9650
lines 537–540why, one step back537func (c *Command) ArgsLenAtDash() int {538 return c.Flags().ArgsLenAtDash()539}540Support for flags before commandsspf13before adoption10a8494
lines 541–543why, one step back541func (c *Command) execute(a []string) (err error) {542 if c == nil {543 return fmt.Errorf("Called Execute() on a nil Command")Merge pull request #90 from eparis/deprecated-subcommandsEric Parisbefore adoption9cf0f37
lines 544–547why, one step back544 }545546 if len(c.Deprecated) > 0 {547 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)Support for flags before commandsspf13before adoption10a8494
lines 548–549why, one step back548 }549Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
lines 550–553why, one step back550 // initialize help flag as the last point possible to allow for user551 // overriding552 c.initHelpFlag()553Support for flags before commandsspf13before adoption10a8494
lines 554–556why, one step back554 err = c.ParseFlags(a)555 if err != nil {556 return errMerge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 557why, one step back557 }Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 558why, one step back558 // If help is called, regardless of other flags, return we want helpMerge pull request #139 from alexanderguy/RunE-is-runnableBjørn Erik Pedersenbefore adoption1ba88c4
line 559why, one step back559 // Also say we need help if the command isn't runnable.Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
lines 560–566why, one step back560 helpVal, err := c.Flags().GetBool("help")561 if err != nil {562 // should be impossible to get here as we always declare a help563 // flag in initHelpFlag()564 c.Println("\"help\" flag declared as non-bool. Please correct your code")565 return err566 }Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
line 567why, one step back567Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 568why, one step back568 if helpVal || !c.Runnable() {Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 569why, one step back569 return flag.ErrHelpSupport for flags before commandsspf13before adoption10a8494
line 570why, one step back570 }Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
lines 571–572why, one step back571572 c.preRun()Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048
line 573why, one step back573Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 574why, one step back574 argWoFlags := c.Flags().Args()Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048
lines 575–577why, one step back575 if c.DisableFlagParsing {576 argWoFlags = a577 }Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 578why, one step back578Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
line 579why, one step back579 for p := c; p != nil; p = p.Parent() {Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
line 580why, one step back580 if p.PersistentPreRunE != nil {Merge pull request #164 from vikstrous/fix_bugEric Parisbefore adoptiond732ab3
line 581why, one step back581 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 582–585why, one step back582 return err583 }584 break585 } else if p.PersistentPreRun != nil {Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
lines 586–588why, one step back586 p.PersistentPreRun(c, argWoFlags)587 break588 }Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 589why, one step back589 }Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 590–594why, one step back590 if c.PreRunE != nil {591 if err := c.PreRunE(c, argWoFlags); err != nil {592 return err593 }594 } else if c.PreRun != nil {Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 595–597why, one step back595 c.PreRun(c, argWoFlags)596 }597Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 598–609why, one step back598 if c.RunE != nil {599 if err := c.RunE(c, argWoFlags); err != nil {600 return err601 }602 } else {603 c.Run(c, argWoFlags)604 }605 if c.PostRunE != nil {606 if err := c.PostRunE(c, argWoFlags); err != nil {607 return err608 }609 } else if c.PostRun != nil {Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 610–611why, one step back610 c.PostRun(c, argWoFlags)611 }Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
line 612why, one step back612 for p := c; p != nil; p = p.Parent() {Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 613–618why, one step back613 if p.PersistentPostRunE != nil {614 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {615 return err616 }617 break618 } else if p.PersistentPostRun != nil {Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
lines 619–621why, one step back619 p.PersistentPostRun(c, argWoFlags)620 break621 }Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 622–623why, one step back622 }623Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 624why, one step back624 return nilSupport for flags before commandsspf13before adoption10a8494
lines 625–626why, one step back625}626Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 627why, one step back627func (c *Command) preRun() {Adding "OnInitialize()" method instead of directly setting a property. Now can have multiple initializers.spf13before adoption864687a
lines 628–630why, one step back628 for _, x := range initializers {629 x()630 }Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 631–632why, one step back631}632Support for flags before commandsspf13before adoption10a8494
lines 633–640why, one step back633func (c *Command) errorMsgFromParse() string {634 s := c.flagErrorBuf.String()635636 x := strings.Split(s, "\n")637638 if len(x) > 0 {639 return x[0]640 }Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 641why, one step back641 return ""Support for flags before commandsspf13before adoption10a8494
lines 642–646why, one step back642}643644// Call execute to use the args (os.Args[1:] by default)645// and run through the command tree finding appropriate matches646// for commands and then corresponding flags.Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
lines 647–650why, one step back647func (c *Command) Execute() error {648 _, err := c.ExecuteC()649 return err650}Support for flags before commandsspf13before adoption10a8494
line 651why, one step back651Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
lines 652–653why, one step back652func (c *Command) ExecuteC() (cmd *Command, err error) {653Support for flags before commandsspf13before adoption10a8494
lines 654–655why, one step back654 // Regardless of what command execute is called on, run on Root only655 if c.HasParent() {Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
line 656why, one step back656 return c.Root().ExecuteC()Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29
lines 657–658why, one step back657 }658Merge pull request #197 from magiconair/issue-195-mousetrap-win-onlyEric Parisbefore adoption7366561
lines 659–661why, one step back659 // windows hook660 if preExecHookFn != nil {661 preExecHookFn(c)Support for flags before commandsspf13before adoption10a8494
lines 662–665why, one step back662 }663664 // initialize help as the last point possible to allow for user665 // overridingMerge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 666why, one step back666 c.initHelpCmd()Support for flags before commandsspf13before adoption10a8494
lines 667–669why, one step back667668 var args []string669Limit the verbose test workaround to "cobra.test" onlyAnthony Fokbefore adoptione576205
line 670why, one step back670 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155Use nil instead of len for arg check.Jonathan Reynabefore adoption1ef0913
line 671why, one step back671 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {Support for flags before commandsspf13before adoption10a8494
lines 672–676why, one step back672 args = os.Args[1:]673 } else {674 args = c.args675 }676Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 677why, one step back677 cmd, flags, err := c.Find(args)Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 678–682why, one step back678 if err != nil {679 // If found parse to a subcommand and then failed, talk about the subcommand680 if cmd != nil {681 c = cmd682 }Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e
lines 683–686why, one step back683 if !c.SilenceErrors {684 c.Println("Error:", err.Error())685 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())686 }Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
line 687why, one step back687 return c, errSupport for flags before commandsspf13before adoption10a8494
line 688why, one step back688 }Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 689why, one step back689 err = cmd.execute(flags)Support for flags before commandsspf13before adoption10a8494
line 690why, one step back690 if err != nil {always show help if requested, even if SilenceErrors is enabledSascha Holzleiterbefore adoption2bd8a73
lines 691–697why, one step back691 // Always show help if requested, even if SilenceErrors is in692 // effect693 if err == flag.ErrHelp {694 cmd.HelpFunc()(cmd, args)695 return cmd, nil696 }697Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e
lines 698–701why, one step back698 // If root command has SilentErrors flagged,699 // all subcommands should respect it700 if !cmd.SilenceErrors && !c.SilenceErrors {701 c.Println("Error:", err.Error())Merge pull request #174 from jbowes/fix-duplicate-usageEric Parisbefore adoptiona082ce4
lines 702–707why, one step back702 }703704 // If root command has SilentUsage flagged,705 // all subcommands should respect it706 if !cmd.SilenceUsage && !c.SilenceUsage {707 c.Println(cmd.UsageString())Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e
line 708why, one step back708 }Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
line 709why, one step back709 return cmd, errSupport for flags before commandsspf13before adoption10a8494
line 710why, one step back710 }Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
line 711why, one step back711 return cmd, nilSupport for flags before commandsspf13before adoption10a8494
lines 712–713why, one step back712}713Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 714why, one step back714func (c *Command) initHelpFlag() {Merge pull request #133 from eparis/late-init-help-flagEric Parisbefore adoption4c4f2d9
line 715why, one step back715 if c.Flags().Lookup("help") == nil {Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 716why, one step back716 c.Flags().BoolP("help", "h", false, "help for "+c.Name())Merge pull request #133 from eparis/late-init-help-flagEric Parisbefore adoption4c4f2d9
line 717why, one step back717 }Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
lines 718–720why, one step back718}719720func (c *Command) initHelpCmd() {Support for flags before commandsspf13before adoption10a8494
line 721why, one step back721 if c.helpCommand == nil {Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
lines 722–725why, one step back722 if !c.HasSubCommands() {723 return724 }725Support for flags before commandsspf13before adoption10a8494
lines 726–730why, one step back726 c.helpCommand = &Command{727 Use: "help [command]",728 Short: "Help about any command",729 Long: `Help provides help for any command in the application.730 Simply type ` + c.Name() + ` help [path to command] for full details.`,Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 731–732why, one step back731 PersistentPreRun: func(cmd *Command, args []string) {},732 PersistentPostRun: func(cmd *Command, args []string) {},Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 733–737why, one step back733734 Run: func(c *Command, args []string) {735 cmd, _, e := c.Root().Find(args)736 if cmd == nil || e != nil {737 c.Printf("Unknown help topic %#q.", args)Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d
line 738why, one step back738 c.Root().Usage()Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
line 739why, one step back739 } else {Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d
line 740why, one step back740 cmd.Help()Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 741–742why, one step back741 }742 },Support for flags before commandsspf13before adoption10a8494
lines 743–747why, one step back743 }744 }745 c.AddCommand(c.helpCommand)746}747Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 748why, one step back748// Used for testing.Support for flags before commandsspf13before adoption10a8494
lines 749–750why, one step back749func (c *Command) ResetCommands() {750 c.commands = nilMerge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 751why, one step back751 c.helpCommand = nilSupport for flags before commandsspf13before adoption10a8494
lines 752–753why, one step back752}753Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 754why, one step back754// Sorts commands by their names.Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
lines 755–761why, one step back755type commandSorterByName []*Command756757func (c commandSorterByName) Len() int { return len(c) }758func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }759func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }760761// Commands returns a sorted slice of child commands.Support for flags before commandsspf13before adoption10a8494
line 762why, one step back762func (c *Command) Commands() []*Command {Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
line 763why, one step back763 // do not sort commands if it already sorted or sorting was disabledMerge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
line 764why, one step back764 if EnableCommandSorting && !c.commandsAreSorted {Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
lines 765–767why, one step back765 sort.Sort(commandSorterByName(c.commands))766 c.commandsAreSorted = true767 }Support for flags before commandsspf13before adoption10a8494
lines 768–770why, one step back768 return c.commands769}770Code commentaryAhsanul Haquebefore adoptione1e66f7
line 771why, one step back771// AddCommand adds one or more commands to this parent command.Support for flags before commandsspf13before adoption10a8494
lines 772–785why, one step back772func (c *Command) AddCommand(cmds ...*Command) {773 for i, x := range cmds {774 if cmds[i] == c {775 panic("Command can't be a child of itself")776 }777 cmds[i].parent = c778 // update max lengths779 usageLen := len(x.Use)780 if usageLen > c.commandsMaxUseLen {781 c.commandsMaxUseLen = usageLen782 }783 commandPathLen := len(x.CommandPath())784 if commandPathLen > c.commandsMaxCommandPathLen {785 c.commandsMaxCommandPathLen = commandPathLenhelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 786–789why, one step back786 }787 nameLen := len(x.Name())788 if nameLen > c.commandsMaxNameLen {789 c.commandsMaxNameLen = nameLenSupport for flags before commandsspf13before adoption10a8494
line 790why, one step back790 }Merge pull request #211 from NanXiao/patch-1Eric Parisbefore adoptionea3bf16
line 791why, one step back791 // If global normalization function exists, update all childrenAdd Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 792–794why, one step back792 if c.globNormFunc != nil {793 x.SetGlobalNormalizationFunc(c.globNormFunc)794 }Support for flags before commandsspf13before adoption10a8494
line 795why, one step back795 c.commands = append(c.commands, x)Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
line 796why, one step back796 c.commandsAreSorted = falseSupport for flags before commandsspf13before adoption10a8494
lines 797–799why, one step back797 }798}799Merge pull request #278 from kevintpeng/patch-1Eric Parisbefore adoptionf368244
line 800why, one step back800// RemoveCommand removes one or more commands from a parent command.Add Command's RemoveCommand methodÉtienne Vallette d'Osiabefore adoptionf479c92
lines 801–833why, one step back801func (c *Command) RemoveCommand(cmds ...*Command) {802 commands := []*Command{}803main:804 for _, command := range c.commands {805 for _, cmd := range cmds {806 if command == cmd {807 command.parent = nil808 continue main809 }810 }811 commands = append(commands, command)812 }813 c.commands = commands814 // recompute all lengths815 c.commandsMaxUseLen = 0816 c.commandsMaxCommandPathLen = 0817 c.commandsMaxNameLen = 0818 for _, command := range c.commands {819 usageLen := len(command.Use)820 if usageLen > c.commandsMaxUseLen {821 c.commandsMaxUseLen = usageLen822 }823 commandPathLen := len(command.CommandPath())824 if commandPathLen > c.commandsMaxCommandPathLen {825 c.commandsMaxCommandPathLen = commandPathLen826 }827 nameLen := len(command.Name())828 if nameLen > c.commandsMaxNameLen {829 c.commandsMaxNameLen = nameLen830 }831 }832}833Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 834why, one step back834// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.Support for flags before commandsspf13before adoption10a8494
line 835why, one step back835func (c *Command) Print(i ...interface{}) {Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
line 836why, one step back836 fmt.Fprint(c.OutOrStderr(), i...)Support for flags before commandsspf13before adoption10a8494
lines 837–838why, one step back837}838Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 839why, one step back839// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.Support for flags before commandsspf13before adoption10a8494
lines 840–844why, one step back840func (c *Command) Println(i ...interface{}) {841 str := fmt.Sprintln(i...)842 c.Print(str)843}844Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 845why, one step back845// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.Support for flags before commandsspf13before adoption10a8494
lines 846–850why, one step back846func (c *Command) Printf(format string, i ...interface{}) {847 str := fmt.Sprintf(format, i...)848 c.Print(str)849}850Code commentaryAhsanul Haquebefore adoptione1e66f7
line 851why, one step back851// CommandPath returns the full path to this command.Support for flags before commandsspf13before adoption10a8494
lines 852–861why, one step back852func (c *Command) CommandPath() string {853 str := c.Name()854 x := c855 for x.HasParent() {856 str = x.parent.Name() + " " + str857 x = x.parent858 }859 return str860}861Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 862why, one step back862// UseLine puts out the full usage for a given command (including parents).Support for flags before commandsspf13before adoption10a8494
lines 863–871why, one step back863func (c *Command) UseLine() string {864 str := ""865 if c.HasParent() {866 str = c.parent.CommandPath() + " "867 }868 return str + c.Use869}870871// For use in determining which flags have been assigned to which commandsMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 872why, one step back872// and which persist.Support for flags before commandsspf13before adoption10a8494
lines 873–926why, one step back873func (c *Command) DebugFlags() {874 c.Println("DebugFlags called on", c.Name())875 var debugflags func(*Command)876877 debugflags = func(x *Command) {878 if x.HasFlags() || x.HasPersistentFlags() {879 c.Println(x.Name())880 }881 if x.HasFlags() {882 x.flags.VisitAll(func(f *flag.Flag) {883 if x.HasPersistentFlags() {884 if x.persistentFlag(f.Name) == nil {885 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")886 } else {887 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")888 }889 } else {890 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")891 }892 })893 }894 if x.HasPersistentFlags() {895 x.pflags.VisitAll(func(f *flag.Flag) {896 if x.HasFlags() {897 if x.flags.Lookup(f.Name) == nil {898 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")899 }900 } else {901 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")902 }903 })904 }905 c.Println(x.flagErrorBuf)906 if x.HasSubCommands() {907 for _, y := range x.commands {908 debugflags(y)909 }910 }911 }912913 debugflags(c)914}915916// Name returns the command's name: the first word in the use line.917func (c *Command) Name() string {918 if c.name != "" {919 return c.name920 }921 name := c.Use922 i := strings.Index(name, " ")923 if i >= 0 {924 name = name[:i]925 }926 return nameReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 927–928why, one step back927}928Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 929why, one step back929// HasAlias determines if a given string is an alias of the command.Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 930–940why, one step back930func (c *Command) HasAlias(s string) bool {931 for _, a := range c.Aliases {932 if a == s {933 return true934 }935 }936 return false937}938939func (c *Command) NameAndAliases() string {940 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 941–944why, one step back941}942943func (c *Command) HasExample() bool {944 return len(c.Example) > 0Support for flags before commandsspf13before adoption10a8494
lines 945–946why, one step back945}946Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 947why, one step back947// Runnable determines if the command is itself runnable.Support for flags before commandsspf13before adoption10a8494
line 948why, one step back948func (c *Command) Runnable() bool {Merge pull request #139 from alexanderguy/RunE-is-runnableBjørn Erik Pedersenbefore adoption1ba88c4
line 949why, one step back949 return c.Run != nil || c.RunE != nilSupport for flags before commandsspf13before adoption10a8494
lines 950–951why, one step back950}951Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 952why, one step back952// HasSubCommands determines if the command has children commands.Support for flags before commandsspf13before adoption10a8494
lines 953–954why, one step back953func (c *Command) HasSubCommands() bool {954 return len(c.commands) > 0Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 955–956why, one step back955}956Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 957why, one step back957// IsAvailableCommand determines if a command is available as a non-help commandMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 958why, one step back958// (this includes all non deprecated/hidden commands).Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 959why, one step back959func (c *Command) IsAvailableCommand() bool {Merge pull request #146 from eparis/is-available-reworkEric Parisbefore adoption4b86c66
lines 960–962why, one step back960 if len(c.Deprecated) != 0 || c.Hidden {961 return false962 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 963why, one step back963Merge pull request #150 from eparis/help-not-availableEric Parisbefore adoption0d9b07b
lines 964–967why, one step back964 if c.HasParent() && c.Parent().helpCommand == c {965 return false966 }967Merge pull request #146 from eparis/is-available-reworkEric Parisbefore adoption4b86c66
lines 968–972why, one step back968 if c.Runnable() || c.HasAvailableSubCommands() {969 return true970 }971972 return falseMerge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 973–976why, one step back973}974975// IsHelpCommand determines if a command is a 'help' command; a help command is976// determined by the fact that it is NOT runnable/hidden/deprecated, and has noMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 977why, one step back977// sub commands that are runnable/hidden/deprecated.Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 978why, one step back978func (c *Command) IsHelpCommand() bool {Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 979–981why, one step back979980 // if a command is runnable, deprecated, or hidden it is not a 'help' command981 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 982–983why, one step back982 return false983 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 984–985why, one step back984985 // if any non-help sub commands are found, the command is not a 'help' commandMerge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
lines 986–989why, one step back986 for _, sub := range c.commands {987 if !sub.IsHelpCommand() {988 return false989 }Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 990why, one step back990 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 991–992why, one step back991992 // the command either has no sub commands, or no non-help sub commandsMerge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 993why, one step back993 return trueMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 994–995why, one step back994}995Merge pull request #327 from bogem/fixesEric Parisbefore adoption1f47171
line 996why, one step back996// HasHelpSubCommands determines if a command has any available 'help' sub commandsMerge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 997why, one step back997// that need to be shown in the usage/help default template under 'additional helpMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 998why, one step back998// topics'.Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 999why, one step back999func (c *Command) HasHelpSubCommands() bool {Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 1000–1001why, one step back10001001 // return true on the first found available 'help' sub commandMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 1002why, one step back1002 for _, sub := range c.commands {Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 1003why, one step back1003 if sub.IsHelpCommand() {Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 1004–1006why, one step back1004 return true1005 }1006 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 1007–1008why, one step back10071008 // the command either has no sub commands, or no available 'help' sub commandsMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 1009–1011why, one step back1009 return false1010}1011Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 1012why, one step back1012// HasAvailableSubCommands determines if a command has available sub commands thatMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1013why, one step back1013// need to be shown in the usage/help default template under 'available commands'.Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 1014–1017why, one step back1014func (c *Command) HasAvailableSubCommands() bool {10151016 // return true on the first found available (non deprecated/help/hidden)1017 // sub commandMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 1018why, one step back1018 for _, sub := range c.commands {Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 1019why, one step back1019 if sub.IsAvailableCommand() {Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 1020–1022why, one step back1020 return true1021 }1022 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 1023–1025why, one step back10231024 // the command either has no sub comamnds, or no available (non deprecated/help/hidden)1025 // sub commandsMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 1026why, one step back1026 return falseSupport for flags before commandsspf13before adoption10a8494
lines 1027–1028why, one step back1027}1028Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1029why, one step back1029// HasParent determines if the command is a child command.Support for flags before commandsspf13before adoption10a8494
lines 1030–1031why, one step back1030func (c *Command) HasParent() bool {1031 return c.parent != nilAdd Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 1032–1033why, one step back1032}1033Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1034why, one step back1034// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists.Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 1035–1036why, one step back1035func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1036 return c.globNormFuncSupport for flags before commandsspf13before adoption10a8494
lines 1037–1038why, one step back1037}1038Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
lines 1039–1040why, one step back1039// Flage returns the complete FlagSet that applies1040// to this command (local and persistent declared here and by all parents).Support for flags before commandsspf13before adoption10a8494
lines 1041–1051why, one step back1041func (c *Command) Flags() *flag.FlagSet {1042 if c.flags == nil {1043 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1044 if c.flagErrorBuf == nil {1045 c.flagErrorBuf = new(bytes.Buffer)1046 }1047 c.flags.SetOutput(c.flagErrorBuf)1048 }1049 return c.flags1050}1051Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1052why, one step back1052// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.Merge pull request #288 from eparis/flags-vs-commandsEric Parisbefore adoptionc21ee9d
lines 1053–1064why, one step back1053func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1054 persistentFlags := c.PersistentFlags()10551056 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1057 c.LocalFlags().VisitAll(func(f *flag.Flag) {1058 if persistentFlags.Lookup(f.Name) == nil {1059 out.AddFlag(f)1060 }1061 })1062 return out1063}1064Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1065why, one step back1065// LocalFlags returns the local FlagSet specifically set in the current command.Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1066–1069why, one step back1066func (c *Command) LocalFlags() *flag.FlagSet {1067 c.mergePersistentFlags()10681069 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1070–1071why, one step back1070 c.lflags.VisitAll(func(f *flag.Flag) {1071 local.AddFlag(f)Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 1072why, one step back1072 })Merge pull request #127 from eparis/show-commandline-on-parentEric Parisbefore adoptiondb05184
lines 1073–1079why, one step back1073 if !c.HasParent() {1074 flag.CommandLine.VisitAll(func(f *flag.Flag) {1075 if local.Lookup(f.Name) == nil {1076 local.AddFlag(f)1077 }1078 })1079 }Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1080–1082why, one step back1080 return local1081}1082Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1083why, one step back1083// InheritedFlags returns all flags which were inherited from parents commands.new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 1084–1086why, one step back1084func (c *Command) InheritedFlags() *flag.FlagSet {1085 c.mergePersistentFlags()1086Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1087–1088why, one step back1087 inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1088 local := c.LocalFlags()new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 1089why, one step back1089Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 1090why, one step back1090 var rmerge func(x *Command)new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 1091why, one step back1091Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1092–1103why, one step back1092 rmerge = func(x *Command) {1093 if x.HasPersistentFlags() {1094 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1095 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1096 inherited.AddFlag(f)1097 }1098 })1099 }1100 if x.HasParent() {1101 rmerge(x.parent)1102 }1103 }new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 1104–1108why, one step back11041105 if c.HasParent() {1106 rmerge(c.parent)1107 }1108Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 1109why, one step back1109 return inheritednew InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 1110–1111why, one step back1110}1111Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1112why, one step back1112// NonInheritedFlags returns all flags which were not inherited from parent commands.new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
line 1113why, one step back1113func (c *Command) NonInheritedFlags() *flag.FlagSet {Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 1114why, one step back1114 return c.LocalFlags()new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 1115–1116why, one step back1115}1116Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1117why, one step back1117// PersistentFlags returns the persistent FlagSet specifically set in the current command.Support for flags before commandsspf13before adoption10a8494
lines 1118–1128why, one step back1118func (c *Command) PersistentFlags() *flag.FlagSet {1119 if c.pflags == nil {1120 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1121 if c.flagErrorBuf == nil {1122 c.flagErrorBuf = new(bytes.Buffer)1123 }1124 c.pflags.SetOutput(c.flagErrorBuf)1125 }1126 return c.pflags1127}1128Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1129why, one step back1129// ResetFlags is used in testing.Support for flags before commandsspf13before adoption10a8494
lines 1130–1138why, one step back1130func (c *Command) ResetFlags() {1131 c.flagErrorBuf = new(bytes.Buffer)1132 c.flagErrorBuf.Reset()1133 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1134 c.flags.SetOutput(c.flagErrorBuf)1135 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1136 c.pflags.SetOutput(c.flagErrorBuf)1137}1138Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1139why, one step back1139// Does the command contain any flags (local plus persistent from the entire structure).Support for flags before commandsspf13before adoption10a8494
lines 1140–1143why, one step back1140func (c *Command) HasFlags() bool {1141 return c.Flags().HasFlags()1142}1143Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1144why, one step back1144// Does the command contain persistent flags.Support for flags before commandsspf13before adoption10a8494
lines 1145–1148why, one step back1145func (c *Command) HasPersistentFlags() bool {1146 return c.PersistentFlags().HasFlags()1147}1148Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1149why, one step back1149// Does the command has flags specifically declared locally.Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1150–1153why, one step back1150func (c *Command) HasLocalFlags() bool {1151 return c.LocalFlags().HasFlags()1152}1153Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1154why, one step back1154// Does the command have flags inherited from its parent command.Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1155–1156why, one step back1155func (c *Command) HasInheritedFlags() bool {1156 return c.InheritedFlags().HasFlags()Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1157–1159why, one step back1157}11581159// Does the command contain any flags (local plus persistent from the entireMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1160why, one step back1160// structure) which are not hidden or deprecated.Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1161–1164why, one step back1161func (c *Command) HasAvailableFlags() bool {1162 return c.Flags().HasAvailableFlags()1163}1164Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1165why, one step back1165// Does the command contain persistent flags which are not hidden or deprecated.Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1166–1170why, one step back1166func (c *Command) HasAvailablePersistentFlags() bool {1167 return c.PersistentFlags().HasAvailableFlags()1168}11691170// Does the command has flags specifically declared locally which are not hiddenMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1171why, one step back1171// or deprecated.Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1172–1176why, one step back1172func (c *Command) HasAvailableLocalFlags() bool {1173 return c.LocalFlags().HasAvailableFlags()1174}11751176// Does the command have flags inherited from its parent command which areMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1177why, one step back1177// not hidden or deprecated.Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1178–1179why, one step back1178func (c *Command) HasAvailableInheritedFlags() bool {1179 return c.InheritedFlags().HasAvailableFlags()Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1180–1181why, one step back1180}1181Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1182why, one step back1182// Flag climbs up the command tree looking for matching flag.Support for flags before commandsspf13before adoption10a8494
lines 1183–1192why, one step back1183func (c *Command) Flag(name string) (flag *flag.Flag) {1184 flag = c.Flags().Lookup(name)11851186 if flag == nil {1187 flag = c.persistentFlag(name)1188 }11891190 return1191}1192Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1193why, one step back1193// Recursively find matching persistent flag.Support for flags before commandsspf13before adoption10a8494
lines 1194–1204why, one step back1194func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1195 if c.HasPersistentFlags() {1196 flag = c.PersistentFlags().Lookup(name)1197 }11981199 if flag == nil && c.HasParent() {1200 flag = c.parent.persistentFlag(name)1201 }1202 return1203}1204Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1205why, one step back1205// ParseFlags parses persistent flag tree and local flags.Support for flags before commandsspf13before adoption10a8494
line 1206why, one step back1206func (c *Command) ParseFlags(args []string) (err error) {Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048
lines 1207–1209why, one step back1207 if c.DisableFlagParsing {1208 return nil1209 }Support for flags before commandsspf13before adoption10a8494
lines 1210–1211why, one step back1210 c.mergePersistentFlags()1211 err = c.Flags().Parse(args)Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e
line 1212why, one step back1212 returnSupport for flags before commandsspf13before adoption10a8494
lines 1213–1214why, one step back1213}1214Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1215why, one step back1215// Parent returns a commands parent command.Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1216–1219why, one step back1216func (c *Command) Parent() *Command {1217 return c.parent1218}1219Support for flags before commandsspf13before adoption10a8494
lines 1220–1222why, one step back1220func (c *Command) mergePersistentFlags() {1221 var rmerge func(x *Command)1222Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1223–1235why, one step back1223 // Save the set of local flags1224 if c.lflags == nil {1225 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1226 if c.flagErrorBuf == nil {1227 c.flagErrorBuf = new(bytes.Buffer)1228 }1229 c.lflags.SetOutput(c.flagErrorBuf)1230 addtolocal := func(f *flag.Flag) {1231 c.lflags.AddFlag(f)1232 }1233 c.Flags().VisitAll(addtolocal)1234 c.PersistentFlags().VisitAll(addtolocal)1235 }Support for flags before commandsspf13before adoption10a8494
line 1236why, one step back1236 rmerge = func(x *Command) {Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 1237why, one step back1237 if !x.HasParent() {Merge pull request #75 from eparis/CommandLineEric Parisbefore adoption2d5fab0
lines 1238–1243why, one step back1238 flag.CommandLine.VisitAll(func(f *flag.Flag) {1239 if x.PersistentFlags().Lookup(f.Name) == nil {1240 x.PersistentFlags().AddFlag(f)1241 }1242 })1243 }Support for flags before commandsspf13before adoption10a8494
lines 1244–1257why, one step back1244 if x.HasPersistentFlags() {1245 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1246 if c.Flags().Lookup(f.Name) == nil {1247 c.Flags().AddFlag(f)1248 }1249 })1250 }1251 if x.HasParent() {1252 rmerge(x.parent)1253 }1254 }12551256 rmerge(c)1257}