command.go
This file
Path
command.go
1,634 lines · 45.1 KiB · Go
Last changed by
Rename BashCompDirectives to ShellCompDirectives (#1082)Marc Khouzambefore adoptionb84ef40
History of this fileTake it
The walk stopped after 200 commits: lines older than d7cfb13 point at it.
Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1–19why, 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.1314// 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.16package cobra1718import (19 "bytes"Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687
line 20why, one step back20 "context"Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 21–30why, one step back21 "fmt"22 "io"23 "os"24 "path/filepath"25 "sort"26 "strings"2728 flag "github.com/spf13/pflag"29)30Add support for ignoring parse errors (#662)Rajat Jindalbefore adoption4dab30c
lines 31–33why, one step back31// FParseErrWhitelist configures Flag parse errors to be ignored32type FParseErrWhitelist flag.ParseErrorsWhitelist33Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 34–59why, one step back34// Command is just that, a command for your application.35// E.g. 'go run ...' - 'run' is the command. Cobra requires36// you to define the usage and description as part of your command37// definition to ensure usability.38type Command struct {39 // Use is the one-line usage message.40 Use string4142 // Aliases is an array of aliases that can be used instead of the first word in Use.43 Aliases []string4445 // SuggestFor is an array of command names for which this command will be suggested -46 // similar to aliases but only suggests.47 SuggestFor []string4849 // Short is the short description shown in the 'help' output.50 Short string5152 // Long is the long message shown in the 'help <this-command>' output.53 Long string5455 // Example is examples of how to use the command.56 Example string5758 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions59 ValidArgs []stringAdd support for custom completions in Go (#1035)Marc Khouzambefore adoptionb80aeb1
lines 60–62why, one step back60 // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.61 // It is a dynamic version of using ValidArgs.62 // Only one of ValidArgs and ValidArgsFunction can be used for a command.Rename BashCompDirectives to ShellCompDirectives (#1082)Marc Khouzambefore adoptionb84ef40
line 63why, one step back63 ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 64why, one step back64Update documentationAlbert Nigmatzianovbefore adoption1723331
lines 65–67why, one step back65 // Expected arguments66 Args PositionalArgs67Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 68–85why, one step back68 // ArgAliases is List of aliases for ValidArgs.69 // These are not suggested to the user in the bash completion,70 // but accepted if entered manually.71 ArgAliases []string7273 // BashCompletionFunction is custom functions used by the bash autocompletion generator.74 BashCompletionFunction string7576 // Deprecated defines, if this command is deprecated and should print this string when used.77 Deprecated string7879 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.80 Hidden bool8182 // Annotations are key/value pairs that can be used by applications to identify or83 // group commands.84 Annotations map[string]string85Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
lines 86–87why, one step back86 // Version defines the version for this command. If this value is non-empty and the command does not87 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,Add short version flag -v when not otherwise set (#996)Dave Hendersonbefore adoption95f2f73
lines 88–89why, one step back88 // will print content of the "Version" variable. A shorthand "v" flag will also be added if the89 // command does not define one.Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
lines 90–91why, one step back90 Version string91Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 92–134why, one step back92 // The *Run functions are executed in the following order:93 // * PersistentPreRun()94 // * PreRun()95 // * Run()96 // * PostRun()97 // * PersistentPostRun()98 // All functions get the same args, the arguments after the command name.99 //100 // PersistentPreRun: children of this command will inherit and execute.101 PersistentPreRun func(cmd *Command, args []string)102 // PersistentPreRunE: PersistentPreRun but returns an error.103 PersistentPreRunE func(cmd *Command, args []string) error104 // PreRun: children of this command will not inherit.105 PreRun func(cmd *Command, args []string)106 // PreRunE: PreRun but returns an error.107 PreRunE func(cmd *Command, args []string) error108 // Run: Typically the actual work function. Most commands will only implement this.109 Run func(cmd *Command, args []string)110 // RunE: Run but returns an error.111 RunE func(cmd *Command, args []string) error112 // PostRun: run after the Run command.113 PostRun func(cmd *Command, args []string)114 // PostRunE: PostRun but returns an error.115 PostRunE func(cmd *Command, args []string) error116 // PersistentPostRun: children of this command will inherit and execute after PostRun.117 PersistentPostRun func(cmd *Command, args []string)118 // PersistentPostRunE: PersistentPostRun but returns an error.119 PersistentPostRunE func(cmd *Command, args []string) error120121 // SilenceErrors is an option to quiet errors down stream.122 SilenceErrors bool123124 // SilenceUsage is an option to silence usage when an error occurs.125 SilenceUsage bool126127 // DisableFlagParsing disables the flag parsing.128 // If this is true all flags will be passed to the command as arguments.129 DisableFlagParsing bool130131 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")132 // will be printed by generating docs for this command.133 DisableAutoGenTag bool134Disable flags in UseLine (#552)Daniel Nephinbefore adoption34ceca5
lines 135–138why, one step back135 // DisableFlagsInUseLine will disable the addition of [flags] to the usage136 // line of a command when printing help or generating docs137 DisableFlagsInUseLine bool138Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 139–145why, one step back139 // DisableSuggestions disables the suggestions based on Levenshtein distance140 // that go along with 'unknown command' messages.141 DisableSuggestions bool142 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.143 // Must be > 0.144 SuggestionsMinimumDistance int145Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 146–148why, one step back146 // TraverseChildren parses flags on all parents before executing child command.147 TraverseChildren bool148Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687
line 149why, one step back149 // FParseErrWhitelist flag parse errors to be ignoredAdd support for ignoring parse errors (#662)Rajat Jindalbefore adoption4dab30c
lines 150–151why, one step back150 FParseErrWhitelist FParseErrWhitelist151Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687
lines 152–153why, one step back152 ctx context.Context153Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 154–163why, one step back154 // commands is the list of commands supported by this program.155 commands []*Command156 // parent is a parent command for this command.157 parent *Command158 // Max lengths of commands' string lengths for use in padding.159 commandsMaxUseLen int160 commandsMaxCommandPathLen int161 commandsMaxNameLen int162 // commandsAreSorted defines, if command slice are sorted or not.163 commandsAreSorted boolAdd `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983
lines 164–168why, one step back164 // commandCalledAs is the name or alias value used to call this command.165 commandCalledAs struct {166 name string167 called bool168 }Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 169–201why, one step back169170 // args is actual args parsed from flags.171 args []string172 // flagErrorBuf contains all error messages from pflag.173 flagErrorBuf *bytes.Buffer174 // flags is full set of flags.175 flags *flag.FlagSet176 // pflags contains persistent flags.177 pflags *flag.FlagSet178 // lflags contains local flags.179 lflags *flag.FlagSet180 // iflags contains inherited flags.181 iflags *flag.FlagSet182 // parentsPflags is all persistent flags of cmd's parents.183 parentsPflags *flag.FlagSet184 // globNormFunc is the global normalization function185 // that we can use on every pflag set and children commands186 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName187188 // usageFunc is usage func defined by user.189 usageFunc func(*Command) error190 // usageTemplate is usage template defined by user.191 usageTemplate string192 // flagErrorFunc is func defined by user and it's called when the parsing of193 // flags returns an error.194 flagErrorFunc func(*Command, error) error195 // helpTemplate is help template defined by user.196 helpTemplate string197 // helpFunc is help func defined by user.198 helpFunc func(*Command, []string)199 // helpCommand is command with usage 'help'. If it's not defined by user,200 // cobra uses default help command.201 helpCommand *CommandAdd support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
lines 202–203why, one step back202 // versionTemplate is the version template defined by user.203 versionTemplate stringExtending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
lines 204–210why, one step back204205 // inReader is a reader defined by the user that replaces stdin206 inReader io.Reader207 // outWriter is a writer defined by the user that replaces stdout208 outWriter io.Writer209 // errWriter is a writer defined by the user that replaces stderr210 errWriter io.WriterUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 211–212why, one step back211}212Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687
lines 213–218why, one step back213// Context returns underlying command context. If command wasn't214// executed with ExecuteContext Context returns Background context.215func (c *Command) Context() context.Context {216 return c.ctx217}218Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 219–226why, one step back219// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden220// particularly useful when testing.221func (c *Command) SetArgs(a []string) {222 c.args = a223}224225// SetOutput sets the destination for usage and error messages.226// If output is nil, os.Stderr is used.Deprecate and maintain backwards compatibilityJuan Lenibefore adoptioncb27ce1
line 227why, one step back227// Deprecated: Use SetOut and/or SetErr insteadUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 228why, one step back228func (c *Command) SetOutput(output io.Writer) {Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
line 229why, one step back229 c.outWriter = outputDeprecate and maintain backwards compatibilityJuan Lenibefore adoptioncb27ce1
line 230why, one step back230 c.errWriter = outputUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 231–232why, one step back231}232Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
lines 233–235why, one step back233// SetOut sets the destination for usage messages.234// If newOut is nil, os.Stdout is used.235func (c *Command) SetOut(newOut io.Writer) {Fixed linter issuesJuan Lenibefore adoption0ea93dd
line 236why, one step back236 c.outWriter = newOutExtending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
lines 237–240why, one step back237}238239// SetErr sets the destination for error messages.240// If newErr is nil, os.Stderr is used.Fixed linter issuesJuan Lenibefore adoption0ea93dd
line 241why, one step back241func (c *Command) SetErr(newErr io.Writer) {Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
lines 242–244why, one step back242 c.errWriter = newErr243}244Correct all complaints from golintBruce Downsbefore adoption51f06c7
line 245why, one step back245// SetIn sets the source for input dataExtending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
lines 246–250why, one step back246// If newIn is nil, os.Stdin is used.247func (c *Command) SetIn(newIn io.Reader) {248 c.inReader = newIn249}250Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 251–281why, one step back251// SetUsageFunc sets usage function. Usage can be defined by application.252func (c *Command) SetUsageFunc(f func(*Command) error) {253 c.usageFunc = f254}255256// SetUsageTemplate sets usage template. Can be defined by Application.257func (c *Command) SetUsageTemplate(s string) {258 c.usageTemplate = s259}260261// SetFlagErrorFunc sets a function to generate an error when flag parsing262// fails.263func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {264 c.flagErrorFunc = f265}266267// SetHelpFunc sets help function. Can be defined by Application.268func (c *Command) SetHelpFunc(f func(*Command, []string)) {269 c.helpFunc = f270}271272// SetHelpCommand sets help command.273func (c *Command) SetHelpCommand(cmd *Command) {274 c.helpCommand = cmd275}276277// SetHelpTemplate sets help template to be used. Application can use it to set custom template.278func (c *Command) SetHelpTemplate(s string) {279 c.helpTemplate = s280}281Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
lines 282–286why, one step back282// SetVersionTemplate sets version template to be used. Application can use it to set custom template.283func (c *Command) SetVersionTemplate(s string) {284 c.versionTemplate = s285}286Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 287–308why, one step back287// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.288// The user should not have a cyclic dependency on commands.289func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {290 c.Flags().SetNormalizeFunc(n)291 c.PersistentFlags().SetNormalizeFunc(n)292 c.globNormFunc = n293294 for _, command := range c.commands {295 command.SetGlobalNormalizationFunc(n)296 }297}298299// OutOrStdout returns output to stdout.300func (c *Command) OutOrStdout() io.Writer {301 return c.getOut(os.Stdout)302}303304// OutOrStderr returns output to stderr305func (c *Command) OutOrStderr() io.Writer {306 return c.getOut(os.Stderr)307}308Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
lines 309–313why, one step back309// ErrOrStderr returns output to stderr310func (c *Command) ErrOrStderr() io.Writer {311 return c.getErr(os.Stderr)312}313Correct documentation for InOrStdin (#929)Daniel Espondabefore adoption3c26245
line 314why, one step back314// InOrStdin returns input to stdinExtending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
lines 315–318why, one step back315func (c *Command) InOrStdin() io.Reader {316 return c.getIn(os.Stdin)317}318Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 319why, one step back319func (c *Command) getOut(def io.Writer) io.Writer {Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
lines 320–321why, one step back320 if c.outWriter != nil {321 return c.outWriterUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 322–328why, one step back322 }323 if c.HasParent() {324 return c.parent.getOut(def)325 }326 return def327}328Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
lines 329–348why, one step back329func (c *Command) getErr(def io.Writer) io.Writer {330 if c.errWriter != nil {331 return c.errWriter332 }333 if c.HasParent() {334 return c.parent.getErr(def)335 }336 return def337}338339func (c *Command) getIn(def io.Reader) io.Reader {340 if c.inReader != nil {341 return c.inReader342 }343 if c.HasParent() {344 return c.parent.getIn(def)345 }346 return def347}348Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 349–385why, one step back349// UsageFunc returns either the function set by SetUsageFunc for this command350// or a parent, or it returns a default usage function.351func (c *Command) UsageFunc() (f func(*Command) error) {352 if c.usageFunc != nil {353 return c.usageFunc354 }355 if c.HasParent() {356 return c.Parent().UsageFunc()357 }358 return func(c *Command) error {359 c.mergePersistentFlags()360 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)361 if err != nil {362 c.Println(err)363 }364 return err365 }366}367368// Usage puts out the usage for the command.369// Used when a user provides invalid input.370// Can be defined by user by overriding UsageFunc.371func (c *Command) Usage() error {372 return c.UsageFunc()(c)373}374375// HelpFunc returns either the function set by SetHelpFunc for this command376// or a parent, or it returns a function with default help behavior.377func (c *Command) HelpFunc() func(*Command, []string) {378 if c.helpFunc != nil {379 return c.helpFunc380 }381 if c.HasParent() {382 return c.Parent().HelpFunc()383 }384 return func(c *Command, a []string) {385 c.mergePersistentFlags()Revert change so help is printed on stdout again (#1004)Marc Khouzambefore adoption0d9d2d4
lines 386–388why, one step back386 // The help should be sent to stdout387 // See https://github.com/spf13/cobra/issues/1002388 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 389–402why, one step back389 if err != nil {390 c.Println(err)391 }392 }393}394395// Help puts out the help for the command.396// Used when a user calls help [command].397// Can be defined by user by overriding HelpFunc.398func (c *Command) Help() error {399 c.HelpFunc()(c, []string{})400 return nil401}402considering stderr in UsageStringJuan Lenibefore adoptionb635726
line 403why, one step back403// UsageString returns usage string.Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 404why, one step back404func (c *Command) UsageString() string {considering stderr in UsageStringJuan Lenibefore adoptionb635726
line 405why, one step back405 // Storing normal writersExtending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
line 406why, one step back406 tmpOutput := c.outWriterconsidering stderr in UsageStringJuan Lenibefore adoptionb635726
lines 407–408why, one step back407 tmpErr := c.errWriter408Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 409why, one step back409 bb := new(bytes.Buffer)Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
line 410why, one step back410 c.outWriter = bbconsidering stderr in UsageStringJuan Lenibefore adoptionb635726
lines 411–412why, one step back411 c.errWriter = bb412Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 413why, one step back413 c.Usage()considering stderr in UsageStringJuan Lenibefore adoptionb635726
lines 414–415why, one step back414415 // Setting things back to normalExtending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1
line 416why, one step back416 c.outWriter = tmpOutputconsidering stderr in UsageStringJuan Lenibefore adoptionb635726
lines 417–418why, one step back417 c.errWriter = tmpErr418Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 419–516why, one step back419 return bb.String()420}421422// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this423// command or a parent, or it returns a function which returns the original424// error.425func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {426 if c.flagErrorFunc != nil {427 return c.flagErrorFunc428 }429430 if c.HasParent() {431 return c.parent.FlagErrorFunc()432 }433 return func(c *Command, err error) error {434 return err435 }436}437438var minUsagePadding = 25439440// UsagePadding return padding for the usage.441func (c *Command) UsagePadding() int {442 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {443 return minUsagePadding444 }445 return c.parent.commandsMaxUseLen446}447448var minCommandPathPadding = 11449450// CommandPathPadding return padding for the command path.451func (c *Command) CommandPathPadding() int {452 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {453 return minCommandPathPadding454 }455 return c.parent.commandsMaxCommandPathLen456}457458var minNamePadding = 11459460// NamePadding returns padding for the name.461func (c *Command) NamePadding() int {462 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {463 return minNamePadding464 }465 return c.parent.commandsMaxNameLen466}467468// UsageTemplate returns usage template for the command.469func (c *Command) UsageTemplate() string {470 if c.usageTemplate != "" {471 return c.usageTemplate472 }473474 if c.HasParent() {475 return c.parent.UsageTemplate()476 }477 return `Usage:{{if .Runnable}}478 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}479 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}480481Aliases:482 {{.NameAndAliases}}{{end}}{{if .HasExample}}483484Examples:485{{.Example}}{{end}}{{if .HasAvailableSubCommands}}486487Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}488 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}489490Flags:491{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}492493Global Flags:494{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}495496Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}497 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}498499Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}500`501}502503// HelpTemplate return help template for the command.504func (c *Command) HelpTemplate() string {505 if c.helpTemplate != "" {506 return c.helpTemplate507 }508509 if c.HasParent() {510 return c.parent.HelpTemplate()511 }512 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}513514{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`515}516Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
lines 517–529why, one step back517// VersionTemplate return version template for the command.518func (c *Command) VersionTemplate() string {519 if c.versionTemplate != "" {520 return c.versionTemplate521 }522523 if c.HasParent() {524 return c.parent.VersionTemplate()525 }526 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}527`528}529Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 530–563why, one step back530func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {531 flag := fs.Lookup(name)532 if flag == nil {533 return false534 }535 return flag.NoOptDefVal != ""536}537538func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {539 if len(name) == 0 {540 return false541 }542543 flag := fs.ShorthandLookup(name[:1])544 if flag == nil {545 return false546 }547 return flag.NoOptDefVal != ""548}549550func stripFlags(args []string, c *Command) []string {551 if len(args) == 0 {552 return args553 }554 c.mergePersistentFlags()555556 commands := []string{}557 flags := c.Flags()558559Loop:560 for len(args) > 0 {561 s := args[0]562 args = args[1:]563 switch {Terminate the stripping of flags when -- is found (#649)Di Xubefore adoptionc439c4f
lines 564–566why, one step back564 case s == "--":565 // "--" terminates the flags566 break LoopUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 567–601why, one step back567 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):568 // If '--flag arg' then569 // delete arg from args.570 fallthrough // (do the same as below)571 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):572 // If '-f arg' then573 // delete 'arg' from args or break the loop if len(args) <= 1.574 if len(args) <= 1 {575 break Loop576 } else {577 args = args[1:]578 continue579 }580 case s != "" && !strings.HasPrefix(s, "-"):581 commands = append(commands, s)582 }583 }584585 return commands586}587588// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like589// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).590func argsMinusFirstX(args []string, x string) []string {591 for i, y := range args {592 if x == y {593 ret := []string{}594 ret = append(ret, args[:i]...)595 ret = append(ret, args[i+1:]...)596 return ret597 }598 }599 return args600}601Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 602–606why, one step back602func isFlagArg(arg string) bool {603 return ((len(arg) >= 3 && arg[1] == '-') ||604 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))605}606Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 607–618why, one step back607// Find the target command given the args and command tree608// Meant to be run on the highest node. Only searches down.609func (c *Command) Find(args []string) (*Command, []string, error) {610 var innerfind func(*Command, []string) (*Command, []string)611612 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {613 argsWOflags := stripFlags(innerArgs, c)614 if len(argsWOflags) == 0 {615 return c, innerArgs616 }617 nextSubCmd := argsWOflags[0]618Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 619–621why, one step back619 cmd := c.findNext(nextSubCmd)620 if cmd != nil {621 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 622–626why, one step back622 }623 return c, innerArgs624 }625626 commandFound, a := innerfind(c, args)Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
lines 627–628why, one step back627 if commandFound.Args == nil {628 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 629–630why, one step back629 }630 return commandFound, a, nilAllow commands to explicitly state if they do, or do not take arbitrary argumentsEric Parisbefore adoptiond89c499
lines 631–632why, one step back631}632Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
line 633why, one step back633func (c *Command) findSuggestions(arg string) string {Allow commands to explicitly state if they do, or do not take arbitrary argumentsEric Parisbefore adoptiond89c499
lines 634–640why, one step back634 if c.DisableSuggestions {635 return ""636 }637 if c.SuggestionsMinimumDistance <= 0 {638 c.SuggestionsMinimumDistance = 2639 }640 suggestionsString := ""Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
line 641why, one step back641 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {Allow commands to explicitly state if they do, or do not take arbitrary argumentsEric Parisbefore adoptiond89c499
lines 642–647why, one step back642 suggestionsString += "\n\nDid you mean this?\n"643 for _, s := range suggestions {644 suggestionsString += fmt.Sprintf("\t%v\n", s)645 }646 }647 return suggestionsStringUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 648–649why, one step back648}649Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 650–653why, one step back650func (c *Command) findNext(next string) *Command {651 matches := make([]*Command, 0)652 for _, cmd := range c.commands {653 if cmd.Name() == next || cmd.HasAlias(next) {Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983
line 654why, one step back654 cmd.commandCalledAs.name = nextAdd a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 655–664why, one step back655 return cmd656 }657 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {658 matches = append(matches, cmd)659 }660 }661662 if len(matches) == 1 {663 return matches[0]664 }Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983
line 665why, one step back665Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 666–711why, one step back666 return nil667}668669// Traverse the command tree to find the command, and parse args for670// each parent.671func (c *Command) Traverse(args []string) (*Command, []string, error) {672 flags := []string{}673 inFlag := false674675 for i, arg := range args {676 switch {677 // A long flag with a space separated value678 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):679 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'680 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())681 flags = append(flags, arg)682 continue683 // A short flag with a space separated value684 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):685 inFlag = true686 flags = append(flags, arg)687 continue688 // The value for a flag689 case inFlag:690 inFlag = false691 flags = append(flags, arg)692 continue693 // A flag without a value, or with an `=` separated value694 case isFlagArg(arg):695 flags = append(flags, arg)696 continue697 }698699 cmd := c.findNext(arg)700 if cmd == nil {701 return c, args, nil702 }703704 if err := c.ParseFlags(flags); err != nil {705 return nil, args, err706 }707 return cmd.Traverse(args[i+1:])708 }709 return c, args, nil710}711Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 712–748why, one step back712// SuggestionsFor provides suggestions for the typedName.713func (c *Command) SuggestionsFor(typedName string) []string {714 suggestions := []string{}715 for _, cmd := range c.commands {716 if cmd.IsAvailableCommand() {717 levenshteinDistance := ld(typedName, cmd.Name(), true)718 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance719 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))720 if suggestByLevenshtein || suggestByPrefix {721 suggestions = append(suggestions, cmd.Name())722 }723 for _, explicitSuggestion := range cmd.SuggestFor {724 if strings.EqualFold(typedName, explicitSuggestion) {725 suggestions = append(suggestions, cmd.Name())726 }727 }728 }729 }730 return suggestions731}732733// VisitParents visits all parents of the command and invokes fn on each parent.734func (c *Command) VisitParents(fn func(*Command)) {735 if c.HasParent() {736 fn(c.Parent())737 c.Parent().VisitParents(fn)738 }739}740741// Root finds root command.742func (c *Command) Root() *Command {743 if c.HasParent() {744 return c.Parent().Root()745 }746 return c747}748Improve testsAlbert Nigmatzianovbefore adoption65c8acb
lines 749–750why, one step back749// ArgsLenAtDash will return the length of c.Flags().Args at the moment750// when a -- was found during args parsing.Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 751–763why, one step back751func (c *Command) ArgsLenAtDash() int {752 return c.Flags().ArgsLenAtDash()753}754755func (c *Command) execute(a []string) (err error) {756 if c == nil {757 return fmt.Errorf("Called Execute() on a nil Command")758 }759760 if len(c.Deprecated) > 0 {761 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)762 }763Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
line 764why, one step back764 // initialize help and version flag at the last point possible to allow for userUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 765–766why, one step back765 // overriding766 c.InitDefaultHelpFlag()Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
line 767why, one step back767 c.InitDefaultVersionFlag()Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 768–783why, one step back768769 err = c.ParseFlags(a)770 if err != nil {771 return c.FlagErrorFunc()(c, err)772 }773774 // If help is called, regardless of other flags, return we want help.775 // Also say we need help if the command isn't runnable.776 helpVal, err := c.Flags().GetBool("help")777 if err != nil {778 // should be impossible to get here as we always declare a help779 // flag in InitDefaultHelpFlag()780 c.Println("\"help\" flag declared as non-bool. Please correct your code")781 return err782 }783Ensure that '--version' flag works properly for root command (#595)Nick Miyakebefore adoptionccaecb1
line 784why, one step back784 if helpVal {Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 785–787why, one step back785 return flag.ErrHelp786 }787Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
lines 788–801why, one step back788 // for back-compat, only add version flag behavior if version is defined789 if c.Version != "" {790 versionVal, err := c.Flags().GetBool("version")791 if err != nil {792 c.Println("\"version\" flag declared as non-bool. Please correct your code")793 return err794 }795 if versionVal {796 err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)797 if err != nil {798 c.Println(err)799 }800 return err801 }Ensure that '--version' flag works properly for root command (#595)Nick Miyakebefore adoptionccaecb1
lines 802–804why, one step back802 }803804 if !c.Runnable() {Partial Revert of #922 (#1068)Joshua Harshmanbefore adoption6607e6b
line 805why, one step back805 return flag.ErrHelpAdd support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
lines 806–807why, one step back806 }807Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 808–814why, one step back808 c.preRun()809810 argWoFlags := c.Flags().Args()811 if c.DisableFlagParsing {812 argWoFlags = a813 }814Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
lines 815–818why, one step back815 if err := c.ValidateArgs(argWoFlags); err != nil {816 return err817 }818Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 819–837why, one step back819 for p := c; p != nil; p = p.Parent() {820 if p.PersistentPreRunE != nil {821 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {822 return err823 }824 break825 } else if p.PersistentPreRun != nil {826 p.PersistentPreRun(c, argWoFlags)827 break828 }829 }830 if c.PreRunE != nil {831 if err := c.PreRunE(c, argWoFlags); err != nil {832 return err833 }834 } else if c.PreRun != nil {835 c.PreRun(c, argWoFlags)836 }837enforce required flags (#502)Di Xubefore adoption4d6af28
lines 838–840why, one step back838 if err := c.validateRequiredFlags(); err != nil {839 return err840 }Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 841–875why, one step back841 if c.RunE != nil {842 if err := c.RunE(c, argWoFlags); err != nil {843 return err844 }845 } else {846 c.Run(c, argWoFlags)847 }848 if c.PostRunE != nil {849 if err := c.PostRunE(c, argWoFlags); err != nil {850 return err851 }852 } else if c.PostRun != nil {853 c.PostRun(c, argWoFlags)854 }855 for p := c; p != nil; p = p.Parent() {856 if p.PersistentPostRunE != nil {857 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {858 return err859 }860 break861 } else if p.PersistentPostRun != nil {862 p.PersistentPostRun(c, argWoFlags)863 break864 }865 }866867 return nil868}869870func (c *Command) preRun() {871 for _, x := range initializers {872 x()873 }874}875Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687
lines 876–882why, one step back876// ExecuteContext is the same as Execute(), but sets the ctx on the command.877// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle functions.878func (c *Command) ExecuteContext(ctx context.Context) error {879 c.ctx = ctx880 return c.Execute()881}882Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 883–892why, one step back883// Execute uses the args (os.Args[1:] by default)884// and run through the command tree finding appropriate matches885// for commands and then corresponding flags.886func (c *Command) Execute() error {887 _, err := c.ExecuteC()888 return err889}890891// ExecuteC executes the command.892func (c *Command) ExecuteC() (cmd *Command, err error) {Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687
lines 893–896why, one step back893 if c.ctx == nil {894 c.ctx = context.Background()895 }896Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 897–910why, one step back897 // Regardless of what command execute is called on, run on Root only898 if c.HasParent() {899 return c.Root().ExecuteC()900 }901902 // windows hook903 if preExecHookFn != nil {904 preExecHookFn(c)905 }906907 // initialize help as the last point possible to allow for user908 // overriding909 c.InitDefaultHelpCmd()910[TrivialPatches] Typos in README.md, fix and update CI, update projects list... (#840)umarcorbefore adoption5755ecf
line 911why, one step back911 args := c.argsUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 912–916why, one step back912913 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155914 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {915 args = os.Args[1:]916 }Add support for custom completions in Go (#1035)Marc Khouzambefore adoptionb80aeb1
lines 917–919why, one step back917918 // initialize the hidden command to be used for bash completion919 c.initCompleteCmd(args)Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 920why, one step back920Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 921–926why, one step back921 var flags []string922 if c.TraverseChildren {923 cmd, flags, err = c.Traverse(args)924 } else {925 cmd, flags, err = c.Find(args)926 }Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 927–937why, one step back927 if err != nil {928 // If found parse to a subcommand and then failed, talk about the subcommand929 if cmd != nil {930 c = cmd931 }932 if !c.SilenceErrors {933 c.Println("Error:", err.Error())934 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())935 }936 return c, err937 }Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
line 938why, one step back938Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983
lines 939–943why, one step back939 cmd.commandCalledAs.called = true940 if cmd.commandCalledAs.name == "" {941 cmd.commandCalledAs.name = cmd.Name()942 }943Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687
lines 944–949why, one step back944 // We have to pass global context to children command945 // if context is present on the parent command.946 if cmd.ctx == nil {947 cmd.ctx = c.ctx948 }949Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 950–971why, one step back950 err = cmd.execute(flags)951 if err != nil {952 // Always show help if requested, even if SilenceErrors is in953 // effect954 if err == flag.ErrHelp {955 cmd.HelpFunc()(cmd, args)956 return cmd, nil957 }958959 // If root command has SilentErrors flagged,960 // all subcommands should respect it961 if !cmd.SilenceErrors && !c.SilenceErrors {962 c.Println("Error:", err.Error())963 }964965 // If root command has SilentUsage flagged,966 // all subcommands should respect it967 if !cmd.SilenceUsage && !c.SilenceUsage {968 c.Println(cmd.UsageString())969 }970 }971 return cmd, errRefactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
lines 972–978why, one step back972}973974func (c *Command) ValidateArgs(args []string) error {975 if c.Args == nil {976 return nil977 }978 return c.Args(c, args)enforce required flags (#502)Di Xubefore adoption4d6af28
lines 979–994why, one step back979}980981func (c *Command) validateRequiredFlags() error {982 flags := c.Flags()983 missingFlagNames := []string{}984 flags.VisitAll(func(pflag *flag.Flag) {985 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]986 if !found {987 return988 }989 if (requiredAnnotation[0] == "true") && !pflag.Changed {990 missingFlagNames = append(missingFlagNames, pflag.Name)991 }992 })993994 if len(missingFlagNames) > 0 {Update error message for missing required flags (#580)Nick Miyakebefore adoption19e54c4
line 995why, one step back995 return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))enforce required flags (#502)Di Xubefore adoption4d6af28
lines 996–997why, one step back996 }997 return nilUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 998–1012why, one step back998}9991000// InitDefaultHelpFlag adds default help flag to c.1001// It is called automatically by executing the c or by calling help and usage.1002// If c already has help flag, it will do nothing.1003func (c *Command) InitDefaultHelpFlag() {1004 c.mergePersistentFlags()1005 if c.Flags().Lookup("help") == nil {1006 usage := "help for "1007 if c.Name() == "" {1008 usage += "this command"1009 } else {1010 usage += c.Name()1011 }1012 c.Flags().BoolP("help", "h", false, usage)Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce
lines 1013–1032why, one step back1013 }1014}10151016// InitDefaultVersionFlag adds default version flag to c.1017// It is called automatically by executing the c.1018// If c already has a version flag, it will do nothing.1019// If c.Version is empty, it will do nothing.1020func (c *Command) InitDefaultVersionFlag() {1021 if c.Version == "" {1022 return1023 }10241025 c.mergePersistentFlags()1026 if c.Flags().Lookup("version") == nil {1027 usage := "version for "1028 if c.Name() == "" {1029 usage += "this command"1030 } else {1031 usage += c.Name()1032 }Add short version flag -v when not otherwise set (#996)Dave Hendersonbefore adoption95f2f73
lines 1033–1037why, one step back1033 if c.Flags().ShorthandLookup("v") == nil {1034 c.Flags().BoolP("version", "v", false, usage)1035 } else {1036 c.Flags().Bool("version", false, usage)1037 }Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1038–1044why, one step back1038 }1039}10401041// InitDefaultHelpCmd adds default help command to c.1042// It is called automatically by executing the c or by calling help and usage.1043// If c already has help command or c has no subcommands, it will do nothing.1044func (c *Command) InitDefaultHelpCmd() {Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02
line 1045why, one step back1045 if !c.HasSubCommands() {Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1046–1048why, one step back1046 return1047 }1048Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02
lines 1049–1053why, one step back1049 if c.helpCommand == nil {1050 c.helpCommand = &Command{1051 Use: "help [command]",1052 Short: "Help about any command",1053 Long: `Help provides help for any command in the application.Delete tab in the long description of helpAlbert Nigmatzianovbefore adoptiond994347
line 1054why, one step back1054Simply type ` + c.Name() + ` help [path to command] for full details.`,Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 1055why, one step back1055Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02
lines 1056–1066why, one step back1056 Run: func(c *Command, args []string) {1057 cmd, _, e := c.Root().Find(args)1058 if cmd == nil || e != nil {1059 c.Printf("Unknown help topic %#q\n", args)1060 c.Root().Usage()1061 } else {1062 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1063 cmd.Help()1064 }1065 },1066 }Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1067–1071why, one step back1067 }1068 c.RemoveCommand(c.helpCommand)1069 c.AddCommand(c.helpCommand)1070}1071Edit ResetFlags and ResetCommands descriptionsAlbert Nigmatzianovbefore adoptiond6a4305
line 1072why, one step back1072// ResetCommands delete parent, subcommand and help command from c.Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 1073why, one step back1073func (c *Command) ResetCommands() {Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
line 1074why, one step back1074 c.parent = nilUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1075–1174why, one step back1075 c.commands = nil1076 c.helpCommand = nil1077 c.parentsPflags = nil1078}10791080// Sorts commands by their names.1081type commandSorterByName []*Command10821083func (c commandSorterByName) Len() int { return len(c) }1084func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }1085func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }10861087// Commands returns a sorted slice of child commands.1088func (c *Command) Commands() []*Command {1089 // do not sort commands if it already sorted or sorting was disabled1090 if EnableCommandSorting && !c.commandsAreSorted {1091 sort.Sort(commandSorterByName(c.commands))1092 c.commandsAreSorted = true1093 }1094 return c.commands1095}10961097// AddCommand adds one or more commands to this parent command.1098func (c *Command) AddCommand(cmds ...*Command) {1099 for i, x := range cmds {1100 if cmds[i] == c {1101 panic("Command can't be a child of itself")1102 }1103 cmds[i].parent = c1104 // update max lengths1105 usageLen := len(x.Use)1106 if usageLen > c.commandsMaxUseLen {1107 c.commandsMaxUseLen = usageLen1108 }1109 commandPathLen := len(x.CommandPath())1110 if commandPathLen > c.commandsMaxCommandPathLen {1111 c.commandsMaxCommandPathLen = commandPathLen1112 }1113 nameLen := len(x.Name())1114 if nameLen > c.commandsMaxNameLen {1115 c.commandsMaxNameLen = nameLen1116 }1117 // If global normalization function exists, update all children1118 if c.globNormFunc != nil {1119 x.SetGlobalNormalizationFunc(c.globNormFunc)1120 }1121 c.commands = append(c.commands, x)1122 c.commandsAreSorted = false1123 }1124}11251126// RemoveCommand removes one or more commands from a parent command.1127func (c *Command) RemoveCommand(cmds ...*Command) {1128 commands := []*Command{}1129main:1130 for _, command := range c.commands {1131 for _, cmd := range cmds {1132 if command == cmd {1133 command.parent = nil1134 continue main1135 }1136 }1137 commands = append(commands, command)1138 }1139 c.commands = commands1140 // recompute all lengths1141 c.commandsMaxUseLen = 01142 c.commandsMaxCommandPathLen = 01143 c.commandsMaxNameLen = 01144 for _, command := range c.commands {1145 usageLen := len(command.Use)1146 if usageLen > c.commandsMaxUseLen {1147 c.commandsMaxUseLen = usageLen1148 }1149 commandPathLen := len(command.CommandPath())1150 if commandPathLen > c.commandsMaxCommandPathLen {1151 c.commandsMaxCommandPathLen = commandPathLen1152 }1153 nameLen := len(command.Name())1154 if nameLen > c.commandsMaxNameLen {1155 c.commandsMaxNameLen = nameLen1156 }1157 }1158}11591160// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1161func (c *Command) Print(i ...interface{}) {1162 fmt.Fprint(c.OutOrStderr(), i...)1163}11641165// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1166func (c *Command) Println(i ...interface{}) {1167 c.Print(fmt.Sprintln(i...))1168}11691170// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1171func (c *Command) Printf(format string, i ...interface{}) {1172 c.Print(fmt.Sprintf(format, i...))1173}1174Allow for explicit output to err/stderrJuan Lenibefore adoption618bc00
lines 1175–1189why, one step back1175// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.1176func (c *Command) PrintErr(i ...interface{}) {1177 fmt.Fprint(c.ErrOrStderr(), i...)1178}11791180// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.1181func (c *Command) PrintErrln(i ...interface{}) {1182 c.Print(fmt.Sprintln(i...))1183}11841185// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.1186func (c *Command) PrintErrf(format string, i ...interface{}) {1187 c.Print(fmt.Sprintf(format, i...))1188}1189Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1190–1204why, one step back1190// CommandPath returns the full path to this command.1191func (c *Command) CommandPath() string {1192 if c.HasParent() {1193 return c.Parent().CommandPath() + " " + c.Name()1194 }1195 return c.Name()1196}11971198// UseLine puts out the full usage for a given command (including parents).1199func (c *Command) UseLine() string {1200 var useline string1201 if c.HasParent() {1202 useline = c.parent.CommandPath() + " " + c.Use1203 } else {1204 useline = c.UseDisable flags in UseLine (#552)Daniel Nephinbefore adoption34ceca5
lines 1205–1207why, one step back1205 }1206 if c.DisableFlagsInUseLine {1207 return uselineUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1208–1257why, one step back1208 }1209 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1210 useline += " [flags]"1211 }1212 return useline1213}12141215// DebugFlags used to determine which flags have been assigned to which commands1216// and which persist.1217func (c *Command) DebugFlags() {1218 c.Println("DebugFlags called on", c.Name())1219 var debugflags func(*Command)12201221 debugflags = func(x *Command) {1222 if x.HasFlags() || x.HasPersistentFlags() {1223 c.Println(x.Name())1224 }1225 if x.HasFlags() {1226 x.flags.VisitAll(func(f *flag.Flag) {1227 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1228 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1229 } else {1230 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1231 }1232 })1233 }1234 if x.HasPersistentFlags() {1235 x.pflags.VisitAll(func(f *flag.Flag) {1236 if x.HasFlags() {1237 if x.flags.Lookup(f.Name) == nil {1238 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1239 }1240 } else {1241 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1242 }1243 })1244 }1245 c.Println(x.flagErrorBuf)1246 if x.HasSubCommands() {1247 for _, y := range x.commands {1248 debugflags(y)1249 }1250 }1251 }12521253 debugflags(c)1254}12551256// Name returns the command's name: the first word in the use line.1257func (c *Command) Name() string {Delete name field from Command (#547)Albert Nigmatzianovbefore adoption40f1880
lines 1258–1261why, one step back1258 name := c.Use1259 i := strings.Index(name, " ")1260 if i >= 0 {1261 name = name[:i]Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 1262why, one step back1262 }Delete name field from Command (#547)Albert Nigmatzianovbefore adoption40f1880
line 1263why, one step back1263 return nameUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1264–1275why, one step back1264}12651266// HasAlias determines if a given string is an alias of the command.1267func (c *Command) HasAlias(s string) bool {1268 for _, a := range c.Aliases {1269 if a == s {1270 return true1271 }1272 }1273 return false1274}1275Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983
lines 1276–1284why, one step back1276// CalledAs returns the command name or alias that was used to invoke1277// this command or an empty string if the command has not been called.1278func (c *Command) CalledAs() string {1279 if c.commandCalledAs.called {1280 return c.commandCalledAs.name1281 }1282 return ""1283}1284Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 1285–1288why, one step back1285// hasNameOrAliasPrefix returns true if the Name or any of aliases start1286// with prefix1287func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1288 if strings.HasPrefix(c.Name(), prefix) {Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983
line 1289why, one step back1289 c.commandCalledAs.name = c.Name()Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 1290–1293why, one step back1290 return true1291 }1292 for _, alias := range c.Aliases {1293 if strings.HasPrefix(alias, prefix) {Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983
line 1294why, one step back1294 c.commandCalledAs.name = aliasAdd a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 1295–1301why, one step back1295 return true1296 }1297 }1298 return false1299}13001301// NameAndAliases returns a list of the command name and all aliasesUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1302–1386why, one step back1302func (c *Command) NameAndAliases() string {1303 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1304}13051306// HasExample determines if the command has example.1307func (c *Command) HasExample() bool {1308 return len(c.Example) > 01309}13101311// Runnable determines if the command is itself runnable.1312func (c *Command) Runnable() bool {1313 return c.Run != nil || c.RunE != nil1314}13151316// HasSubCommands determines if the command has children commands.1317func (c *Command) HasSubCommands() bool {1318 return len(c.commands) > 01319}13201321// IsAvailableCommand determines if a command is available as a non-help command1322// (this includes all non deprecated/hidden commands).1323func (c *Command) IsAvailableCommand() bool {1324 if len(c.Deprecated) != 0 || c.Hidden {1325 return false1326 }13271328 if c.HasParent() && c.Parent().helpCommand == c {1329 return false1330 }13311332 if c.Runnable() || c.HasAvailableSubCommands() {1333 return true1334 }13351336 return false1337}13381339// IsAdditionalHelpTopicCommand determines if a command is an additional1340// help topic command; additional help topic command is determined by the1341// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1342// are runnable/hidden/deprecated.1343// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1344func (c *Command) IsAdditionalHelpTopicCommand() bool {1345 // if a command is runnable, deprecated, or hidden it is not a 'help' command1346 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1347 return false1348 }13491350 // if any non-help sub commands are found, the command is not a 'help' command1351 for _, sub := range c.commands {1352 if !sub.IsAdditionalHelpTopicCommand() {1353 return false1354 }1355 }13561357 // the command either has no sub commands, or no non-help sub commands1358 return true1359}13601361// HasHelpSubCommands determines if a command has any available 'help' sub commands1362// that need to be shown in the usage/help default template under 'additional help1363// topics'.1364func (c *Command) HasHelpSubCommands() bool {1365 // return true on the first found available 'help' sub command1366 for _, sub := range c.commands {1367 if sub.IsAdditionalHelpTopicCommand() {1368 return true1369 }1370 }13711372 // the command either has no sub commands, or no available 'help' sub commands1373 return false1374}13751376// HasAvailableSubCommands determines if a command has available sub commands that1377// need to be shown in the usage/help default template under 'available commands'.1378func (c *Command) HasAvailableSubCommands() bool {1379 // return true on the first found available (non deprecated/help/hidden)1380 // sub command1381 for _, sub := range c.commands {1382 if sub.IsAvailableCommand() {1383 return true1384 }1385 }1386Fix typo (#573)Pavol Loffaybefore adoptionf634327
line 1387why, one step back1387 // the command either has no sub commands, or no available (non deprecated/help/hidden)Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1388–1396why, one step back1388 // sub commands1389 return false1390}13911392// HasParent determines if the command is a child command.1393func (c *Command) HasParent() bool {1394 return c.parent != nil1395}1396fix grammatical error in command.go (#626)Shamus Taylorbefore adoption3a7eb14
line 1397why, one step back1397// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1398–1440why, one step back1398func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1399 return c.globNormFunc1400}14011402// Flags returns the complete FlagSet that applies1403// to this command (local and persistent declared here and by all parents).1404func (c *Command) Flags() *flag.FlagSet {1405 if c.flags == nil {1406 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1407 if c.flagErrorBuf == nil {1408 c.flagErrorBuf = new(bytes.Buffer)1409 }1410 c.flags.SetOutput(c.flagErrorBuf)1411 }14121413 return c.flags1414}14151416// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1417func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1418 persistentFlags := c.PersistentFlags()14191420 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1421 c.LocalFlags().VisitAll(func(f *flag.Flag) {1422 if persistentFlags.Lookup(f.Name) == nil {1423 out.AddFlag(f)1424 }1425 })1426 return out1427}14281429// LocalFlags returns the local FlagSet specifically set in the current command.1430func (c *Command) LocalFlags() *flag.FlagSet {1431 c.mergePersistentFlags()14321433 if c.lflags == nil {1434 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1435 if c.flagErrorBuf == nil {1436 c.flagErrorBuf = new(bytes.Buffer)1437 }1438 c.lflags.SetOutput(c.flagErrorBuf)1439 }1440 c.lflags.SortFlags = c.Flags().SortFlagsImprove consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
lines 1441–1443why, one step back1441 if c.globNormFunc != nil {1442 c.lflags.SetNormalizeFunc(c.globNormFunc)1443 }Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1444–1454why, one step back14441445 addToLocal := func(f *flag.Flag) {1446 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1447 c.lflags.AddFlag(f)1448 }1449 }1450 c.Flags().VisitAll(addToLocal)1451 c.PersistentFlags().VisitAll(addToLocal)1452 return c.lflags1453}1454[TrivialPatches] Typos in README.md, fix and update CI, update projects list... (#840)umarcorbefore adoption5755ecf
line 1455why, one step back1455// InheritedFlags returns all flags which were inherited from parent commands.Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1456–1467why, one step back1456func (c *Command) InheritedFlags() *flag.FlagSet {1457 c.mergePersistentFlags()14581459 if c.iflags == nil {1460 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1461 if c.flagErrorBuf == nil {1462 c.flagErrorBuf = new(bytes.Buffer)1463 }1464 c.iflags.SetOutput(c.flagErrorBuf)1465 }14661467 local := c.LocalFlags()Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
lines 1468–1471why, one step back1468 if c.globNormFunc != nil {1469 c.iflags.SetNormalizeFunc(c.globNormFunc)1470 }1471Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1472–1496why, one step back1472 c.parentsPflags.VisitAll(func(f *flag.Flag) {1473 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1474 c.iflags.AddFlag(f)1475 }1476 })1477 return c.iflags1478}14791480// NonInheritedFlags returns all flags which were not inherited from parent commands.1481func (c *Command) NonInheritedFlags() *flag.FlagSet {1482 return c.LocalFlags()1483}14841485// PersistentFlags returns the persistent FlagSet specifically set in the current command.1486func (c *Command) PersistentFlags() *flag.FlagSet {1487 if c.pflags == nil {1488 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1489 if c.flagErrorBuf == nil {1490 c.flagErrorBuf = new(bytes.Buffer)1491 }1492 c.pflags.SetOutput(c.flagErrorBuf)1493 }1494 return c.pflags1495}1496Edit ResetFlags and ResetCommands descriptionsAlbert Nigmatzianovbefore adoptiond6a4305
line 1497why, one step back1497// ResetFlags deletes all flags from command.Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1498–1504why, one step back1498func (c *Command) ResetFlags() {1499 c.flagErrorBuf = new(bytes.Buffer)1500 c.flagErrorBuf.Reset()1501 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1502 c.flags.SetOutput(c.flagErrorBuf)1503 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1504 c.pflags.SetOutput(c.flagErrorBuf)Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
lines 1505–1508why, one step back15051506 c.lflags = nil1507 c.iflags = nil1508 c.parentsPflags = nilUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1509–1578why, one step back1509}15101511// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1512func (c *Command) HasFlags() bool {1513 return c.Flags().HasFlags()1514}15151516// HasPersistentFlags checks if the command contains persistent flags.1517func (c *Command) HasPersistentFlags() bool {1518 return c.PersistentFlags().HasFlags()1519}15201521// HasLocalFlags checks if the command has flags specifically declared locally.1522func (c *Command) HasLocalFlags() bool {1523 return c.LocalFlags().HasFlags()1524}15251526// HasInheritedFlags checks if the command has flags inherited from its parent command.1527func (c *Command) HasInheritedFlags() bool {1528 return c.InheritedFlags().HasFlags()1529}15301531// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1532// structure) which are not hidden or deprecated.1533func (c *Command) HasAvailableFlags() bool {1534 return c.Flags().HasAvailableFlags()1535}15361537// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1538func (c *Command) HasAvailablePersistentFlags() bool {1539 return c.PersistentFlags().HasAvailableFlags()1540}15411542// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1543// or deprecated.1544func (c *Command) HasAvailableLocalFlags() bool {1545 return c.LocalFlags().HasAvailableFlags()1546}15471548// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1549// not hidden or deprecated.1550func (c *Command) HasAvailableInheritedFlags() bool {1551 return c.InheritedFlags().HasAvailableFlags()1552}15531554// Flag climbs up the command tree looking for matching flag.1555func (c *Command) Flag(name string) (flag *flag.Flag) {1556 flag = c.Flags().Lookup(name)15571558 if flag == nil {1559 flag = c.persistentFlag(name)1560 }15611562 return1563}15641565// Recursively find matching persistent flag.1566func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1567 if c.HasPersistentFlags() {1568 flag = c.PersistentFlags().Lookup(name)1569 }15701571 if flag == nil {1572 c.updateParentsPflags()1573 flag = c.parentsPflags.Lookup(name)1574 }1575 return1576}15771578// ParseFlags parses persistent flag tree and local flags.Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83
line 1579why, one step back1579func (c *Command) ParseFlags(args []string) error {Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1580–1582why, one step back1580 if c.DisableFlagParsing {1581 return nil1582 }Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83
line 1583why, one step back1583Create new buffer if not present yet (#549)Thomas Cyronbefore adoption7b2c5ac
lines 1584–1586why, one step back1584 if c.flagErrorBuf == nil {1585 c.flagErrorBuf = new(bytes.Buffer)1586 }Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83
line 1587why, one step back1587 beforeErrorBufLen := c.flagErrorBuf.Len()Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
line 1588why, one step back1588 c.mergePersistentFlags()Add support for ignoring parse errors (#662)Rajat Jindalbefore adoption4dab30c
line 1589why, one step back1589Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687
line 1590why, one step back1590 // do it here after merging all flags and just before parseAdd support for ignoring parse errors (#662)Rajat Jindalbefore adoption4dab30c
lines 1591–1592why, one step back1591 c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)1592Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83
lines 1593–1599why, one step back1593 err := c.Flags().Parse(args)1594 // Print warnings if they occurred (e.g. deprecated flag messages).1595 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1596 c.Print(c.flagErrorBuf.String())1597 }15981599 return errUpdate README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1600–1622why, one step back1600}16011602// Parent returns a commands parent command.1603func (c *Command) Parent() *Command {1604 return c.parent1605}16061607// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1608// and adds missing persistent flags of all parents.1609func (c *Command) mergePersistentFlags() {1610 c.updateParentsPflags()1611 c.Flags().AddFlagSet(c.PersistentFlags())1612 c.Flags().AddFlagSet(c.parentsPflags)1613}16141615// updateParentsPflags updates c.parentsPflags by adding1616// new persistent flags of all parents.1617// If c.parentsPflags == nil, it makes new.1618func (c *Command) updateParentsPflags() {1619 if c.parentsPflags == nil {1620 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1621 c.parentsPflags.SetOutput(c.flagErrorBuf)1622 c.parentsPflags.SortFlags = falseImprove consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
lines 1623–1626why, one step back1623 }16241625 if c.globNormFunc != nil {1626 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)Update README.mdAlbert Nigmatzianovbefore adoptiond7cfb13
lines 1627–1634why, one step back1627 }16281629 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)16301631 c.VisitParents(func(parent *Command) {1632 c.parentsPflags.AddFlagSet(parent.PersistentFlags())1633 })1634}