command.go
This file
Path
command.go
1,115 lines · 28.4 KiB · Go
Last changed by
Merge pull request #153 from eparis/remove-useless-assignmentEric Parisbefore adoptioneeec8e3
History of this 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–21why, one step back16package cobra1718import (19 "bytes"20 "fmt"21 "io"Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 22why, one step back22 "os"Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29
line 23why, one step back23 "runtime"Organize the files a bit betterspf13before adoption62fb674
line 24why, one step back24 "strings"Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29
line 25why, one step back25 "time"Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
lines 26–28why, one step back2627 "github.com/inconshreveable/mousetrap"28 flag "github.com/spf13/pflag"Organize the files a bit betterspf13before adoption62fb674
lines 29–39why, one step back29)3031// Command is just that, a command for your application.32// eg. 'go run' ... 'run' is the command. Cobra requires33// you to define the usage and description as part of your command34// definition to ensure usability.35type Command struct {36 // Name is the command name, usually the executable's name.37 name string38 // The one-line usage message.39 Use stringReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 40–41why, one step back40 // An array of aliases that can be used instead of the first word in Use.41 Aliases []stringOrganize the files a bit betterspf13before adoption62fb674
lines 42–45why, one step back42 // The short description shown in the 'help' output.43 Short string44 // The long message shown in the 'help <this-command>' output.45 Long stringNew "example" section of commandsEric Parisbefore adoptionbf480fe
lines 46–47why, one step back46 // Examples of how to use the command47 Example stringMerge pull request #69 from eparis/command-annotationsEric Parisbefore adoptionc746d30
lines 48–51why, one step back48 // List of all valid non-flag arguments, used for bash completions *TODO* actually validate these49 ValidArgs []string50 // Custom functions used by the bash autocompletion generator51 BashCompletionFunction stringMerge pull request #90 from eparis/deprecated-subcommandsEric Parisbefore adoption9cf0f37
lines 52–53why, one step back52 // Is this command deprecated and should print this string when used?53 Deprecated stringMerge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 54–55why, one step back54 // Is this command hidden and should NOT show up in the list of available commands?55 Hidden boolRestores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 56why, one step back56 // Full set of flagsOrganize the files a bit betterspf13before adoption62fb674
line 57why, one step back57 flags *flag.FlagSetRestores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 58why, one step back58 // Set of flags childrens of this command will inheritOrganize the files a bit betterspf13before adoption62fb674
line 59why, one step back59 pflags *flag.FlagSetExplicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 60–61why, one step back60 // Flags that are declared specifically by this command (not inherited).61 lflags *flag.FlagSetMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 62–70why, one step back62 // The *Run functions are executed in the following order:63 // * PersistentPreRun()64 // * PreRun()65 // * Run()66 // * PostRun()67 // * PersistentPostRun()68 // All functions get the same args, the arguments after the command name69 // PersistentPreRun: children of this command will inherit and execute70 PersistentPreRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 71–72why, one step back71 // PersistentPreRunE: PersistentPreRun but returns an error72 PersistentPreRunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 73–74why, one step back73 // PreRun: children of this command will not inherit.74 PreRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 75–76why, one step back75 // PreRunE: PreRun but returns an error76 PreRunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 77why, one step back77 // Run: Typically the actual work function. Most commands will only implement thisOrganize the files a bit betterspf13before adoption62fb674
line 78why, one step back78 Run func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 79–80why, one step back79 // RunE: Run but returns an error80 RunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 81–82why, one step back81 // PostRun: run after the Run command.82 PostRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 83–84why, one step back83 // PostRunE: PostRun but returns an error84 PostRunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 85–86why, one step back85 // PersistentPostRun: children of this command will inherit and execute after PostRun86 PersistentPostRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 87–88why, one step back87 // PersistentPostRunE: PersistentPostRun but returns an error88 PersistentPostRunE func(cmd *Command, args []string) errorRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 89why, one step back89 // Commands is the list of commands supported by this program.Organize the files a bit betterspf13before adoption62fb674
lines 90–91why, one step back90 commands []*Command91 // Parent Command for this commandRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 92why, one step back92 parent *CommandMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 93–95why, one step back93 // max lengths of commands' string lengths for use in padding94 commandsMaxUseLen int95 commandsMaxCommandPathLen inthelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 96why, one step back96 commandsMaxNameLen intRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 97why, one step back97Organize the files a bit betterspf13before adoption62fb674
line 98why, one step back98 flagErrorBuf *bytes.BufferRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 99why, one step back99Code commentaryAhsanul Haquebefore adoptione1e66f7
line 100why, one step back100 args []string // actual args parsed from flagsDocumentation updatespf13before adoption59bd285
line 101why, one step back101 output *io.Writer // nil means stderr; use Out() method insteadRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 102–106why, one step back102 usageFunc func(*Command) error // Usage can be defined by application103 usageTemplate string // Can be defined by Application104 helpTemplate string // Can be defined by Application105 helpFunc func(*Command, []string) // Help can be defined by application106 helpCommand *Command // The help commandAdd Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 107–108why, one step back107 // The global normalization function that we can use on every pFlag set and children commands108 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedNameOrganize the files a bit betterspf13before adoption62fb674
lines 109–110why, one step back109}110Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 111–114why, one step back111// os.Args[1:] by default, if desired, can be overridden112// particularly useful when testing.113func (c *Command) SetArgs(a []string) {114 c.args = aAdd ability to cast a command to a commanderspf13before adoption74ce44d
lines 115–116why, one step back115}116Default usage output to stdoutEric Parisbefore adoption6de96b8
line 117why, one step back117func (c *Command) getOut(def io.Writer) io.Writer {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 118–124why, one step back118 if c.output != nil {119 return *c.output120 }121122 if c.HasParent() {123 return c.parent.Out()124 } else {Default usage output to stdoutEric Parisbefore adoption6de96b8
line 125why, one step back125 return defRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 126–128why, one step back126 }127}128Default usage output to stdoutEric Parisbefore adoption6de96b8
lines 129–136why, one step back129func (c *Command) Out() io.Writer {130 return c.getOut(os.Stderr)131}132133func (c *Command) getOutOrStdout() io.Writer {134 return c.getOut(os.Stdout)135}136Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 137–166why, one step back137// SetOutput sets the destination for usage and error messages.138// If output is nil, os.Stderr is used.139func (c *Command) SetOutput(output io.Writer) {140 c.output = &output141}142143// Usage can be defined by application144func (c *Command) SetUsageFunc(f func(*Command) error) {145 c.usageFunc = f146}147148// Can be defined by Application149func (c *Command) SetUsageTemplate(s string) {150 c.usageTemplate = s151}152153// Can be defined by Application154func (c *Command) SetHelpFunc(f func(*Command, []string)) {155 c.helpFunc = f156}157158func (c *Command) SetHelpCommand(cmd *Command) {159 c.helpCommand = cmd160}161162// Can be defined by Application163func (c *Command) SetHelpTemplate(s string) {164 c.helpTemplate = s165}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}178Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 179–188why, one step back179func (c *Command) UsageFunc() (f func(*Command) error) {180 if c.usageFunc != nil {181 return c.usageFunc182 }183184 if c.HasParent() {185 return c.parent.UsageFunc()186 } else {187 return func(c *Command) error {188 err := tmpl(c.Out(), c.UsageTemplate(), c)Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7
lines 189–191why, one step back189 if err != nil {190 fmt.Print(err)191 }Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 192–195why, one step back192 return err193 }194 }195}Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 196–198why, one step back196197// HelpFunc returns either the function set by SetHelpFunc for this command198// or a parent, or it returns a function which calls c.Help()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 199why, one step back199func (c *Command) HelpFunc() func(*Command, []string) {Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 200–205why, one step back200 cmd := c201 for cmd != nil {202 if cmd.helpFunc != nil {203 return cmd.helpFunc204 }205 cmd = cmd.parentRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 206why, one step back206 }Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 207–210why, one step back207 return func(*Command, []string) {208 err := c.Help()209 if err != nil {210 c.Println(err)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 211–214why, one step back211 }212 }213}214Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 215–226why, one step back215var minUsagePadding int = 25216217func (c *Command) UsagePadding() int {218 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {219 return minUsagePadding220 } else {221 return c.parent.commandsMaxUseLen222 }223}224225var minCommandPathPadding int = 11226Code commentaryAhsanul Haquebefore adoptione1e66f7
line 227why, one step back227//Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 228–235why, one step back228func (c *Command) CommandPathPadding() int {229 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {230 return minCommandPathPadding231 } else {232 return c.parent.commandsMaxCommandPathLen233 }234}235help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 236–245why, one step back236var minNamePadding int = 11237238func (c *Command) NamePadding() int {239 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {240 return minNamePadding241 } else {242 return c.parent.commandsMaxNameLen243 }244}245Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 246–253why, one step back246func (c *Command) UsageTemplate() string {247 if c.usageTemplate != "" {248 return c.usageTemplate249 }250251 if c.HasParent() {252 return c.parent.UsageTemplate()253 } else {Merge pull request #153 from eparis/remove-useless-assignmentEric Parisbefore adoptioneeec8e3
line 254why, one step back254 return `Usage:{{if .Runnable}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 255why, one step back255 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 256–258why, one step back256 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}257258Aliases:New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 259–260why, one step back259 {{.NameAndAliases}}260{{end}}{{if .HasExample}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 261why, one step back261New "example" section of commandsEric Parisbefore adoptionbf480fe
line 262why, one step back262Examples:Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 263why, one step back263{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 264why, one step back264Merge pull request #148 from tamird/trailing-spacesEric Parisbefore adoption42498ec
line 265why, one step back265Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
lines 266–268why, one step back266 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}}267268Flags:Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7
line 269why, one step back269{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasInheritedFlags}}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
lines 270–271why, one step back270271Global Flags:Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7
line 272why, one step back272{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 273why, one step back273Merge pull request #148 from tamird/trailing-spacesEric Parisbefore adoption42498ec
line 274why, one step back274Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}Merge pull request #137 from eparis/fix-help-templateEric Parisbefore adoption99d2c51
line 275why, one step back275 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 276why, one step back276Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 277why, one step back277Use "{{.CommandPath}} [command] --help" for more information about a command.Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 278why, one step back278{{end}}`Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 279–289why, one step back279 }280}281282func (c *Command) HelpTemplate() string {283 if c.helpTemplate != "" {284 return c.helpTemplate285 }286287 if c.HasParent() {288 return c.parent.HelpTemplate()289 } else {Merge pull request #151 from eparis/no-newline-without-shortEric Parisbefore adoption85bb343
lines 290–292why, one step back290 return `{{with or .Long .Short }}{{. | trim}}291292{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 293–295why, one step back293 }294}295Add ability to cast a command to a commanderspf13before adoption74ce44d
lines 296–302why, one step back296// Really only used when casting a command to a commander297func (c *Command) resetChildrensParents() {298 for _, x := range c.commands {299 x.parent = c300 }301}302Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 303–313why, one step back303// Test if the named flag is a boolean flag.304func isBooleanFlag(name string, f *flag.FlagSet) bool {305 flag := f.Lookup(name)306 if flag == nil {307 return false308 }309 return flag.Value.Type() == "bool"310}311312// Test if the named flag is a boolean flag.313func isBooleanShortFlag(name string, f *flag.FlagSet) bool {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 314–319why, one step back314 result := false315 f.VisitAll(func(f *flag.Flag) {316 if f.Shorthand == name && f.Value.Type() == "bool" {317 result = true318 }319 })Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 320–323why, one step back320 return result321}322323func stripFlags(args []string, c *Command) []string {Support for flags before commandsspf13before adoption10a8494
lines 324–326why, one step back324 if len(args) < 1 {325 return args326 }Merge pull request #70 from brendandburns/masterBjørn Erik Pedersenbefore adoption6264dc6
line 327why, one step back327 c.mergePersistentFlags()Support for flags before commandsspf13before adoption10a8494
lines 328–331why, one step back328329 commands := []string{}330331 inQuote := falseFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 332why, one step back332 inFlag := falseSupport for flags before commandsspf13before adoption10a8494
lines 333–339why, one step back333 for _, y := range args {334 if !inQuote {335 switch {336 case strings.HasPrefix(y, "\""):337 inQuote = true338 case strings.Contains(y, "=\""):339 inQuote = trueFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 340–346why, one step back340 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):341 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'342 inFlag = !isBooleanFlag(y[2:], c.Flags())343 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):344 inFlag = true345 case inFlag:346 inFlag = falseMerge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1
lines 347–348why, one step back347 case y == "":348 // strip empty commands, as the go tests expect this to be ok....Support for flags before commandsspf13before adoption10a8494
lines 349–350why, one step back349 case !strings.HasPrefix(y, "-"):350 commands = append(commands, y)Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 351why, one step back351 inFlag = falseSupport for flags before commandsspf13before adoption10a8494
lines 352–362why, one step back352 }353 }354355 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {356 inQuote = false357 }358 }359360 return commands361}362Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
lines 363–371why, one step back363// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like364// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).365func argsMinusFirstX(args []string, x string) []string {366 for i, y := range args {367 if x == y {368 ret := []string{}369 ret = append(ret, args[:i]...)370 ret = append(ret, args[i+1:]...)371 return retSupport for flags before commandsspf13before adoption10a8494
lines 372–373why, one step back372 }373 }Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
line 374why, one step back374 return argsSupport for flags before commandsspf13before adoption10a8494
lines 375–376why, one step back375}376Organize the files a bit betterspf13before adoption62fb674
line 377why, one step back377// find the target command given the args and command treeAdd support for help commandspf13before adoptionfb2146e
line 378why, one step back378// Meant to be run on the highest node. Only searches down.Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 379why, one step back379func (c *Command) Find(args []string) (*Command, []string, error) {Organize the files a bit betterspf13before adoption62fb674
lines 380–383why, one step back380 if c == nil {381 return nil, nil, fmt.Errorf("Called find() on a nil Command")382 }383Finding command based on args cleaned upspf13before adoption55ff474
lines 384–385why, one step back384 var innerfind func(*Command, []string) (*Command, []string)385Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 386why, one step back386 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 387–403why, one step back387 argsWOflags := stripFlags(innerArgs, c)388 if len(argsWOflags) == 0 {389 return c, innerArgs390 }391 nextSubCmd := argsWOflags[0]392 matches := make([]*Command, 0)393 for _, cmd := range c.commands {394 if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match395 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))396 }397 if EnablePrefixMatching {398 if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match399 matches = append(matches, cmd)400 }401 for _, x := range cmd.Aliases {402 if strings.HasPrefix(x, nextSubCmd) {403 matches = append(matches, cmd)Support for flags before commandsspf13before adoption10a8494
line 404why, one step back404 }adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
line 405why, one step back405 }Organize the files a bit betterspf13before adoption62fb674
lines 406–407why, one step back406 }407 }Finding command based on args cleaned upspf13before adoption55ff474
line 408why, one step back408Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 409–413why, one step back409 // only accept a single prefix match - multiple matches would be ambiguous410 if len(matches) == 1 {411 return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))412 }413Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 414why, one step back414 return c, innerArgsOrganize the files a bit betterspf13before adoption62fb674
line 415why, one step back415 }Finding command based on args cleaned upspf13before adoption55ff474
line 416why, one step back416Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 417why, one step back417 commandFound, a := innerfind(c, args)Merge pull request #119 from eparis/bogus-bad-commandEric Parisbefore adoption66816bc
line 418why, one step back418 argsWOflags := stripFlags(a, commandFound)Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 419–424why, one step back419420 // no subcommand, always take args421 if !commandFound.HasSubCommands() {422 return commandFound, a, nil423 }424 // root command with subcommands, do subcommand checkingMerge pull request #119 from eparis/bogus-bad-commandEric Parisbefore adoption66816bc
line 425why, one step back425 if commandFound == c && len(argsWOflags) > 0 {Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 426why, one step back426 return commandFound, a, fmt.Errorf("unknown command %q for %q", argsWOflags[0], commandFound.CommandPath())Organize the files a bit betterspf13before adoption62fb674
lines 427–428why, one step back427 }428Finding command based on args cleaned upspf13before adoption55ff474
line 429why, one step back429 return commandFound, a, nilOrganize the files a bit betterspf13before adoption62fb674
lines 430–431why, one step back430}431Add support for help commandspf13before adoptionfb2146e
line 432why, one step back432func (c *Command) Root() *Command {Organize the files a bit betterspf13before adoption62fb674
lines 433–441why, one step back433 var findRoot func(*Command) *Command434435 findRoot = func(x *Command) *Command {436 if x.HasParent() {437 return findRoot(x.parent)438 } else {439 return x440 }441 }Add support for help commandspf13before adoptionfb2146e
lines 442–445why, one step back442443 return findRoot(c)444}445fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 446why, one step back446func (c *Command) execute(a []string) (err error) {Organize the files a bit betterspf13before adoption62fb674
lines 447–448why, one step back447 if c == nil {448 return fmt.Errorf("Called Execute() on a nil Command")Merge pull request #90 from eparis/deprecated-subcommandsEric Parisbefore adoption9cf0f37
lines 449–452why, one step back449 }450451 if len(c.Deprecated) > 0 {452 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)Organize the files a bit betterspf13before adoption62fb674
lines 453–454why, one step back453 }454Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
lines 455–458why, one step back455 // initialize help flag as the last point possible to allow for user456 // overriding457 c.initHelpFlag()458fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 459–461why, one step back459 err = c.ParseFlags(a)460 if err != nil {461 return errMerge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 462why, one step back462 }Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 463why, one step back463 // 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 464why, one step back464 // Also say we need help if the command isn't runnable.Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
lines 465–472why, one step back465 helpVal, err := c.Flags().GetBool("help")466 if err != nil {467 // should be impossible to get here as we always declare a help468 // flag in initHelpFlag()469 c.Println("\"help\" flag declared as non-bool. Please correct your code")470 return err471 }472 if helpVal || !c.Runnable() {Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 473why, one step back473 return flag.ErrHelpOrganize the files a bit betterspf13before adoption62fb674
line 474why, one step back474 }Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
lines 475–477why, one step back475476 c.preRun()477 argWoFlags := c.Flags().Args()Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 478why, one step back478Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
line 479why, one step back479 for p := c; p != nil; p = p.Parent() {Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 480–485why, one step back480 if p.PersistentPreRunE != nil {481 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {482 return err483 }484 break485 } else if p.PersistentPreRun != nil {Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
lines 486–488why, one step back486 p.PersistentPreRun(c, argWoFlags)487 break488 }Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 489why, one step back489 }Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 490–494why, one step back490 if c.PreRunE != nil {491 if err := c.PreRunE(c, argWoFlags); err != nil {492 return err493 }494 } else if c.PreRun != nil {Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 495–497why, one step back495 c.PreRun(c, argWoFlags)496 }497Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 498–509why, one step back498 if c.RunE != nil {499 if err := c.RunE(c, argWoFlags); err != nil {500 return err501 }502 } else {503 c.Run(c, argWoFlags)504 }505 if c.PostRunE != nil {506 if err := c.PostRunE(c, argWoFlags); err != nil {507 return err508 }509 } else if c.PostRun != nil {Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 510–511why, one step back510 c.PostRun(c, argWoFlags)511 }Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
line 512why, one step back512 for p := c; p != nil; p = p.Parent() {Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 513–518why, one step back513 if p.PersistentPostRunE != nil {514 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {515 return err516 }517 break518 } else if p.PersistentPostRun != nil {Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
lines 519–521why, one step back519 p.PersistentPostRun(c, argWoFlags)520 break521 }Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 522–523why, one step back522 }523Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 524why, one step back524 return nilOrganize the files a bit betterspf13before adoption62fb674
lines 525–526why, one step back525}526Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 527why, one step back527func (c *Command) preRun() {Adding "OnInitialize()" method instead of directly setting a property. Now can have multiple initializers.spf13before adoption864687a
lines 528–530why, one step back528 for _, x := range initializers {529 x()530 }Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 531–532why, one step back531}532Support for flags before commandsspf13before adoption10a8494
lines 533–544why, one step back533func (c *Command) errorMsgFromParse() string {534 s := c.flagErrorBuf.String()535536 x := strings.Split(s, "\n")537538 if len(x) > 0 {539 return x[0]540 } else {541 return ""542 }543}544Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 545–552why, one step back545// Call execute to use the args (os.Args[1:] by default)546// and run through the command tree finding appropriate matches547// for commands and then corresponding flags.548func (c *Command) Execute() (err error) {549550 // Regardless of what command execute is called on, run on Root only551 if c.HasParent() {552 return c.Root().Execute()Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29
lines 553–560why, one step back553 }554555 if EnableWindowsMouseTrap && runtime.GOOS == "windows" {556 if mousetrap.StartedByExplorer() {557 c.Print(MousetrapHelpText)558 time.Sleep(5 * time.Second)559 os.Exit(1)560 }Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 561–564why, one step back561 }562563 // initialize help as the last point possible to allow for user564 // overridingMerge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 565why, one step back565 c.initHelpCmd()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 566–574why, one step back566567 var args []string568569 if len(c.args) == 0 {570 args = os.Args[1:]571 } else {572 args = c.args573 }574Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 575why, one step back575 cmd, flags, err := c.Find(args)Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 576–583why, one step back576 if err != nil {577 // If found parse to a subcommand and then failed, talk about the subcommand578 if cmd != nil {579 c = cmd580 }581 c.Println("Error:", err.Error())582 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())583 return errRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 584–585why, one step back584 }585Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 586why, one step back586 err = cmd.execute(flags)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 587why, one step back587 if err != nil {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
line 588why, one step back588 if err == flag.ErrHelp {Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
line 589why, one step back589 cmd.HelpFunc()(cmd, args)Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 590why, one step back590 return nilRemove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
line 591why, one step back591 }Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 592–593why, one step back592 c.Println(cmd.UsageString())593 c.Println("Error:", err.Error())Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 594–598why, one step back594 }595596 return597}598Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 599why, one step back599func (c *Command) initHelpFlag() {Merge pull request #133 from eparis/late-init-help-flagEric Parisbefore adoption4c4f2d9
line 600why, one step back600 if c.Flags().Lookup("help") == nil {Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 601why, one step back601 c.Flags().BoolP("help", "h", false, "help for "+c.Name())Merge pull request #133 from eparis/late-init-help-flagEric Parisbefore adoption4c4f2d9
line 602why, one step back602 }Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
lines 603–605why, one step back603}604605func (c *Command) initHelpCmd() {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 606why, one step back606 if c.helpCommand == nil {Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
lines 607–610why, one step back607 if !c.HasSubCommands() {608 return609 }610Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 611–615why, one step back611 c.helpCommand = &Command{612 Use: "help [command]",613 Short: "Help about any command",614 Long: `Help provides help for any command in the application.615 Simply type ` + c.Name() + ` help [path to command] for full details.`,Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 616–617why, one step back616 PersistentPreRun: func(cmd *Command, args []string) {},617 PersistentPostRun: func(cmd *Command, args []string) {},Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 618–628why, one step back618619 Run: func(c *Command, args []string) {620 cmd, _, e := c.Root().Find(args)621 if cmd == nil || e != nil {622 c.Printf("Unknown help topic %#q.", args)623 c.Root().Usage()624 } else {625 helpFunc := cmd.HelpFunc()626 helpFunc(cmd, args)627 }628 },Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 629–633why, one step back629 }630 }631 c.AddCommand(c.helpCommand)632}633Organize the files a bit betterspf13before adoption62fb674
lines 634–636why, one step back634// Used for testing635func (c *Command) ResetCommands() {636 c.commands = nilMerge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 637why, one step back637 c.helpCommand = nilOrganize the files a bit betterspf13before adoption62fb674
lines 638–639why, one step back638}639Code commentaryAhsanul Haquebefore adoptione1e66f7
line 640why, one step back640//Commands returns a slice of child commands.Organize the files a bit betterspf13before adoption62fb674
lines 641–644why, one step back641func (c *Command) Commands() []*Command {642 return c.commands643}644Code commentaryAhsanul Haquebefore adoptione1e66f7
line 645why, one step back645// AddCommand adds one or more commands to this parent command.Organize the files a bit betterspf13before adoption62fb674
lines 646–651why, one step back646func (c *Command) AddCommand(cmds ...*Command) {647 for i, x := range cmds {648 if cmds[i] == c {649 panic("Command can't be a child of itself")650 }651 cmds[i].parent = cMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 652–659why, one step back652 // update max lengths653 usageLen := len(x.Use)654 if usageLen > c.commandsMaxUseLen {655 c.commandsMaxUseLen = usageLen656 }657 commandPathLen := len(x.CommandPath())658 if commandPathLen > c.commandsMaxCommandPathLen {659 c.commandsMaxCommandPathLen = commandPathLenhelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 660–663why, one step back660 }661 nameLen := len(x.Name())662 if nameLen > c.commandsMaxNameLen {663 c.commandsMaxNameLen = nameLenMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
line 664why, one step back664 }Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 665–668why, one step back665 // If glabal normalization function exists, update all children666 if c.globNormFunc != nil {667 x.SetGlobalNormalizationFunc(c.globNormFunc)668 }Organize the files a bit betterspf13before adoption62fb674
lines 669–672why, one step back669 c.commands = append(c.commands, x)670 }671}672Add Command's RemoveCommand methodÉtienne Vallette d'Osiabefore adoptionf479c92
lines 673–706why, one step back673// AddCommand removes one or more commands from a parent command.674func (c *Command) RemoveCommand(cmds ...*Command) {675 commands := []*Command{}676main:677 for _, command := range c.commands {678 for _, cmd := range cmds {679 if command == cmd {680 command.parent = nil681 continue main682 }683 }684 commands = append(commands, command)685 }686 c.commands = commands687 // recompute all lengths688 c.commandsMaxUseLen = 0689 c.commandsMaxCommandPathLen = 0690 c.commandsMaxNameLen = 0691 for _, command := range c.commands {692 usageLen := len(command.Use)693 if usageLen > c.commandsMaxUseLen {694 c.commandsMaxUseLen = usageLen695 }696 commandPathLen := len(command.CommandPath())697 if commandPathLen > c.commandsMaxCommandPathLen {698 c.commandsMaxCommandPathLen = commandPathLen699 }700 nameLen := len(command.Name())701 if nameLen > c.commandsMaxNameLen {702 c.commandsMaxNameLen = nameLen703 }704 }705}706Organize the files a bit betterspf13before adoption62fb674
lines 707–708why, one step back707// Convenience method to Print to the defined output708func (c *Command) Print(i ...interface{}) {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 709why, one step back709 fmt.Fprint(c.Out(), i...)Organize the files a bit betterspf13before adoption62fb674
lines 710–725why, one step back710}711712// Convenience method to Println to the defined output713func (c *Command) Println(i ...interface{}) {714 str := fmt.Sprintln(i...)715 c.Print(str)716}717718// Convenience method to Printf to the defined output719func (c *Command) Printf(format string, i ...interface{}) {720 str := fmt.Sprintf(format, i...)721 c.Print(str)722}723724// Output the usage for the command725// Used when a user provides invalid inputRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 726why, one step back726// Can be defined by user by overriding UsageFuncOrganize the files a bit betterspf13before adoption62fb674
line 727why, one step back727func (c *Command) Usage() error {Help improvementsspf13before adoption2d02c31
line 728why, one step back728 c.mergePersistentFlags()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 729why, one step back729 err := c.UsageFunc()(c)Help improvementsspf13before adoption2d02c31
lines 730–737why, one step back730 return err731}732733// Output the help for the command734// Used when a user calls help [command]735// by the default HelpFunc in the commander736func (c *Command) Help() error {737 c.mergePersistentFlags()Default usage output to stdoutEric Parisbefore adoption6de96b8
line 738why, one step back738 err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)Organize the files a bit betterspf13before adoption62fb674
lines 739–741why, one step back739 return err740}741fix trailing <nil> on help outputspf13before adoption3958385
line 742why, one step back742func (c *Command) UsageString() string {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 743why, one step back743 tmpOutput := c.outputfix trailing <nil> on help outputspf13before adoption3958385
line 744why, one step back744 bb := new(bytes.Buffer)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 745why, one step back745 c.SetOutput(bb)fix trailing <nil> on help outputspf13before adoption3958385
line 746why, one step back746 c.Usage()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 747why, one step back747 c.output = tmpOutputfix trailing <nil> on help outputspf13before adoption3958385
lines 748–750why, one step back748 return bb.String()749}750Code commentaryAhsanul Haquebefore adoptione1e66f7
line 751why, one step back751// CommandPath returns the full path to this command.Organize the files a bit betterspf13before adoption62fb674
lines 752–826why, one step back752func (c *Command) CommandPath() string {753 str := c.Name()754 x := c755 for x.HasParent() {756 str = x.parent.Name() + " " + str757 x = x.parent758 }759 return str760}761762//The full usage for a given command (including parents)763func (c *Command) UseLine() string {764 str := ""765 if c.HasParent() {766 str = c.parent.CommandPath() + " "767 }768 return str + c.Use769}770771// For use in determining which flags have been assigned to which commands772// and which persist773func (c *Command) DebugFlags() {774 c.Println("DebugFlags called on", c.Name())775 var debugflags func(*Command)776777 debugflags = func(x *Command) {778 if x.HasFlags() || x.HasPersistentFlags() {779 c.Println(x.Name())780 }781 if x.HasFlags() {782 x.flags.VisitAll(func(f *flag.Flag) {783 if x.HasPersistentFlags() {784 if x.persistentFlag(f.Name) == nil {785 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")786 } else {787 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")788 }789 } else {790 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")791 }792 })793 }794 if x.HasPersistentFlags() {795 x.pflags.VisitAll(func(f *flag.Flag) {796 if x.HasFlags() {797 if x.flags.Lookup(f.Name) == nil {798 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")799 }800 } else {801 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")802 }803 })804 }805 c.Println(x.flagErrorBuf)806 if x.HasSubCommands() {807 for _, y := range x.commands {808 debugflags(y)809 }810 }811 }812813 debugflags(c)814}815816// Name returns the command's name: the first word in the use line.817func (c *Command) Name() string {818 if c.name != "" {819 return c.name820 }821 name := c.Use822 i := strings.Index(name, " ")823 if i >= 0 {824 name = name[:i]825 }826 return nameReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 827–840why, one step back827}828829// Determine if a given string is an alias of the command.830func (c *Command) HasAlias(s string) bool {831 for _, a := range c.Aliases {832 if a == s {833 return true834 }835 }836 return false837}838839func (c *Command) NameAndAliases() string {840 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 841–844why, one step back841}842843func (c *Command) HasExample() bool {844 return len(c.Example) > 0Organize the files a bit betterspf13before adoption62fb674
lines 845–848why, one step back845}846847// Determine if the command is itself runnable848func (c *Command) Runnable() bool {Merge pull request #139 from alexanderguy/RunE-is-runnableBjørn Erik Pedersenbefore adoption1ba88c4
line 849why, one step back849 return c.Run != nil || c.RunE != nilOrganize the files a bit betterspf13before adoption62fb674
lines 850–854why, one step back850}851852// Determine if the command has children commands853func (c *Command) HasSubCommands() bool {854 return len(c.commands) > 0Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 855–856why, one step back855}856Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 857–859why, one step back857// IsAvailableCommand determines if a command is available as a non-help command858// (this includes all non deprecated/hidden commands)859func (c *Command) IsAvailableCommand() bool {Merge pull request #146 from eparis/is-available-reworkEric Parisbefore adoption4b86c66
lines 860–862why, one step back860 if len(c.Deprecated) != 0 || c.Hidden {861 return false862 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 863why, one step back863Merge pull request #150 from eparis/help-not-availableEric Parisbefore adoption0d9b07b
lines 864–867why, one step back864 if c.HasParent() && c.Parent().helpCommand == c {865 return false866 }867Merge pull request #146 from eparis/is-available-reworkEric Parisbefore adoption4b86c66
lines 868–872why, one step back868 if c.Runnable() || c.HasAvailableSubCommands() {869 return true870 }871872 return falseMerge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 873–877why, one step back873}874875// IsHelpCommand determines if a command is a 'help' command; a help command is876// determined by the fact that it is NOT runnable/hidden/deprecated, and has no877// sub commands that are runnable/hidden/deprecatedMerge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 878why, one step back878func (c *Command) IsHelpCommand() bool {Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 879–881why, one step back879880 // if a command is runnable, deprecated, or hidden it is not a 'help' command881 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 882–883why, one step back882 return false883 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 884–885why, one step back884885 // if any non-help sub commands are found, the command is not a 'help' commandMerge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
lines 886–889why, one step back886 for _, sub := range c.commands {887 if !sub.IsHelpCommand() {888 return false889 }Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 890why, one step back890 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 891–892why, one step back891892 // the command either has no sub commands, or no non-help sub commandsMerge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 893why, one step back893 return trueMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 894–895why, one step back894}895Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 896–898why, one step back896// HasHelpSubCommands determines if a command has any avilable 'help' sub commands897// that need to be shown in the usage/help default template under 'additional help898// topics'Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 899why, one step back899func (c *Command) HasHelpSubCommands() bool {Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 900–901why, one step back900901 // return true on the first found available 'help' sub commandMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 902why, one step back902 for _, sub := range c.commands {Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 903why, one step back903 if sub.IsHelpCommand() {Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 904–906why, one step back904 return true905 }906 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 907–908why, one step back907908 // the command either has no sub commands, or no available 'help' sub commandsMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 909–911why, one step back909 return false910}911Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 912–917why, one step back912// HasAvailableSubCommands determines if a command has available sub commands that913// need to be shown in the usage/help default template under 'available commands'914func (c *Command) HasAvailableSubCommands() bool {915916 // return true on the first found available (non deprecated/help/hidden)917 // sub commandMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 918why, one step back918 for _, sub := range c.commands {Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 919why, one step back919 if sub.IsAvailableCommand() {Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 920–922why, one step back920 return true921 }922 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 923–925why, one step back923924 // the command either has no sub comamnds, or no available (non deprecated/help/hidden)925 // sub commandsMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 926why, one step back926 return falseOrganize the files a bit betterspf13before adoption62fb674
lines 927–931why, one step back927}928929// Determine if the command is a child command930func (c *Command) HasParent() bool {931 return c.parent != nilAdd Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 932–936why, one step back932}933934// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists935func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {936 return c.globNormFuncOrganize the files a bit betterspf13before adoption62fb674
lines 937–938why, one step back937}938Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 939why, one step back939// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)Organize the files a bit betterspf13before adoption62fb674
lines 940–950why, one step back940func (c *Command) Flags() *flag.FlagSet {941 if c.flags == nil {942 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)943 if c.flagErrorBuf == nil {944 c.flagErrorBuf = new(bytes.Buffer)945 }946 c.flags.SetOutput(c.flagErrorBuf)947 }948 return c.flags949}950Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 951–955why, one step back951// Get the local FlagSet specifically set in the current command952func (c *Command) LocalFlags() *flag.FlagSet {953 c.mergePersistentFlags()954955 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 956–957why, one step back956 c.lflags.VisitAll(func(f *flag.Flag) {957 local.AddFlag(f)Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 958why, one step back958 })Merge pull request #127 from eparis/show-commandline-on-parentEric Parisbefore adoptiondb05184
lines 959–965why, one step back959 if !c.HasParent() {960 flag.CommandLine.VisitAll(func(f *flag.Flag) {961 if local.Lookup(f.Name) == nil {962 local.AddFlag(f)963 }964 })965 }Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 966–968why, one step back966 return local967}968new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 969–972why, one step back969// All Flags which were inherited from parents commands970func (c *Command) InheritedFlags() *flag.FlagSet {971 c.mergePersistentFlags()972Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 973–974why, one step back973 inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)974 local := c.LocalFlags()new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 975why, one step back975Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 976why, one step back976 var rmerge func(x *Command)new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 977why, one step back977Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 978–989why, one step back978 rmerge = func(x *Command) {979 if x.HasPersistentFlags() {980 x.PersistentFlags().VisitAll(func(f *flag.Flag) {981 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {982 inherited.AddFlag(f)983 }984 })985 }986 if x.HasParent() {987 rmerge(x.parent)988 }989 }new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 990–994why, one step back990991 if c.HasParent() {992 rmerge(c.parent)993 }994Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 995why, one step back995 return inheritednew InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 996–997why, one step back996}997new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 998–999why, one step back998// All Flags which were not inherited from parent commands999func (c *Command) NonInheritedFlags() *flag.FlagSet {Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 1000why, one step back1000 return c.LocalFlags()new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 1001–1002why, one step back1001}1002Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 1003why, one step back1003// Get the Persistent FlagSet specifically set in the current commandOrganize the files a bit betterspf13before adoption62fb674
lines 1004–1024why, one step back1004func (c *Command) PersistentFlags() *flag.FlagSet {1005 if c.pflags == nil {1006 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1007 if c.flagErrorBuf == nil {1008 c.flagErrorBuf = new(bytes.Buffer)1009 }1010 c.pflags.SetOutput(c.flagErrorBuf)1011 }1012 return c.pflags1013}10141015// For use in testing1016func (c *Command) ResetFlags() {1017 c.flagErrorBuf = new(bytes.Buffer)1018 c.flagErrorBuf.Reset()1019 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1020 c.flags.SetOutput(c.flagErrorBuf)1021 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1022 c.pflags.SetOutput(c.flagErrorBuf)1023}1024Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 1025why, one step back1025// Does the command contain any flags (local plus persistent from the entire structure)Organize the files a bit betterspf13before adoption62fb674
lines 1026–1034why, one step back1026func (c *Command) HasFlags() bool {1027 return c.Flags().HasFlags()1028}10291030// Does the command contain persistent flags1031func (c *Command) HasPersistentFlags() bool {1032 return c.PersistentFlags().HasFlags()1033}1034Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1035–1039why, one step back1035// Does the command has flags specifically declared locally1036func (c *Command) HasLocalFlags() bool {1037 return c.LocalFlags().HasFlags()1038}1039Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1040–1043why, one step back1040func (c *Command) HasInheritedFlags() bool {1041 return c.InheritedFlags().HasFlags()1042}1043Organize the files a bit betterspf13before adoption62fb674
lines 1044–1070why, one step back1044// Climbs up the command tree looking for matching flag1045func (c *Command) Flag(name string) (flag *flag.Flag) {1046 flag = c.Flags().Lookup(name)10471048 if flag == nil {1049 flag = c.persistentFlag(name)1050 }10511052 return1053}10541055// recursively find matching persistent flag1056func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1057 if c.HasPersistentFlags() {1058 flag = c.PersistentFlags().Lookup(name)1059 }10601061 if flag == nil && c.HasParent() {1062 flag = c.parent.persistentFlag(name)1063 }1064 return1065}10661067// Parses persistent flag tree & local flags1068func (c *Command) ParseFlags(args []string) (err error) {1069 c.mergePersistentFlags()1070 err = c.Flags().Parse(args)Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e
line 1071why, one step back1071 returnOrganize the files a bit betterspf13before adoption62fb674
lines 1072–1073why, one step back1072}1073Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1074–1077why, one step back1074func (c *Command) Parent() *Command {1075 return c.parent1076}1077Organize the files a bit betterspf13before adoption62fb674
lines 1078–1080why, one step back1078func (c *Command) mergePersistentFlags() {1079 var rmerge func(x *Command)1080Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1081–1093why, one step back1081 // Save the set of local flags1082 if c.lflags == nil {1083 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1084 if c.flagErrorBuf == nil {1085 c.flagErrorBuf = new(bytes.Buffer)1086 }1087 c.lflags.SetOutput(c.flagErrorBuf)1088 addtolocal := func(f *flag.Flag) {1089 c.lflags.AddFlag(f)1090 }1091 c.Flags().VisitAll(addtolocal)1092 c.PersistentFlags().VisitAll(addtolocal)1093 }Organize the files a bit betterspf13before adoption62fb674
line 1094why, one step back1094 rmerge = func(x *Command) {Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 1095why, one step back1095 if !x.HasParent() {Merge pull request #75 from eparis/CommandLineEric Parisbefore adoption2d5fab0
lines 1096–1101why, one step back1096 flag.CommandLine.VisitAll(func(f *flag.Flag) {1097 if x.PersistentFlags().Lookup(f.Name) == nil {1098 x.PersistentFlags().AddFlag(f)1099 }1100 })1101 }Organize the files a bit betterspf13before adoption62fb674
lines 1102–1115why, one step back1102 if x.HasPersistentFlags() {1103 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1104 if c.Flags().Lookup(f.Name) == nil {1105 c.Flags().AddFlag(f)1106 }1107 })1108 }1109 if x.HasParent() {1110 rmerge(x.parent)1111 }1112 }11131114 rmerge(c)1115}