command.go
This file
Path
command.go
1,197 lines · 31.1 KiB · Go
Last changed by
always show help if requested, even if SilenceErrors is enabledSascha Holzleiterbefore adoption2bd8a73
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"Limit the verbose test workaround to "cobra.test" onlyAnthony Fokbefore adoptione576205
line 23why, one step back23 "path/filepath"Organize the files a bit betterspf13before adoption62fb674
line 24why, one step back24 "strings"Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
lines 25–26why, one step back2526 flag "github.com/spf13/pflag"Organize the files a bit betterspf13before adoption62fb674
lines 27–37why, one step back27)2829// Command is just that, a command for your application.30// eg. 'go run' ... 'run' is the command. Cobra requires31// you to define the usage and description as part of your command32// definition to ensure usability.33type Command struct {34 // Name is the command name, usually the executable's name.35 name string36 // The one-line usage message.37 Use stringReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 38–39why, one step back38 // An array of aliases that can be used instead of the first word in Use.39 Aliases []stringMerge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
lines 40–41why, one step back40 // An array of command names for which this command will be suggested - similar to aliases but only suggests.41 SuggestFor []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 #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e
lines 62–65why, one step back62 // SilenceErrors is an option to quiet errors down stream63 SilenceErrors bool64 // Silence Usage is an option to silence usage when an error occurs.65 SilenceUsage boolMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 66–74why, one step back66 // The *Run functions are executed in the following order:67 // * PersistentPreRun()68 // * PreRun()69 // * Run()70 // * PostRun()71 // * PersistentPostRun()72 // All functions get the same args, the arguments after the command name73 // PersistentPreRun: children of this command will inherit and execute74 PersistentPreRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 75–76why, one step back75 // PersistentPreRunE: PersistentPreRun but returns an error76 PersistentPreRunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 77–78why, one step back77 // PreRun: children of this command will not inherit.78 PreRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 79–80why, one step back79 // PreRunE: PreRun but returns an error80 PreRunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 81why, one step back81 // Run: Typically the actual work function. Most commands will only implement thisOrganize the files a bit betterspf13before adoption62fb674
line 82why, one step back82 Run func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 83–84why, one step back83 // RunE: Run but returns an error84 RunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 85–86why, one step back85 // PostRun: run after the Run command.86 PostRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 87–88why, one step back87 // PostRunE: PostRun but returns an error88 PostRunE func(cmd *Command, args []string) errorMerge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 89–90why, one step back89 // PersistentPostRun: children of this command will inherit and execute after PostRun90 PersistentPostRun func(cmd *Command, args []string)Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 91–92why, one step back91 // PersistentPostRunE: PersistentPostRun but returns an error92 PersistentPostRunE func(cmd *Command, args []string) erroradd a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a
lines 93–94why, one step back93 // DisableAutoGenTag remove94 DisableAutoGenTag boolRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 95why, one step back95 // Commands is the list of commands supported by this program.Organize the files a bit betterspf13before adoption62fb674
lines 96–97why, one step back96 commands []*Command97 // Parent Command for this commandRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 98why, one step back98 parent *CommandMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 99–101why, one step back99 // max lengths of commands' string lengths for use in padding100 commandsMaxUseLen int101 commandsMaxCommandPathLen inthelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 102why, one step back102 commandsMaxNameLen intRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 103why, one step back103Organize the files a bit betterspf13before adoption62fb674
line 104why, one step back104 flagErrorBuf *bytes.BufferRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 105why, one step back105Code commentaryAhsanul Haquebefore adoptione1e66f7
line 106why, one step back106 args []string // actual args parsed from flagsDocumentation updatespf13before adoption59bd285
line 107why, one step back107 output *io.Writer // nil means stderr; use Out() method insteadRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 108–112why, one step back108 usageFunc func(*Command) error // Usage can be defined by application109 usageTemplate string // Can be defined by Application110 helpTemplate string // Can be defined by Application111 helpFunc func(*Command, []string) // Help can be defined by application112 helpCommand *Command // The help commandAdd Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 113–114why, one step back113 // The global normalization function that we can use on every pFlag set and children commands114 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedNameMerge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311
lines 115–119why, one step back115116 // Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages117 DisableSuggestions bool118 // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0119 SuggestionsMinimumDistance intOrganize the files a bit betterspf13before adoption62fb674
lines 120–121why, one step back120}121Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 122–125why, one step back122// os.Args[1:] by default, if desired, can be overridden123// particularly useful when testing.124func (c *Command) SetArgs(a []string) {125 c.args = aAdd ability to cast a command to a commanderspf13before adoption74ce44d
lines 126–127why, one step back126}127Default usage output to stdoutEric Parisbefore adoption6de96b8
line 128why, one step back128func (c *Command) getOut(def io.Writer) io.Writer {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 129–135why, one step back129 if c.output != nil {130 return *c.output131 }132133 if c.HasParent() {134 return c.parent.Out()135 } else {Default usage output to stdoutEric Parisbefore adoption6de96b8
line 136why, one step back136 return defRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 137–139why, one step back137 }138}139Default usage output to stdoutEric Parisbefore adoption6de96b8
lines 140–147why, one step back140func (c *Command) Out() io.Writer {141 return c.getOut(os.Stderr)142}143144func (c *Command) getOutOrStdout() io.Writer {145 return c.getOut(os.Stdout)146}147Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 148–177why, one step back148// SetOutput sets the destination for usage and error messages.149// If output is nil, os.Stderr is used.150func (c *Command) SetOutput(output io.Writer) {151 c.output = &output152}153154// Usage can be defined by application155func (c *Command) SetUsageFunc(f func(*Command) error) {156 c.usageFunc = f157}158159// Can be defined by Application160func (c *Command) SetUsageTemplate(s string) {161 c.usageTemplate = s162}163164// Can be defined by Application165func (c *Command) SetHelpFunc(f func(*Command, []string)) {166 c.helpFunc = f167}168169func (c *Command) SetHelpCommand(cmd *Command) {170 c.helpCommand = cmd171}172173// Can be defined by Application174func (c *Command) SetHelpTemplate(s string) {175 c.helpTemplate = s176}177Add Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 178–189why, one step back178// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.179// The user should not have a cyclic dependency on commands.180func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {181 c.Flags().SetNormalizeFunc(n)182 c.PersistentFlags().SetNormalizeFunc(n)183 c.globNormFunc = n184185 for _, command := range c.commands {186 command.SetGlobalNormalizationFunc(n)187 }188}189Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 190–199why, one step back190func (c *Command) UsageFunc() (f func(*Command) error) {191 if c.usageFunc != nil {192 return c.usageFunc193 }194195 if c.HasParent() {196 return c.parent.UsageFunc()197 } else {198 return func(c *Command) error {199 err := tmpl(c.Out(), c.UsageTemplate(), c)Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7
lines 200–202why, one step back200 if err != nil {201 fmt.Print(err)202 }Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 203–206why, one step back203 return err204 }205 }206}Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 207–209why, one step back207208// HelpFunc returns either the function set by SetHelpFunc for this command209// 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 210why, one step back210func (c *Command) HelpFunc() func(*Command, []string) {Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 211–216why, one step back211 cmd := c212 for cmd != nil {213 if cmd.helpFunc != nil {214 return cmd.helpFunc215 }216 cmd = cmd.parentRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 217why, one step back217 }Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 218–221why, one step back218 return func(*Command, []string) {219 err := c.Help()220 if err != nil {221 c.Println(err)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 222–225why, one step back222 }223 }224}225Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 226–237why, one step back226var minUsagePadding int = 25227228func (c *Command) UsagePadding() int {229 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {230 return minUsagePadding231 } else {232 return c.parent.commandsMaxUseLen233 }234}235236var minCommandPathPadding int = 11237Code commentaryAhsanul Haquebefore adoptione1e66f7
line 238why, one step back238//Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 239–246why, one step back239func (c *Command) CommandPathPadding() int {240 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {241 return minCommandPathPadding242 } else {243 return c.parent.commandsMaxCommandPathLen244 }245}246help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 247–256why, one step back247var minNamePadding int = 11248249func (c *Command) NamePadding() int {250 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {251 return minNamePadding252 } else {253 return c.parent.commandsMaxNameLen254 }255}256Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 257–264why, one step back257func (c *Command) UsageTemplate() string {258 if c.usageTemplate != "" {259 return c.usageTemplate260 }261262 if c.HasParent() {263 return c.parent.UsageTemplate()264 } else {Merge pull request #153 from eparis/remove-useless-assignmentEric Parisbefore adoptioneeec8e3
line 265why, one step back265 return `Usage:{{if .Runnable}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 266why, one step back266 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 267–269why, one step back267 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}268269Aliases:New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 270–271why, one step back270 {{.NameAndAliases}}271{{end}}{{if .HasExample}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 272why, one step back272New "example" section of commandsEric Parisbefore adoptionbf480fe
line 273why, one step back273Examples:Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 274why, one step back274{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 275why, one step back275Merge pull request #148 from tamird/trailing-spacesEric Parisbefore adoption42498ec
line 276why, one step back276Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
lines 277–279why, one step back277 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}}278279Flags:Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7
line 280why, one step back280{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasInheritedFlags}}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
lines 281–282why, one step back281282Global Flags:Merge pull request #152 from eparis/no-newline-after-flagsEric Parisbefore adoptiond96b4f7
line 283why, one step back283{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 284why, one step back284Merge pull request #148 from tamird/trailing-spacesEric Parisbefore adoption42498ec
line 285why, one step back285Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}Merge pull request #137 from eparis/fix-help-templateEric Parisbefore adoption99d2c51
line 286why, one step back286 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 287why, one step back287Merge pull request #154 from eparis/fix-trailing-newlineEric Parisbefore adoptionb28774d
lines 288–289why, one step back288Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}289`Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 290–300why, one step back290 }291}292293func (c *Command) HelpTemplate() string {294 if c.helpTemplate != "" {295 return c.helpTemplate296 }297298 if c.HasParent() {299 return c.parent.HelpTemplate()300 } else {Merge pull request #151 from eparis/no-newline-without-shortEric Parisbefore adoption85bb343
lines 301–303why, one step back301 return `{{with or .Long .Short }}{{. | trim}}302303{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 304–306why, one step back304 }305}306Add ability to cast a command to a commanderspf13before adoption74ce44d
lines 307–313why, one step back307// Really only used when casting a command to a commander308func (c *Command) resetChildrensParents() {309 for _, x := range c.commands {310 x.parent = c311 }312}313Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 314–324why, one step back314// Test if the named flag is a boolean flag.315func isBooleanFlag(name string, f *flag.FlagSet) bool {316 flag := f.Lookup(name)317 if flag == nil {318 return false319 }320 return flag.Value.Type() == "bool"321}322323// Test if the named flag is a boolean flag.324func isBooleanShortFlag(name string, f *flag.FlagSet) bool {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 325–330why, one step back325 result := false326 f.VisitAll(func(f *flag.Flag) {327 if f.Shorthand == name && f.Value.Type() == "bool" {328 result = true329 }330 })Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 331–334why, one step back331 return result332}333334func stripFlags(args []string, c *Command) []string {Support for flags before commandsspf13before adoption10a8494
lines 335–337why, one step back335 if len(args) < 1 {336 return args337 }Merge pull request #70 from brendandburns/masterBjørn Erik Pedersenbefore adoption6264dc6
line 338why, one step back338 c.mergePersistentFlags()Support for flags before commandsspf13before adoption10a8494
lines 339–342why, one step back339340 commands := []string{}341342 inQuote := falseFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 343why, one step back343 inFlag := falseSupport for flags before commandsspf13before adoption10a8494
lines 344–350why, one step back344 for _, y := range args {345 if !inQuote {346 switch {347 case strings.HasPrefix(y, "\""):348 inQuote = true349 case strings.Contains(y, "=\""):350 inQuote = trueFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 351–357why, one step back351 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):352 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'353 inFlag = !isBooleanFlag(y[2:], c.Flags())354 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):355 inFlag = true356 case inFlag:357 inFlag = falseMerge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1
lines 358–359why, one step back358 case y == "":359 // strip empty commands, as the go tests expect this to be ok....Support for flags before commandsspf13before adoption10a8494
lines 360–361why, one step back360 case !strings.HasPrefix(y, "-"):361 commands = append(commands, y)Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 362why, one step back362 inFlag = falseSupport for flags before commandsspf13before adoption10a8494
lines 363–373why, one step back363 }364 }365366 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {367 inQuote = false368 }369 }370371 return commands372}373Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
lines 374–382why, one step back374// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like375// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).376func argsMinusFirstX(args []string, x string) []string {377 for i, y := range args {378 if x == y {379 ret := []string{}380 ret = append(ret, args[:i]...)381 ret = append(ret, args[i+1:]...)382 return retSupport for flags before commandsspf13before adoption10a8494
lines 383–384why, one step back383 }384 }Merge pull request #95 from deads2k/deads-prevent-extra-removalClayton Colemanbefore adoptionaf6b555
line 385why, one step back385 return argsSupport for flags before commandsspf13before adoption10a8494
lines 386–387why, one step back386}387Organize the files a bit betterspf13before adoption62fb674
line 388why, one step back388// find the target command given the args and command treeAdd support for help commandspf13before adoptionfb2146e
line 389why, one step back389// Meant to be run on the highest node. Only searches down.Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 390why, one step back390func (c *Command) Find(args []string) (*Command, []string, error) {Organize the files a bit betterspf13before adoption62fb674
lines 391–394why, one step back391 if c == nil {392 return nil, nil, fmt.Errorf("Called find() on a nil Command")393 }394Finding command based on args cleaned upspf13before adoption55ff474
lines 395–396why, one step back395 var innerfind func(*Command, []string) (*Command, []string)396Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 397why, one step back397 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 398–414why, one step back398 argsWOflags := stripFlags(innerArgs, c)399 if len(argsWOflags) == 0 {400 return c, innerArgs401 }402 nextSubCmd := argsWOflags[0]403 matches := make([]*Command, 0)404 for _, cmd := range c.commands {405 if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match406 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))407 }408 if EnablePrefixMatching {409 if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match410 matches = append(matches, cmd)411 }412 for _, x := range cmd.Aliases {413 if strings.HasPrefix(x, nextSubCmd) {414 matches = append(matches, cmd)Support for flags before commandsspf13before adoption10a8494
line 415why, one step back415 }adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
line 416why, one step back416 }Organize the files a bit betterspf13before adoption62fb674
lines 417–418why, one step back417 }418 }Finding command based on args cleaned upspf13before adoption55ff474
line 419why, one step back419Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 420–424why, one step back420 // only accept a single prefix match - multiple matches would be ambiguous421 if len(matches) == 1 {422 return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))423 }424Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 425why, one step back425 return c, innerArgsOrganize the files a bit betterspf13before adoption62fb674
line 426why, one step back426 }Finding command based on args cleaned upspf13before adoption55ff474
line 427why, one step back427Fix root command without subcommands but with argumentsSam Ghodsbefore adoptione0f326d
line 428why, one step back428 commandFound, a := innerfind(c, args)Merge pull request #119 from eparis/bogus-bad-commandEric Parisbefore adoption66816bc
line 429why, one step back429 argsWOflags := stripFlags(a, commandFound)Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 430–434why, one step back430431 // no subcommand, always take args432 if !commandFound.HasSubCommands() {433 return commandFound, a, nil434 }Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311
line 435why, one step back435Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 436why, one step back436 // root command with subcommands, do subcommand checkingMerge pull request #119 from eparis/bogus-bad-commandEric Parisbefore adoption66816bc
line 437why, one step back437 if commandFound == c && len(argsWOflags) > 0 {Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
line 438why, one step back438 suggestionsString := ""Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311
lines 439–442why, one step back439 if !c.DisableSuggestions {440 if c.SuggestionsMinimumDistance <= 0 {441 c.SuggestionsMinimumDistance = 2442 }Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
lines 443–446why, one step back443 if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {444 suggestionsString += "\n\nDid you mean this?\n"445 for _, s := range suggestions {446 suggestionsString += fmt.Sprintf("\t%v\n", s)Merge pull request #149 from fabianofranz/siblingsEric Parisbefore adoption6d70311
lines 447–449why, one step back447 }448 }449 }Merge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
line 450why, one step back450 return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)Organize the files a bit betterspf13before adoption62fb674
lines 451–452why, one step back451 }452Finding command based on args cleaned upspf13before adoption55ff474
line 453why, one step back453 return commandFound, a, nilMerge pull request #163 from fabianofranz/siblings_improvementsEric Parisbefore adoption046a673
lines 454–473why, one step back454}455456func (c *Command) SuggestionsFor(typedName string) []string {457 suggestions := []string{}458 for _, cmd := range c.commands {459 if cmd.IsAvailableCommand() {460 levenshteinDistance := ld(typedName, cmd.Name(), true)461 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance462 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))463 if suggestByLevenshtein || suggestByPrefix {464 suggestions = append(suggestions, cmd.Name())465 }466 for _, explicitSuggestion := range cmd.SuggestFor {467 if strings.EqualFold(typedName, explicitSuggestion) {468 suggestions = append(suggestions, cmd.Name())469 }470 }471 }472 }473 return suggestionsOrganize the files a bit betterspf13before adoption62fb674
lines 474–475why, one step back474}475add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a
lines 476–490why, one step back476func (c *Command) VisitParents(fn func(*Command)) {477 var traverse func(*Command) *Command478479 traverse = func(x *Command) *Command {480 if x != c {481 fn(x)482 }483 if x.HasParent() {484 return traverse(x.parent)485 }486 return x487 }488 traverse(c)489}490Add support for help commandspf13before adoptionfb2146e
line 491why, one step back491func (c *Command) Root() *Command {Organize the files a bit betterspf13before adoption62fb674
lines 492–497why, one step back492 var findRoot func(*Command) *Command493494 findRoot = func(x *Command) *Command {495 if x.HasParent() {496 return findRoot(x.parent)497 }add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a
line 498why, one step back498 return xOrganize the files a bit betterspf13before adoption62fb674
line 499why, one step back499 }Add support for help commandspf13before adoptionfb2146e
lines 500–503why, one step back500501 return findRoot(c)502}503Merge pull request #167 from siddharthist/docs/ArgsLenAtDashEric Parisbefore adoption8b2293c
lines 504–507why, one step back504// ArgsLenAtDash will return the length of f.Args at the moment when a -- was505// found during arg parsing. This allows your program to know which args were506// before the -- and which came after. (Description from507// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).Merge pull request #160 from eparis/len-at-dashEric Parisbefore adoption53d9650
lines 508–511why, one step back508func (c *Command) ArgsLenAtDash() int {509 return c.Flags().ArgsLenAtDash()510}511fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 512why, one step back512func (c *Command) execute(a []string) (err error) {Organize the files a bit betterspf13before adoption62fb674
lines 513–514why, one step back513 if c == nil {514 return fmt.Errorf("Called Execute() on a nil Command")Merge pull request #90 from eparis/deprecated-subcommandsEric Parisbefore adoption9cf0f37
lines 515–518why, one step back515 }516517 if len(c.Deprecated) > 0 {518 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)Organize the files a bit betterspf13before adoption62fb674
lines 519–520why, one step back519 }520Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
lines 521–524why, one step back521 // initialize help flag as the last point possible to allow for user522 // overriding523 c.initHelpFlag()524fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 525–527why, one step back525 err = c.ParseFlags(a)526 if err != nil {527 return errMerge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 528why, one step back528 }Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 529why, one step back529 // 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 530why, one step back530 // 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 531–538why, one step back531 helpVal, err := c.Flags().GetBool("help")532 if err != nil {533 // should be impossible to get here as we always declare a help534 // flag in initHelpFlag()535 c.Println("\"help\" flag declared as non-bool. Please correct your code")536 return err537 }538 if helpVal || !c.Runnable() {Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 539why, one step back539 return flag.ErrHelpOrganize the files a bit betterspf13before adoption62fb674
line 540why, one step back540 }Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
lines 541–543why, one step back541542 c.preRun()543 argWoFlags := c.Flags().Args()Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 544why, one step back544Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
line 545why, one step back545 for p := c; p != nil; p = p.Parent() {Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
line 546why, one step back546 if p.PersistentPreRunE != nil {Merge pull request #164 from vikstrous/fix_bugEric Parisbefore adoptiond732ab3
line 547why, one step back547 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 548–551why, one step back548 return err549 }550 break551 } else if p.PersistentPreRun != nil {Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
lines 552–554why, one step back552 p.PersistentPreRun(c, argWoFlags)553 break554 }Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 555why, one step back555 }Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 556–560why, one step back556 if c.PreRunE != nil {557 if err := c.PreRunE(c, argWoFlags); err != nil {558 return err559 }560 } else if c.PreRun != nil {Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 561–563why, one step back561 c.PreRun(c, argWoFlags)562 }563Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 564–575why, one step back564 if c.RunE != nil {565 if err := c.RunE(c, argWoFlags); err != nil {566 return err567 }568 } else {569 c.Run(c, argWoFlags)570 }571 if c.PostRunE != nil {572 if err := c.PostRunE(c, argWoFlags); err != nil {573 return err574 }575 } else if c.PostRun != nil {Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 576–577why, one step back576 c.PostRun(c, argWoFlags)577 }Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
line 578why, one step back578 for p := c; p != nil; p = p.Parent() {Merge pull request #134 from apriendeau/masterEric Parisbefore adoptione15d674
lines 579–584why, one step back579 if p.PersistentPostRunE != nil {580 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {581 return err582 }583 break584 } else if p.PersistentPostRun != nil {Merge pull request #102 from andronat/masterEric Parisbefore adoption7fc9f14
lines 585–587why, one step back585 p.PersistentPostRun(c, argWoFlags)586 break587 }Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 588–589why, one step back588 }589Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 590why, one step back590 return nilOrganize the files a bit betterspf13before adoption62fb674
lines 591–592why, one step back591}592Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 593why, one step back593func (c *Command) preRun() {Adding "OnInitialize()" method instead of directly setting a property. Now can have multiple initializers.spf13before adoption864687a
lines 594–596why, one step back594 for _, x := range initializers {595 x()596 }Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 597–598why, one step back597}598Support for flags before commandsspf13before adoption10a8494
lines 599–610why, one step back599func (c *Command) errorMsgFromParse() string {600 s := c.flagErrorBuf.String()601602 x := strings.Split(s, "\n")603604 if len(x) > 0 {605 return x[0]606 } else {607 return ""608 }609}610Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 611–613why, one step back611// Call execute to use the args (os.Args[1:] by default)612// and run through the command tree finding appropriate matches613// for commands and then corresponding flags.Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
lines 614–617why, one step back614func (c *Command) Execute() error {615 _, err := c.ExecuteC()616 return err617}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 618why, one step back618Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
lines 619–620why, one step back619func (c *Command) ExecuteC() (cmd *Command, err error) {620Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 621–622why, one step back621 // Regardless of what command execute is called on, run on Root only622 if c.HasParent() {Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
line 623why, one step back623 return c.Root().ExecuteC()Merge pull request #82 from bep/mousetrapEric Parisbefore adoptionf576d29
lines 624–625why, one step back624 }625Merge pull request #197 from magiconair/issue-195-mousetrap-win-onlyEric Parisbefore adoption7366561
lines 626–628why, one step back626 // windows hook627 if preExecHookFn != nil {628 preExecHookFn(c)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 629–632why, one step back629 }630631 // initialize help as the last point possible to allow for user632 // overridingMerge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 633why, one step back633 c.initHelpCmd()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 634–636why, one step back634635 var args []string636Limit the verbose test workaround to "cobra.test" onlyAnthony Fokbefore adoptione576205
lines 637–638why, one step back637 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155638 if len(c.args) == 0 && filepath.Base(os.Args[0]) != "cobra.test" {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 639–643why, one step back639 args = os.Args[1:]640 } else {641 args = c.args642 }643Merge pull request #85 from eparis/more-simplificationEric Parisbefore adoption7c7837e
line 644why, one step back644 cmd, flags, err := c.Find(args)Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
lines 645–649why, one step back645 if err != nil {646 // If found parse to a subcommand and then failed, talk about the subcommand647 if cmd != nil {648 c = cmd649 }Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e
lines 650–653why, one step back650 if !c.SilenceErrors {651 c.Println("Error:", err.Error())652 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())653 }Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
line 654why, one step back654 return c, errRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 655why, one step back655 }Merge pull request #121 from eparis/cleanupsEric Parisbefore adoption8e12710
line 656why, one step back656 err = cmd.execute(flags)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 657why, one step back657 if err != nil {always show help if requested, even if SilenceErrors is enabledSascha Holzleiterbefore adoption2bd8a73
lines 658–664why, one step back658 // Always show help if requested, even if SilenceErrors is in659 // effect660 if err == flag.ErrHelp {661 cmd.HelpFunc()(cmd, args)662 return cmd, nil663 }664Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e
lines 665–668why, one step back665 // If root command has SilentErrors flagged,666 // all subcommands should respect it667 if !cmd.SilenceErrors && !c.SilenceErrors {668 c.Println("Error:", err.Error())Merge pull request #174 from jbowes/fix-duplicate-usageEric Parisbefore adoptiona082ce4
lines 669–674why, one step back669 }670671 // If root command has SilentUsage flagged,672 // all subcommands should respect it673 if !cmd.SilenceUsage && !c.SilenceUsage {674 c.Println(cmd.UsageString())Merge pull request #169 from apriendeau/silence-errorsEric Parisbefore adoption230787e
line 675why, one step back675 }Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
line 676why, one step back676 return cmd, errRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 677why, one step back677 }Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06
line 678why, one step back678 return cmd, nilRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 679–680why, one step back679}680Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 681why, one step back681func (c *Command) initHelpFlag() {Merge pull request #133 from eparis/late-init-help-flagEric Parisbefore adoption4c4f2d9
line 682why, one step back682 if c.Flags().Lookup("help") == nil {Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
line 683why, one step back683 c.Flags().BoolP("help", "h", false, "help for "+c.Name())Merge pull request #133 from eparis/late-init-help-flagEric Parisbefore adoption4c4f2d9
line 684why, one step back684 }Merge pull request #136 from eparis/late-init-help-flag-fixEric Parisbefore adoptionf7b419f
lines 685–687why, one step back685}686687func (c *Command) initHelpCmd() {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 688why, one step back688 if c.helpCommand == nil {Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
lines 689–692why, one step back689 if !c.HasSubCommands() {690 return691 }692Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 693–697why, one step back693 c.helpCommand = &Command{694 Use: "help [command]",695 Short: "Help about any command",696 Long: `Help provides help for any command in the application.697 Simply type ` + c.Name() + ` help [path to command] for full details.`,Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
lines 698–699why, one step back698 PersistentPreRun: func(cmd *Command, args []string) {},699 PersistentPostRun: func(cmd *Command, args []string) {},Merge pull request #138 from eparis/cleanup-helpfuncEric Parisbefore adoption16b4170
lines 700–710why, one step back700701 Run: func(c *Command, args []string) {702 cmd, _, e := c.Root().Find(args)703 if cmd == nil || e != nil {704 c.Printf("Unknown help topic %#q.", args)705 c.Root().Usage()706 } else {707 helpFunc := cmd.HelpFunc()708 helpFunc(cmd, args)709 }710 },Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 711–715why, one step back711 }712 }713 c.AddCommand(c.helpCommand)714}715Organize the files a bit betterspf13before adoption62fb674
lines 716–718why, one step back716// Used for testing717func (c *Command) ResetCommands() {718 c.commands = nilMerge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 719why, one step back719 c.helpCommand = nilOrganize the files a bit betterspf13before adoption62fb674
lines 720–721why, one step back720}721Code commentaryAhsanul Haquebefore adoptione1e66f7
line 722why, one step back722//Commands returns a slice of child commands.Organize the files a bit betterspf13before adoption62fb674
lines 723–726why, one step back723func (c *Command) Commands() []*Command {724 return c.commands725}726Code commentaryAhsanul Haquebefore adoptione1e66f7
line 727why, one step back727// AddCommand adds one or more commands to this parent command.Organize the files a bit betterspf13before adoption62fb674
lines 728–733why, one step back728func (c *Command) AddCommand(cmds ...*Command) {729 for i, x := range cmds {730 if cmds[i] == c {731 panic("Command can't be a child of itself")732 }733 cmds[i].parent = cMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 734–741why, one step back734 // update max lengths735 usageLen := len(x.Use)736 if usageLen > c.commandsMaxUseLen {737 c.commandsMaxUseLen = usageLen738 }739 commandPathLen := len(x.CommandPath())740 if commandPathLen > c.commandsMaxCommandPathLen {741 c.commandsMaxCommandPathLen = commandPathLenhelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 742–745why, one step back742 }743 nameLen := len(x.Name())744 if nameLen > c.commandsMaxNameLen {745 c.commandsMaxNameLen = nameLenMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
line 746why, one step back746 }Merge pull request #211 from NanXiao/patch-1Eric Parisbefore adoptionea3bf16
line 747why, one step back747 // If global normalization function exists, update all childrenAdd Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 748–750why, one step back748 if c.globNormFunc != nil {749 x.SetGlobalNormalizationFunc(c.globNormFunc)750 }Organize the files a bit betterspf13before adoption62fb674
lines 751–754why, one step back751 c.commands = append(c.commands, x)752 }753}754Add Command's RemoveCommand methodÉtienne Vallette d'Osiabefore adoptionf479c92
lines 755–788why, one step back755// AddCommand removes one or more commands from a parent command.756func (c *Command) RemoveCommand(cmds ...*Command) {757 commands := []*Command{}758main:759 for _, command := range c.commands {760 for _, cmd := range cmds {761 if command == cmd {762 command.parent = nil763 continue main764 }765 }766 commands = append(commands, command)767 }768 c.commands = commands769 // recompute all lengths770 c.commandsMaxUseLen = 0771 c.commandsMaxCommandPathLen = 0772 c.commandsMaxNameLen = 0773 for _, command := range c.commands {774 usageLen := len(command.Use)775 if usageLen > c.commandsMaxUseLen {776 c.commandsMaxUseLen = usageLen777 }778 commandPathLen := len(command.CommandPath())779 if commandPathLen > c.commandsMaxCommandPathLen {780 c.commandsMaxCommandPathLen = commandPathLen781 }782 nameLen := len(command.Name())783 if nameLen > c.commandsMaxNameLen {784 c.commandsMaxNameLen = nameLen785 }786 }787}788Organize the files a bit betterspf13before adoption62fb674
lines 789–790why, one step back789// Convenience method to Print to the defined output790func (c *Command) Print(i ...interface{}) {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 791why, one step back791 fmt.Fprint(c.Out(), i...)Organize the files a bit betterspf13before adoption62fb674
lines 792–807why, one step back792}793794// Convenience method to Println to the defined output795func (c *Command) Println(i ...interface{}) {796 str := fmt.Sprintln(i...)797 c.Print(str)798}799800// Convenience method to Printf to the defined output801func (c *Command) Printf(format string, i ...interface{}) {802 str := fmt.Sprintf(format, i...)803 c.Print(str)804}805806// Output the usage for the command807// Used when a user provides invalid inputRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 808why, one step back808// Can be defined by user by overriding UsageFuncOrganize the files a bit betterspf13before adoption62fb674
line 809why, one step back809func (c *Command) Usage() error {Help improvementsspf13before adoption2d02c31
line 810why, one step back810 c.mergePersistentFlags()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 811why, one step back811 err := c.UsageFunc()(c)Help improvementsspf13before adoption2d02c31
lines 812–819why, one step back812 return err813}814815// Output the help for the command816// Used when a user calls help [command]817// by the default HelpFunc in the commander818func (c *Command) Help() error {819 c.mergePersistentFlags()Default usage output to stdoutEric Parisbefore adoption6de96b8
line 820why, one step back820 err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)Organize the files a bit betterspf13before adoption62fb674
lines 821–823why, one step back821 return err822}823fix trailing <nil> on help outputspf13before adoption3958385
line 824why, one step back824func (c *Command) UsageString() string {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 825why, one step back825 tmpOutput := c.outputfix trailing <nil> on help outputspf13before adoption3958385
line 826why, one step back826 bb := new(bytes.Buffer)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 827why, one step back827 c.SetOutput(bb)fix trailing <nil> on help outputspf13before adoption3958385
line 828why, one step back828 c.Usage()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 829why, one step back829 c.output = tmpOutputfix trailing <nil> on help outputspf13before adoption3958385
lines 830–832why, one step back830 return bb.String()831}832Code commentaryAhsanul Haquebefore adoptione1e66f7
line 833why, one step back833// CommandPath returns the full path to this command.Organize the files a bit betterspf13before adoption62fb674
lines 834–908why, one step back834func (c *Command) CommandPath() string {835 str := c.Name()836 x := c837 for x.HasParent() {838 str = x.parent.Name() + " " + str839 x = x.parent840 }841 return str842}843844//The full usage for a given command (including parents)845func (c *Command) UseLine() string {846 str := ""847 if c.HasParent() {848 str = c.parent.CommandPath() + " "849 }850 return str + c.Use851}852853// For use in determining which flags have been assigned to which commands854// and which persist855func (c *Command) DebugFlags() {856 c.Println("DebugFlags called on", c.Name())857 var debugflags func(*Command)858859 debugflags = func(x *Command) {860 if x.HasFlags() || x.HasPersistentFlags() {861 c.Println(x.Name())862 }863 if x.HasFlags() {864 x.flags.VisitAll(func(f *flag.Flag) {865 if x.HasPersistentFlags() {866 if x.persistentFlag(f.Name) == nil {867 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")868 } else {869 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")870 }871 } else {872 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")873 }874 })875 }876 if x.HasPersistentFlags() {877 x.pflags.VisitAll(func(f *flag.Flag) {878 if x.HasFlags() {879 if x.flags.Lookup(f.Name) == nil {880 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")881 }882 } else {883 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")884 }885 })886 }887 c.Println(x.flagErrorBuf)888 if x.HasSubCommands() {889 for _, y := range x.commands {890 debugflags(y)891 }892 }893 }894895 debugflags(c)896}897898// Name returns the command's name: the first word in the use line.899func (c *Command) Name() string {900 if c.name != "" {901 return c.name902 }903 name := c.Use904 i := strings.Index(name, " ")905 if i >= 0 {906 name = name[:i]907 }908 return nameReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 909–922why, one step back909}910911// Determine if a given string is an alias of the command.912func (c *Command) HasAlias(s string) bool {913 for _, a := range c.Aliases {914 if a == s {915 return true916 }917 }918 return false919}920921func (c *Command) NameAndAliases() string {922 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 923–926why, one step back923}924925func (c *Command) HasExample() bool {926 return len(c.Example) > 0Organize the files a bit betterspf13before adoption62fb674
lines 927–930why, one step back927}928929// Determine if the command is itself runnable930func (c *Command) Runnable() bool {Merge pull request #139 from alexanderguy/RunE-is-runnableBjørn Erik Pedersenbefore adoption1ba88c4
line 931why, one step back931 return c.Run != nil || c.RunE != nilOrganize the files a bit betterspf13before adoption62fb674
lines 932–936why, one step back932}933934// Determine if the command has children commands935func (c *Command) HasSubCommands() bool {936 return len(c.commands) > 0Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 937–938why, one step back937}938Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 939–941why, one step back939// IsAvailableCommand determines if a command is available as a non-help command940// (this includes all non deprecated/hidden commands)941func (c *Command) IsAvailableCommand() bool {Merge pull request #146 from eparis/is-available-reworkEric Parisbefore adoption4b86c66
lines 942–944why, one step back942 if len(c.Deprecated) != 0 || c.Hidden {943 return false944 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 945why, one step back945Merge pull request #150 from eparis/help-not-availableEric Parisbefore adoption0d9b07b
lines 946–949why, one step back946 if c.HasParent() && c.Parent().helpCommand == c {947 return false948 }949Merge pull request #146 from eparis/is-available-reworkEric Parisbefore adoption4b86c66
lines 950–954why, one step back950 if c.Runnable() || c.HasAvailableSubCommands() {951 return true952 }953954 return falseMerge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 955–959why, one step back955}956957// IsHelpCommand determines if a command is a 'help' command; a help command is958// determined by the fact that it is NOT runnable/hidden/deprecated, and has no959// sub commands that are runnable/hidden/deprecatedMerge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 960why, one step back960func (c *Command) IsHelpCommand() bool {Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 961–963why, one step back961962 // if a command is runnable, deprecated, or hidden it is not a 'help' command963 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 964–965why, one step back964 return false965 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 966–967why, one step back966967 // if any non-help sub commands are found, the command is not a 'help' commandMerge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
lines 968–971why, one step back968 for _, sub := range c.commands {969 if !sub.IsHelpCommand() {970 return false971 }Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 972why, one step back972 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 973–974why, one step back973974 // the command either has no sub commands, or no non-help sub commandsMerge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 975why, one step back975 return trueMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 976–977why, one step back976}977Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 978–980why, one step back978// HasHelpSubCommands determines if a command has any avilable 'help' sub commands979// that need to be shown in the usage/help default template under 'additional help980// topics'Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 981why, one step back981func (c *Command) HasHelpSubCommands() bool {Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 982–983why, one step back982983 // return true on the first found available 'help' sub commandMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 984why, one step back984 for _, sub := range c.commands {Merge pull request #122 from eparis/cleanupsEric Parisbefore adoption385fc87
line 985why, one step back985 if sub.IsHelpCommand() {Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 986–988why, one step back986 return true987 }988 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 989–990why, one step back989990 // the command either has no sub commands, or no available 'help' sub commandsMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 991–993why, one step back991 return false992}993Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 994–999why, one step back994// HasAvailableSubCommands determines if a command has available sub commands that995// need to be shown in the usage/help default template under 'available commands'996func (c *Command) HasAvailableSubCommands() bool {997998 // return true on the first found available (non deprecated/help/hidden)999 // sub commandMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 1000why, one step back1000 for _, sub := range c.commands {Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
line 1001why, one step back1001 if sub.IsAvailableCommand() {Merge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
lines 1002–1004why, one step back1002 return true1003 }1004 }Merge pull request #143 from sdomino/feature/hidden-commandsEric Parisbefore adoptionb625a4d
lines 1005–1007why, one step back10051006 // the command either has no sub comamnds, or no available (non deprecated/help/hidden)1007 // sub commandsMerge pull request #77 from eparis/additional-help-topicsEric Parisbefore adoptionbbc5177
line 1008why, one step back1008 return falseOrganize the files a bit betterspf13before adoption62fb674
lines 1009–1013why, one step back1009}10101011// Determine if the command is a child command1012func (c *Command) HasParent() bool {1013 return c.parent != nilAdd Global Normalization FunctionAnastasis Andronidisbefore adoptiond910a04
lines 1014–1018why, one step back1014}10151016// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists1017func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1018 return c.globNormFuncOrganize the files a bit betterspf13before adoption62fb674
lines 1019–1020why, one step back1019}1020Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 1021why, one step back1021// 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 1022–1032why, one step back1022func (c *Command) Flags() *flag.FlagSet {1023 if c.flags == nil {1024 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1025 if c.flagErrorBuf == nil {1026 c.flagErrorBuf = new(bytes.Buffer)1027 }1028 c.flags.SetOutput(c.flagErrorBuf)1029 }1030 return c.flags1031}1032Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1033–1037why, one step back1033// Get the local FlagSet specifically set in the current command1034func (c *Command) LocalFlags() *flag.FlagSet {1035 c.mergePersistentFlags()10361037 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1038–1039why, one step back1038 c.lflags.VisitAll(func(f *flag.Flag) {1039 local.AddFlag(f)Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 1040why, one step back1040 })Merge pull request #127 from eparis/show-commandline-on-parentEric Parisbefore adoptiondb05184
lines 1041–1047why, one step back1041 if !c.HasParent() {1042 flag.CommandLine.VisitAll(func(f *flag.Flag) {1043 if local.Lookup(f.Name) == nil {1044 local.AddFlag(f)1045 }1046 })1047 }Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1048–1050why, one step back1048 return local1049}1050new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 1051–1054why, one step back1051// All Flags which were inherited from parents commands1052func (c *Command) InheritedFlags() *flag.FlagSet {1053 c.mergePersistentFlags()1054Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1055–1056why, one step back1055 inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1056 local := c.LocalFlags()new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 1057why, one step back1057Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 1058why, one step back1058 var rmerge func(x *Command)new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 1059why, one step back1059Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1060–1071why, one step back1060 rmerge = func(x *Command) {1061 if x.HasPersistentFlags() {1062 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1063 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1064 inherited.AddFlag(f)1065 }1066 })1067 }1068 if x.HasParent() {1069 rmerge(x.parent)1070 }1071 }new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 1072–1076why, one step back10721073 if c.HasParent() {1074 rmerge(c.parent)1075 }1076Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 1077why, one step back1077 return inheritednew InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 1078–1079why, one step back1078}1079new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 1080–1081why, one step back1080// All Flags which were not inherited from parent commands1081func (c *Command) NonInheritedFlags() *flag.FlagSet {Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 1082why, one step back1082 return c.LocalFlags()new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 1083–1084why, one step back1083}1084Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 1085why, one step back1085// Get the Persistent FlagSet specifically set in the current commandOrganize the files a bit betterspf13before adoption62fb674
lines 1086–1106why, one step back1086func (c *Command) PersistentFlags() *flag.FlagSet {1087 if c.pflags == nil {1088 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1089 if c.flagErrorBuf == nil {1090 c.flagErrorBuf = new(bytes.Buffer)1091 }1092 c.pflags.SetOutput(c.flagErrorBuf)1093 }1094 return c.pflags1095}10961097// For use in testing1098func (c *Command) ResetFlags() {1099 c.flagErrorBuf = new(bytes.Buffer)1100 c.flagErrorBuf.Reset()1101 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1102 c.flags.SetOutput(c.flagErrorBuf)1103 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1104 c.pflags.SetOutput(c.flagErrorBuf)1105}1106Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 1107why, one step back1107// Does the command contain any flags (local plus persistent from the entire structure)Organize the files a bit betterspf13before adoption62fb674
lines 1108–1116why, one step back1108func (c *Command) HasFlags() bool {1109 return c.Flags().HasFlags()1110}11111112// Does the command contain persistent flags1113func (c *Command) HasPersistentFlags() bool {1114 return c.PersistentFlags().HasFlags()1115}1116Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1117–1121why, one step back1117// Does the command has flags specifically declared locally1118func (c *Command) HasLocalFlags() bool {1119 return c.LocalFlags().HasFlags()1120}1121Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1122–1125why, one step back1122func (c *Command) HasInheritedFlags() bool {1123 return c.InheritedFlags().HasFlags()1124}1125Organize the files a bit betterspf13before adoption62fb674
lines 1126–1152why, one step back1126// Climbs up the command tree looking for matching flag1127func (c *Command) Flag(name string) (flag *flag.Flag) {1128 flag = c.Flags().Lookup(name)11291130 if flag == nil {1131 flag = c.persistentFlag(name)1132 }11331134 return1135}11361137// recursively find matching persistent flag1138func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1139 if c.HasPersistentFlags() {1140 flag = c.PersistentFlags().Lookup(name)1141 }11421143 if flag == nil && c.HasParent() {1144 flag = c.parent.persistentFlag(name)1145 }1146 return1147}11481149// Parses persistent flag tree & local flags1150func (c *Command) ParseFlags(args []string) (err error) {1151 c.mergePersistentFlags()1152 err = c.Flags().Parse(args)Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e
line 1153why, one step back1153 returnOrganize the files a bit betterspf13before adoption62fb674
lines 1154–1155why, one step back1154}1155Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 1156–1159why, one step back1156func (c *Command) Parent() *Command {1157 return c.parent1158}1159Organize the files a bit betterspf13before adoption62fb674
lines 1160–1162why, one step back1160func (c *Command) mergePersistentFlags() {1161 var rmerge func(x *Command)1162Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 1163–1175why, one step back1163 // Save the set of local flags1164 if c.lflags == nil {1165 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1166 if c.flagErrorBuf == nil {1167 c.flagErrorBuf = new(bytes.Buffer)1168 }1169 c.lflags.SetOutput(c.flagErrorBuf)1170 addtolocal := func(f *flag.Flag) {1171 c.lflags.AddFlag(f)1172 }1173 c.Flags().VisitAll(addtolocal)1174 c.PersistentFlags().VisitAll(addtolocal)1175 }Organize the files a bit betterspf13before adoption62fb674
line 1176why, one step back1176 rmerge = func(x *Command) {Merge pull request #100 from eparis/pre-post-runEric Parisbefore adoption3ee9552
line 1177why, one step back1177 if !x.HasParent() {Merge pull request #75 from eparis/CommandLineEric Parisbefore adoption2d5fab0
lines 1178–1183why, one step back1178 flag.CommandLine.VisitAll(func(f *flag.Flag) {1179 if x.PersistentFlags().Lookup(f.Name) == nil {1180 x.PersistentFlags().AddFlag(f)1181 }1182 })1183 }Organize the files a bit betterspf13before adoption62fb674
lines 1184–1197why, one step back1184 if x.HasPersistentFlags() {1185 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1186 if c.Flags().Lookup(f.Name) == nil {1187 c.Flags().AddFlag(f)1188 }1189 })1190 }1191 if x.HasParent() {1192 rmerge(x.parent)1193 }1194 }11951196 rmerge(c)1197}