command.go
This file
Path
command.go
1,517 lines · 41.8 KiB · Go
Last changed by
Add support for ignoring parse errors (#662)Rajat Jindalbefore adoption4dab30c
History of this fileTake it
1// 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"20 "fmt"21 "io"22 "os"23 "path/filepath"24 "sort"25 "strings"2627 flag "github.com/spf13/pflag"28)2930// FParseErrWhitelist configures Flag parse errors to be ignored31type FParseErrWhitelist flag.ParseErrorsWhitelist3233// Command is just that, a command for your application.34// E.g. 'go run ...' - 'run' is the command. Cobra requires35// you to define the usage and description as part of your command36// definition to ensure usability.37type Command struct {38 // Use is the one-line usage message.39 Use string4041 // Aliases is an array of aliases that can be used instead of the first word in Use.42 Aliases []string4344 // SuggestFor is an array of command names for which this command will be suggested -45 // similar to aliases but only suggests.46 SuggestFor []string4748 // Short is the short description shown in the 'help' output.49 Short string5051 // Long is the long message shown in the 'help <this-command>' output.52 Long string5354 // Example is examples of how to use the command.55 Example string5657 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions58 ValidArgs []string5960 // Expected arguments61 Args PositionalArgs6263 // ArgAliases is List of aliases for ValidArgs.64 // These are not suggested to the user in the bash completion,65 // but accepted if entered manually.66 ArgAliases []string6768 // BashCompletionFunction is custom functions used by the bash autocompletion generator.69 BashCompletionFunction string7071 // Deprecated defines, if this command is deprecated and should print this string when used.72 Deprecated string7374 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.75 Hidden bool7677 // Annotations are key/value pairs that can be used by applications to identify or78 // group commands.79 Annotations map[string]string8081 // Version defines the version for this command. If this value is non-empty and the command does not82 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,83 // will print content of the "Version" variable.84 Version string8586 // The *Run functions are executed in the following order:87 // * PersistentPreRun()88 // * PreRun()89 // * Run()90 // * PostRun()91 // * PersistentPostRun()92 // All functions get the same args, the arguments after the command name.93 //94 // PersistentPreRun: children of this command will inherit and execute.95 PersistentPreRun func(cmd *Command, args []string)96 // PersistentPreRunE: PersistentPreRun but returns an error.97 PersistentPreRunE func(cmd *Command, args []string) error98 // PreRun: children of this command will not inherit.99 PreRun func(cmd *Command, args []string)100 // PreRunE: PreRun but returns an error.101 PreRunE func(cmd *Command, args []string) error102 // Run: Typically the actual work function. Most commands will only implement this.103 Run func(cmd *Command, args []string)104 // RunE: Run but returns an error.105 RunE func(cmd *Command, args []string) error106 // PostRun: run after the Run command.107 PostRun func(cmd *Command, args []string)108 // PostRunE: PostRun but returns an error.109 PostRunE func(cmd *Command, args []string) error110 // PersistentPostRun: children of this command will inherit and execute after PostRun.111 PersistentPostRun func(cmd *Command, args []string)112 // PersistentPostRunE: PersistentPostRun but returns an error.113 PersistentPostRunE func(cmd *Command, args []string) error114115 // SilenceErrors is an option to quiet errors down stream.116 SilenceErrors bool117118 // SilenceUsage is an option to silence usage when an error occurs.119 SilenceUsage bool120121 // DisableFlagParsing disables the flag parsing.122 // If this is true all flags will be passed to the command as arguments.123 DisableFlagParsing bool124125 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")126 // will be printed by generating docs for this command.127 DisableAutoGenTag bool128129 // DisableFlagsInUseLine will disable the addition of [flags] to the usage130 // line of a command when printing help or generating docs131 DisableFlagsInUseLine bool132133 // DisableSuggestions disables the suggestions based on Levenshtein distance134 // that go along with 'unknown command' messages.135 DisableSuggestions bool136 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.137 // Must be > 0.138 SuggestionsMinimumDistance int139140 // TraverseChildren parses flags on all parents before executing child command.141 TraverseChildren bool142143 //FParseErrWhitelist flag parse errors to be ignored144 FParseErrWhitelist FParseErrWhitelist145146 // commands is the list of commands supported by this program.147 commands []*Command148 // parent is a parent command for this command.149 parent *Command150 // Max lengths of commands' string lengths for use in padding.151 commandsMaxUseLen int152 commandsMaxCommandPathLen int153 commandsMaxNameLen int154 // commandsAreSorted defines, if command slice are sorted or not.155 commandsAreSorted bool156 // commandCalledAs is the name or alias value used to call this command.157 commandCalledAs struct {158 name string159 called bool160 }161162 // args is actual args parsed from flags.163 args []string164 // flagErrorBuf contains all error messages from pflag.165 flagErrorBuf *bytes.Buffer166 // flags is full set of flags.167 flags *flag.FlagSet168 // pflags contains persistent flags.169 pflags *flag.FlagSet170 // lflags contains local flags.171 lflags *flag.FlagSet172 // iflags contains inherited flags.173 iflags *flag.FlagSet174 // parentsPflags is all persistent flags of cmd's parents.175 parentsPflags *flag.FlagSet176 // globNormFunc is the global normalization function177 // that we can use on every pflag set and children commands178 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName179180 // output is an output writer defined by user.181 output io.Writer182 // usageFunc is usage func defined by user.183 usageFunc func(*Command) error184 // usageTemplate is usage template defined by user.185 usageTemplate string186 // flagErrorFunc is func defined by user and it's called when the parsing of187 // flags returns an error.188 flagErrorFunc func(*Command, error) error189 // helpTemplate is help template defined by user.190 helpTemplate string191 // helpFunc is help func defined by user.192 helpFunc func(*Command, []string)193 // helpCommand is command with usage 'help'. If it's not defined by user,194 // cobra uses default help command.195 helpCommand *Command196 // versionTemplate is the version template defined by user.197 versionTemplate string198}199200// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden201// particularly useful when testing.202func (c *Command) SetArgs(a []string) {203 c.args = a204}205206// SetOutput sets the destination for usage and error messages.207// If output is nil, os.Stderr is used.208func (c *Command) SetOutput(output io.Writer) {209 c.output = output210}211212// SetUsageFunc sets usage function. Usage can be defined by application.213func (c *Command) SetUsageFunc(f func(*Command) error) {214 c.usageFunc = f215}216217// SetUsageTemplate sets usage template. Can be defined by Application.218func (c *Command) SetUsageTemplate(s string) {219 c.usageTemplate = s220}221222// SetFlagErrorFunc sets a function to generate an error when flag parsing223// fails.224func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {225 c.flagErrorFunc = f226}227228// SetHelpFunc sets help function. Can be defined by Application.229func (c *Command) SetHelpFunc(f func(*Command, []string)) {230 c.helpFunc = f231}232233// SetHelpCommand sets help command.234func (c *Command) SetHelpCommand(cmd *Command) {235 c.helpCommand = cmd236}237238// SetHelpTemplate sets help template to be used. Application can use it to set custom template.239func (c *Command) SetHelpTemplate(s string) {240 c.helpTemplate = s241}242243// SetVersionTemplate sets version template to be used. Application can use it to set custom template.244func (c *Command) SetVersionTemplate(s string) {245 c.versionTemplate = s246}247248// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.249// The user should not have a cyclic dependency on commands.250func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {251 c.Flags().SetNormalizeFunc(n)252 c.PersistentFlags().SetNormalizeFunc(n)253 c.globNormFunc = n254255 for _, command := range c.commands {256 command.SetGlobalNormalizationFunc(n)257 }258}259260// OutOrStdout returns output to stdout.261func (c *Command) OutOrStdout() io.Writer {262 return c.getOut(os.Stdout)263}264265// OutOrStderr returns output to stderr266func (c *Command) OutOrStderr() io.Writer {267 return c.getOut(os.Stderr)268}269270func (c *Command) getOut(def io.Writer) io.Writer {271 if c.output != nil {272 return c.output273 }274 if c.HasParent() {275 return c.parent.getOut(def)276 }277 return def278}279280// UsageFunc returns either the function set by SetUsageFunc for this command281// or a parent, or it returns a default usage function.282func (c *Command) UsageFunc() (f func(*Command) error) {283 if c.usageFunc != nil {284 return c.usageFunc285 }286 if c.HasParent() {287 return c.Parent().UsageFunc()288 }289 return func(c *Command) error {290 c.mergePersistentFlags()291 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)292 if err != nil {293 c.Println(err)294 }295 return err296 }297}298299// Usage puts out the usage for the command.300// Used when a user provides invalid input.301// Can be defined by user by overriding UsageFunc.302func (c *Command) Usage() error {303 return c.UsageFunc()(c)304}305306// HelpFunc returns either the function set by SetHelpFunc for this command307// or a parent, or it returns a function with default help behavior.308func (c *Command) HelpFunc() func(*Command, []string) {309 if c.helpFunc != nil {310 return c.helpFunc311 }312 if c.HasParent() {313 return c.Parent().HelpFunc()314 }315 return func(c *Command, a []string) {316 c.mergePersistentFlags()317 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)318 if err != nil {319 c.Println(err)320 }321 }322}323324// Help puts out the help for the command.325// Used when a user calls help [command].326// Can be defined by user by overriding HelpFunc.327func (c *Command) Help() error {328 c.HelpFunc()(c, []string{})329 return nil330}331332// UsageString return usage string.333func (c *Command) UsageString() string {334 tmpOutput := c.output335 bb := new(bytes.Buffer)336 c.SetOutput(bb)337 c.Usage()338 c.output = tmpOutput339 return bb.String()340}341342// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this343// command or a parent, or it returns a function which returns the original344// error.345func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {346 if c.flagErrorFunc != nil {347 return c.flagErrorFunc348 }349350 if c.HasParent() {351 return c.parent.FlagErrorFunc()352 }353 return func(c *Command, err error) error {354 return err355 }356}357358var minUsagePadding = 25359360// UsagePadding return padding for the usage.361func (c *Command) UsagePadding() int {362 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {363 return minUsagePadding364 }365 return c.parent.commandsMaxUseLen366}367368var minCommandPathPadding = 11369370// CommandPathPadding return padding for the command path.371func (c *Command) CommandPathPadding() int {372 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {373 return minCommandPathPadding374 }375 return c.parent.commandsMaxCommandPathLen376}377378var minNamePadding = 11379380// NamePadding returns padding for the name.381func (c *Command) NamePadding() int {382 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {383 return minNamePadding384 }385 return c.parent.commandsMaxNameLen386}387388// UsageTemplate returns usage template for the command.389func (c *Command) UsageTemplate() string {390 if c.usageTemplate != "" {391 return c.usageTemplate392 }393394 if c.HasParent() {395 return c.parent.UsageTemplate()396 }397 return `Usage:{{if .Runnable}}398 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}399 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}400401Aliases:402 {{.NameAndAliases}}{{end}}{{if .HasExample}}403404Examples:405{{.Example}}{{end}}{{if .HasAvailableSubCommands}}406407Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}408 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}409410Flags:411{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}412413Global Flags:414{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}415416Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}417 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}418419Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}420`421}422423// HelpTemplate return help template for the command.424func (c *Command) HelpTemplate() string {425 if c.helpTemplate != "" {426 return c.helpTemplate427 }428429 if c.HasParent() {430 return c.parent.HelpTemplate()431 }432 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}433434{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`435}436437// VersionTemplate return version template for the command.438func (c *Command) VersionTemplate() string {439 if c.versionTemplate != "" {440 return c.versionTemplate441 }442443 if c.HasParent() {444 return c.parent.VersionTemplate()445 }446 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}447`448}449450func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {451 flag := fs.Lookup(name)452 if flag == nil {453 return false454 }455 return flag.NoOptDefVal != ""456}457458func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {459 if len(name) == 0 {460 return false461 }462463 flag := fs.ShorthandLookup(name[:1])464 if flag == nil {465 return false466 }467 return flag.NoOptDefVal != ""468}469470func stripFlags(args []string, c *Command) []string {471 if len(args) == 0 {472 return args473 }474 c.mergePersistentFlags()475476 commands := []string{}477 flags := c.Flags()478479Loop:480 for len(args) > 0 {481 s := args[0]482 args = args[1:]483 switch {484 case s == "--":485 // "--" terminates the flags486 break Loop487 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):488 // If '--flag arg' then489 // delete arg from args.490 fallthrough // (do the same as below)491 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):492 // If '-f arg' then493 // delete 'arg' from args or break the loop if len(args) <= 1.494 if len(args) <= 1 {495 break Loop496 } else {497 args = args[1:]498 continue499 }500 case s != "" && !strings.HasPrefix(s, "-"):501 commands = append(commands, s)502 }503 }504505 return commands506}507508// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like509// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).510func argsMinusFirstX(args []string, x string) []string {511 for i, y := range args {512 if x == y {513 ret := []string{}514 ret = append(ret, args[:i]...)515 ret = append(ret, args[i+1:]...)516 return ret517 }518 }519 return args520}521522func isFlagArg(arg string) bool {523 return ((len(arg) >= 3 && arg[1] == '-') ||524 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))525}526527// Find the target command given the args and command tree528// Meant to be run on the highest node. Only searches down.529func (c *Command) Find(args []string) (*Command, []string, error) {530 var innerfind func(*Command, []string) (*Command, []string)531532 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {533 argsWOflags := stripFlags(innerArgs, c)534 if len(argsWOflags) == 0 {535 return c, innerArgs536 }537 nextSubCmd := argsWOflags[0]538539 cmd := c.findNext(nextSubCmd)540 if cmd != nil {541 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))542 }543 return c, innerArgs544 }545546 commandFound, a := innerfind(c, args)547 if commandFound.Args == nil {548 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))549 }550 return commandFound, a, nil551}552553func (c *Command) findSuggestions(arg string) string {554 if c.DisableSuggestions {555 return ""556 }557 if c.SuggestionsMinimumDistance <= 0 {558 c.SuggestionsMinimumDistance = 2559 }560 suggestionsString := ""561 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {562 suggestionsString += "\n\nDid you mean this?\n"563 for _, s := range suggestions {564 suggestionsString += fmt.Sprintf("\t%v\n", s)565 }566 }567 return suggestionsString568}569570func (c *Command) findNext(next string) *Command {571 matches := make([]*Command, 0)572 for _, cmd := range c.commands {573 if cmd.Name() == next || cmd.HasAlias(next) {574 cmd.commandCalledAs.name = next575 return cmd576 }577 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {578 matches = append(matches, cmd)579 }580 }581582 if len(matches) == 1 {583 return matches[0]584 }585586 return nil587}588589// Traverse the command tree to find the command, and parse args for590// each parent.591func (c *Command) Traverse(args []string) (*Command, []string, error) {592 flags := []string{}593 inFlag := false594595 for i, arg := range args {596 switch {597 // A long flag with a space separated value598 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):599 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'600 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())601 flags = append(flags, arg)602 continue603 // A short flag with a space separated value604 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):605 inFlag = true606 flags = append(flags, arg)607 continue608 // The value for a flag609 case inFlag:610 inFlag = false611 flags = append(flags, arg)612 continue613 // A flag without a value, or with an `=` separated value614 case isFlagArg(arg):615 flags = append(flags, arg)616 continue617 }618619 cmd := c.findNext(arg)620 if cmd == nil {621 return c, args, nil622 }623624 if err := c.ParseFlags(flags); err != nil {625 return nil, args, err626 }627 return cmd.Traverse(args[i+1:])628 }629 return c, args, nil630}631632// SuggestionsFor provides suggestions for the typedName.633func (c *Command) SuggestionsFor(typedName string) []string {634 suggestions := []string{}635 for _, cmd := range c.commands {636 if cmd.IsAvailableCommand() {637 levenshteinDistance := ld(typedName, cmd.Name(), true)638 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance639 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))640 if suggestByLevenshtein || suggestByPrefix {641 suggestions = append(suggestions, cmd.Name())642 }643 for _, explicitSuggestion := range cmd.SuggestFor {644 if strings.EqualFold(typedName, explicitSuggestion) {645 suggestions = append(suggestions, cmd.Name())646 }647 }648 }649 }650 return suggestions651}652653// VisitParents visits all parents of the command and invokes fn on each parent.654func (c *Command) VisitParents(fn func(*Command)) {655 if c.HasParent() {656 fn(c.Parent())657 c.Parent().VisitParents(fn)658 }659}660661// Root finds root command.662func (c *Command) Root() *Command {663 if c.HasParent() {664 return c.Parent().Root()665 }666 return c667}668669// ArgsLenAtDash will return the length of c.Flags().Args at the moment670// when a -- was found during args parsing.671func (c *Command) ArgsLenAtDash() int {672 return c.Flags().ArgsLenAtDash()673}674675func (c *Command) execute(a []string) (err error) {676 if c == nil {677 return fmt.Errorf("Called Execute() on a nil Command")678 }679680 if len(c.Deprecated) > 0 {681 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)682 }683684 // initialize help and version flag at the last point possible to allow for user685 // overriding686 c.InitDefaultHelpFlag()687 c.InitDefaultVersionFlag()688689 err = c.ParseFlags(a)690 if err != nil {691 return c.FlagErrorFunc()(c, err)692 }693694 // If help is called, regardless of other flags, return we want help.695 // Also say we need help if the command isn't runnable.696 helpVal, err := c.Flags().GetBool("help")697 if err != nil {698 // should be impossible to get here as we always declare a help699 // flag in InitDefaultHelpFlag()700 c.Println("\"help\" flag declared as non-bool. Please correct your code")701 return err702 }703704 if helpVal {705 return flag.ErrHelp706 }707708 // for back-compat, only add version flag behavior if version is defined709 if c.Version != "" {710 versionVal, err := c.Flags().GetBool("version")711 if err != nil {712 c.Println("\"version\" flag declared as non-bool. Please correct your code")713 return err714 }715 if versionVal {716 err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)717 if err != nil {718 c.Println(err)719 }720 return err721 }722 }723724 if !c.Runnable() {725 return flag.ErrHelp726 }727728 c.preRun()729730 argWoFlags := c.Flags().Args()731 if c.DisableFlagParsing {732 argWoFlags = a733 }734735 if err := c.ValidateArgs(argWoFlags); err != nil {736 return err737 }738739 for p := c; p != nil; p = p.Parent() {740 if p.PersistentPreRunE != nil {741 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {742 return err743 }744 break745 } else if p.PersistentPreRun != nil {746 p.PersistentPreRun(c, argWoFlags)747 break748 }749 }750 if c.PreRunE != nil {751 if err := c.PreRunE(c, argWoFlags); err != nil {752 return err753 }754 } else if c.PreRun != nil {755 c.PreRun(c, argWoFlags)756 }757758 if err := c.validateRequiredFlags(); err != nil {759 return err760 }761 if c.RunE != nil {762 if err := c.RunE(c, argWoFlags); err != nil {763 return err764 }765 } else {766 c.Run(c, argWoFlags)767 }768 if c.PostRunE != nil {769 if err := c.PostRunE(c, argWoFlags); err != nil {770 return err771 }772 } else if c.PostRun != nil {773 c.PostRun(c, argWoFlags)774 }775 for p := c; p != nil; p = p.Parent() {776 if p.PersistentPostRunE != nil {777 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {778 return err779 }780 break781 } else if p.PersistentPostRun != nil {782 p.PersistentPostRun(c, argWoFlags)783 break784 }785 }786787 return nil788}789790func (c *Command) preRun() {791 for _, x := range initializers {792 x()793 }794}795796// Execute uses the args (os.Args[1:] by default)797// and run through the command tree finding appropriate matches798// for commands and then corresponding flags.799func (c *Command) Execute() error {800 _, err := c.ExecuteC()801 return err802}803804// ExecuteC executes the command.805func (c *Command) ExecuteC() (cmd *Command, err error) {806 // Regardless of what command execute is called on, run on Root only807 if c.HasParent() {808 return c.Root().ExecuteC()809 }810811 // windows hook812 if preExecHookFn != nil {813 preExecHookFn(c)814 }815816 // initialize help as the last point possible to allow for user817 // overriding818 c.InitDefaultHelpCmd()819820 var args []string821822 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155823 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {824 args = os.Args[1:]825 } else {826 args = c.args827 }828829 var flags []string830 if c.TraverseChildren {831 cmd, flags, err = c.Traverse(args)832 } else {833 cmd, flags, err = c.Find(args)834 }835 if err != nil {836 // If found parse to a subcommand and then failed, talk about the subcommand837 if cmd != nil {838 c = cmd839 }840 if !c.SilenceErrors {841 c.Println("Error:", err.Error())842 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())843 }844 return c, err845 }846847 cmd.commandCalledAs.called = true848 if cmd.commandCalledAs.name == "" {849 cmd.commandCalledAs.name = cmd.Name()850 }851852 err = cmd.execute(flags)853 if err != nil {854 // Always show help if requested, even if SilenceErrors is in855 // effect856 if err == flag.ErrHelp {857 cmd.HelpFunc()(cmd, args)858 return cmd, nil859 }860861 // If root command has SilentErrors flagged,862 // all subcommands should respect it863 if !cmd.SilenceErrors && !c.SilenceErrors {864 c.Println("Error:", err.Error())865 }866867 // If root command has SilentUsage flagged,868 // all subcommands should respect it869 if !cmd.SilenceUsage && !c.SilenceUsage {870 c.Println(cmd.UsageString())871 }872 }873 return cmd, err874}875876func (c *Command) ValidateArgs(args []string) error {877 if c.Args == nil {878 return nil879 }880 return c.Args(c, args)881}882883func (c *Command) validateRequiredFlags() error {884 flags := c.Flags()885 missingFlagNames := []string{}886 flags.VisitAll(func(pflag *flag.Flag) {887 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]888 if !found {889 return890 }891 if (requiredAnnotation[0] == "true") && !pflag.Changed {892 missingFlagNames = append(missingFlagNames, pflag.Name)893 }894 })895896 if len(missingFlagNames) > 0 {897 return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))898 }899 return nil900}901902// InitDefaultHelpFlag adds default help flag to c.903// It is called automatically by executing the c or by calling help and usage.904// If c already has help flag, it will do nothing.905func (c *Command) InitDefaultHelpFlag() {906 c.mergePersistentFlags()907 if c.Flags().Lookup("help") == nil {908 usage := "help for "909 if c.Name() == "" {910 usage += "this command"911 } else {912 usage += c.Name()913 }914 c.Flags().BoolP("help", "h", false, usage)915 }916}917918// InitDefaultVersionFlag adds default version flag to c.919// It is called automatically by executing the c.920// If c already has a version flag, it will do nothing.921// If c.Version is empty, it will do nothing.922func (c *Command) InitDefaultVersionFlag() {923 if c.Version == "" {924 return925 }926927 c.mergePersistentFlags()928 if c.Flags().Lookup("version") == nil {929 usage := "version for "930 if c.Name() == "" {931 usage += "this command"932 } else {933 usage += c.Name()934 }935 c.Flags().Bool("version", false, usage)936 }937}938939// InitDefaultHelpCmd adds default help command to c.940// It is called automatically by executing the c or by calling help and usage.941// If c already has help command or c has no subcommands, it will do nothing.942func (c *Command) InitDefaultHelpCmd() {943 if !c.HasSubCommands() {944 return945 }946947 if c.helpCommand == nil {948 c.helpCommand = &Command{949 Use: "help [command]",950 Short: "Help about any command",951 Long: `Help provides help for any command in the application.952Simply type ` + c.Name() + ` help [path to command] for full details.`,953954 Run: func(c *Command, args []string) {955 cmd, _, e := c.Root().Find(args)956 if cmd == nil || e != nil {957 c.Printf("Unknown help topic %#q\n", args)958 c.Root().Usage()959 } else {960 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown961 cmd.Help()962 }963 },964 }965 }966 c.RemoveCommand(c.helpCommand)967 c.AddCommand(c.helpCommand)968}969970// ResetCommands delete parent, subcommand and help command from c.971func (c *Command) ResetCommands() {972 c.parent = nil973 c.commands = nil974 c.helpCommand = nil975 c.parentsPflags = nil976}977978// Sorts commands by their names.979type commandSorterByName []*Command980981func (c commandSorterByName) Len() int { return len(c) }982func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }983func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }984985// Commands returns a sorted slice of child commands.986func (c *Command) Commands() []*Command {987 // do not sort commands if it already sorted or sorting was disabled988 if EnableCommandSorting && !c.commandsAreSorted {989 sort.Sort(commandSorterByName(c.commands))990 c.commandsAreSorted = true991 }992 return c.commands993}994995// AddCommand adds one or more commands to this parent command.996func (c *Command) AddCommand(cmds ...*Command) {997 for i, x := range cmds {998 if cmds[i] == c {999 panic("Command can't be a child of itself")1000 }1001 cmds[i].parent = c1002 // update max lengths1003 usageLen := len(x.Use)1004 if usageLen > c.commandsMaxUseLen {1005 c.commandsMaxUseLen = usageLen1006 }1007 commandPathLen := len(x.CommandPath())1008 if commandPathLen > c.commandsMaxCommandPathLen {1009 c.commandsMaxCommandPathLen = commandPathLen1010 }1011 nameLen := len(x.Name())1012 if nameLen > c.commandsMaxNameLen {1013 c.commandsMaxNameLen = nameLen1014 }1015 // If global normalization function exists, update all children1016 if c.globNormFunc != nil {1017 x.SetGlobalNormalizationFunc(c.globNormFunc)1018 }1019 c.commands = append(c.commands, x)1020 c.commandsAreSorted = false1021 }1022}10231024// RemoveCommand removes one or more commands from a parent command.1025func (c *Command) RemoveCommand(cmds ...*Command) {1026 commands := []*Command{}1027main:1028 for _, command := range c.commands {1029 for _, cmd := range cmds {1030 if command == cmd {1031 command.parent = nil1032 continue main1033 }1034 }1035 commands = append(commands, command)1036 }1037 c.commands = commands1038 // recompute all lengths1039 c.commandsMaxUseLen = 01040 c.commandsMaxCommandPathLen = 01041 c.commandsMaxNameLen = 01042 for _, command := range c.commands {1043 usageLen := len(command.Use)1044 if usageLen > c.commandsMaxUseLen {1045 c.commandsMaxUseLen = usageLen1046 }1047 commandPathLen := len(command.CommandPath())1048 if commandPathLen > c.commandsMaxCommandPathLen {1049 c.commandsMaxCommandPathLen = commandPathLen1050 }1051 nameLen := len(command.Name())1052 if nameLen > c.commandsMaxNameLen {1053 c.commandsMaxNameLen = nameLen1054 }1055 }1056}10571058// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1059func (c *Command) Print(i ...interface{}) {1060 fmt.Fprint(c.OutOrStderr(), i...)1061}10621063// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1064func (c *Command) Println(i ...interface{}) {1065 c.Print(fmt.Sprintln(i...))1066}10671068// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1069func (c *Command) Printf(format string, i ...interface{}) {1070 c.Print(fmt.Sprintf(format, i...))1071}10721073// CommandPath returns the full path to this command.1074func (c *Command) CommandPath() string {1075 if c.HasParent() {1076 return c.Parent().CommandPath() + " " + c.Name()1077 }1078 return c.Name()1079}10801081// UseLine puts out the full usage for a given command (including parents).1082func (c *Command) UseLine() string {1083 var useline string1084 if c.HasParent() {1085 useline = c.parent.CommandPath() + " " + c.Use1086 } else {1087 useline = c.Use1088 }1089 if c.DisableFlagsInUseLine {1090 return useline1091 }1092 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1093 useline += " [flags]"1094 }1095 return useline1096}10971098// DebugFlags used to determine which flags have been assigned to which commands1099// and which persist.1100func (c *Command) DebugFlags() {1101 c.Println("DebugFlags called on", c.Name())1102 var debugflags func(*Command)11031104 debugflags = func(x *Command) {1105 if x.HasFlags() || x.HasPersistentFlags() {1106 c.Println(x.Name())1107 }1108 if x.HasFlags() {1109 x.flags.VisitAll(func(f *flag.Flag) {1110 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1111 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1112 } else {1113 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1114 }1115 })1116 }1117 if x.HasPersistentFlags() {1118 x.pflags.VisitAll(func(f *flag.Flag) {1119 if x.HasFlags() {1120 if x.flags.Lookup(f.Name) == nil {1121 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1122 }1123 } else {1124 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1125 }1126 })1127 }1128 c.Println(x.flagErrorBuf)1129 if x.HasSubCommands() {1130 for _, y := range x.commands {1131 debugflags(y)1132 }1133 }1134 }11351136 debugflags(c)1137}11381139// Name returns the command's name: the first word in the use line.1140func (c *Command) Name() string {1141 name := c.Use1142 i := strings.Index(name, " ")1143 if i >= 0 {1144 name = name[:i]1145 }1146 return name1147}11481149// HasAlias determines if a given string is an alias of the command.1150func (c *Command) HasAlias(s string) bool {1151 for _, a := range c.Aliases {1152 if a == s {1153 return true1154 }1155 }1156 return false1157}11581159// CalledAs returns the command name or alias that was used to invoke1160// this command or an empty string if the command has not been called.1161func (c *Command) CalledAs() string {1162 if c.commandCalledAs.called {1163 return c.commandCalledAs.name1164 }1165 return ""1166}11671168// hasNameOrAliasPrefix returns true if the Name or any of aliases start1169// with prefix1170func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1171 if strings.HasPrefix(c.Name(), prefix) {1172 c.commandCalledAs.name = c.Name()1173 return true1174 }1175 for _, alias := range c.Aliases {1176 if strings.HasPrefix(alias, prefix) {1177 c.commandCalledAs.name = alias1178 return true1179 }1180 }1181 return false1182}11831184// NameAndAliases returns a list of the command name and all aliases1185func (c *Command) NameAndAliases() string {1186 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1187}11881189// HasExample determines if the command has example.1190func (c *Command) HasExample() bool {1191 return len(c.Example) > 01192}11931194// Runnable determines if the command is itself runnable.1195func (c *Command) Runnable() bool {1196 return c.Run != nil || c.RunE != nil1197}11981199// HasSubCommands determines if the command has children commands.1200func (c *Command) HasSubCommands() bool {1201 return len(c.commands) > 01202}12031204// IsAvailableCommand determines if a command is available as a non-help command1205// (this includes all non deprecated/hidden commands).1206func (c *Command) IsAvailableCommand() bool {1207 if len(c.Deprecated) != 0 || c.Hidden {1208 return false1209 }12101211 if c.HasParent() && c.Parent().helpCommand == c {1212 return false1213 }12141215 if c.Runnable() || c.HasAvailableSubCommands() {1216 return true1217 }12181219 return false1220}12211222// IsAdditionalHelpTopicCommand determines if a command is an additional1223// help topic command; additional help topic command is determined by the1224// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1225// are runnable/hidden/deprecated.1226// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1227func (c *Command) IsAdditionalHelpTopicCommand() bool {1228 // if a command is runnable, deprecated, or hidden it is not a 'help' command1229 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1230 return false1231 }12321233 // if any non-help sub commands are found, the command is not a 'help' command1234 for _, sub := range c.commands {1235 if !sub.IsAdditionalHelpTopicCommand() {1236 return false1237 }1238 }12391240 // the command either has no sub commands, or no non-help sub commands1241 return true1242}12431244// HasHelpSubCommands determines if a command has any available 'help' sub commands1245// that need to be shown in the usage/help default template under 'additional help1246// topics'.1247func (c *Command) HasHelpSubCommands() bool {1248 // return true on the first found available 'help' sub command1249 for _, sub := range c.commands {1250 if sub.IsAdditionalHelpTopicCommand() {1251 return true1252 }1253 }12541255 // the command either has no sub commands, or no available 'help' sub commands1256 return false1257}12581259// HasAvailableSubCommands determines if a command has available sub commands that1260// need to be shown in the usage/help default template under 'available commands'.1261func (c *Command) HasAvailableSubCommands() bool {1262 // return true on the first found available (non deprecated/help/hidden)1263 // sub command1264 for _, sub := range c.commands {1265 if sub.IsAvailableCommand() {1266 return true1267 }1268 }12691270 // the command either has no sub commands, or no available (non deprecated/help/hidden)1271 // sub commands1272 return false1273}12741275// HasParent determines if the command is a child command.1276func (c *Command) HasParent() bool {1277 return c.parent != nil1278}12791280// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.1281func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1282 return c.globNormFunc1283}12841285// Flags returns the complete FlagSet that applies1286// to this command (local and persistent declared here and by all parents).1287func (c *Command) Flags() *flag.FlagSet {1288 if c.flags == nil {1289 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1290 if c.flagErrorBuf == nil {1291 c.flagErrorBuf = new(bytes.Buffer)1292 }1293 c.flags.SetOutput(c.flagErrorBuf)1294 }12951296 return c.flags1297}12981299// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1300func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1301 persistentFlags := c.PersistentFlags()13021303 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1304 c.LocalFlags().VisitAll(func(f *flag.Flag) {1305 if persistentFlags.Lookup(f.Name) == nil {1306 out.AddFlag(f)1307 }1308 })1309 return out1310}13111312// LocalFlags returns the local FlagSet specifically set in the current command.1313func (c *Command) LocalFlags() *flag.FlagSet {1314 c.mergePersistentFlags()13151316 if c.lflags == nil {1317 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1318 if c.flagErrorBuf == nil {1319 c.flagErrorBuf = new(bytes.Buffer)1320 }1321 c.lflags.SetOutput(c.flagErrorBuf)1322 }1323 c.lflags.SortFlags = c.Flags().SortFlags1324 if c.globNormFunc != nil {1325 c.lflags.SetNormalizeFunc(c.globNormFunc)1326 }13271328 addToLocal := func(f *flag.Flag) {1329 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1330 c.lflags.AddFlag(f)1331 }1332 }1333 c.Flags().VisitAll(addToLocal)1334 c.PersistentFlags().VisitAll(addToLocal)1335 return c.lflags1336}13371338// InheritedFlags returns all flags which were inherited from parents commands.1339func (c *Command) InheritedFlags() *flag.FlagSet {1340 c.mergePersistentFlags()13411342 if c.iflags == nil {1343 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1344 if c.flagErrorBuf == nil {1345 c.flagErrorBuf = new(bytes.Buffer)1346 }1347 c.iflags.SetOutput(c.flagErrorBuf)1348 }13491350 local := c.LocalFlags()1351 if c.globNormFunc != nil {1352 c.iflags.SetNormalizeFunc(c.globNormFunc)1353 }13541355 c.parentsPflags.VisitAll(func(f *flag.Flag) {1356 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1357 c.iflags.AddFlag(f)1358 }1359 })1360 return c.iflags1361}13621363// NonInheritedFlags returns all flags which were not inherited from parent commands.1364func (c *Command) NonInheritedFlags() *flag.FlagSet {1365 return c.LocalFlags()1366}13671368// PersistentFlags returns the persistent FlagSet specifically set in the current command.1369func (c *Command) PersistentFlags() *flag.FlagSet {1370 if c.pflags == nil {1371 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1372 if c.flagErrorBuf == nil {1373 c.flagErrorBuf = new(bytes.Buffer)1374 }1375 c.pflags.SetOutput(c.flagErrorBuf)1376 }1377 return c.pflags1378}13791380// ResetFlags deletes all flags from command.1381func (c *Command) ResetFlags() {1382 c.flagErrorBuf = new(bytes.Buffer)1383 c.flagErrorBuf.Reset()1384 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1385 c.flags.SetOutput(c.flagErrorBuf)1386 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1387 c.pflags.SetOutput(c.flagErrorBuf)13881389 c.lflags = nil1390 c.iflags = nil1391 c.parentsPflags = nil1392}13931394// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1395func (c *Command) HasFlags() bool {1396 return c.Flags().HasFlags()1397}13981399// HasPersistentFlags checks if the command contains persistent flags.1400func (c *Command) HasPersistentFlags() bool {1401 return c.PersistentFlags().HasFlags()1402}14031404// HasLocalFlags checks if the command has flags specifically declared locally.1405func (c *Command) HasLocalFlags() bool {1406 return c.LocalFlags().HasFlags()1407}14081409// HasInheritedFlags checks if the command has flags inherited from its parent command.1410func (c *Command) HasInheritedFlags() bool {1411 return c.InheritedFlags().HasFlags()1412}14131414// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1415// structure) which are not hidden or deprecated.1416func (c *Command) HasAvailableFlags() bool {1417 return c.Flags().HasAvailableFlags()1418}14191420// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1421func (c *Command) HasAvailablePersistentFlags() bool {1422 return c.PersistentFlags().HasAvailableFlags()1423}14241425// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1426// or deprecated.1427func (c *Command) HasAvailableLocalFlags() bool {1428 return c.LocalFlags().HasAvailableFlags()1429}14301431// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1432// not hidden or deprecated.1433func (c *Command) HasAvailableInheritedFlags() bool {1434 return c.InheritedFlags().HasAvailableFlags()1435}14361437// Flag climbs up the command tree looking for matching flag.1438func (c *Command) Flag(name string) (flag *flag.Flag) {1439 flag = c.Flags().Lookup(name)14401441 if flag == nil {1442 flag = c.persistentFlag(name)1443 }14441445 return1446}14471448// Recursively find matching persistent flag.1449func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1450 if c.HasPersistentFlags() {1451 flag = c.PersistentFlags().Lookup(name)1452 }14531454 if flag == nil {1455 c.updateParentsPflags()1456 flag = c.parentsPflags.Lookup(name)1457 }1458 return1459}14601461// ParseFlags parses persistent flag tree and local flags.1462func (c *Command) ParseFlags(args []string) error {1463 if c.DisableFlagParsing {1464 return nil1465 }14661467 if c.flagErrorBuf == nil {1468 c.flagErrorBuf = new(bytes.Buffer)1469 }1470 beforeErrorBufLen := c.flagErrorBuf.Len()1471 c.mergePersistentFlags()14721473 //do it here after merging all flags and just before parse1474 c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)14751476 err := c.Flags().Parse(args)1477 // Print warnings if they occurred (e.g. deprecated flag messages).1478 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1479 c.Print(c.flagErrorBuf.String())1480 }14811482 return err1483}14841485// Parent returns a commands parent command.1486func (c *Command) Parent() *Command {1487 return c.parent1488}14891490// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1491// and adds missing persistent flags of all parents.1492func (c *Command) mergePersistentFlags() {1493 c.updateParentsPflags()1494 c.Flags().AddFlagSet(c.PersistentFlags())1495 c.Flags().AddFlagSet(c.parentsPflags)1496}14971498// updateParentsPflags updates c.parentsPflags by adding1499// new persistent flags of all parents.1500// If c.parentsPflags == nil, it makes new.1501func (c *Command) updateParentsPflags() {1502 if c.parentsPflags == nil {1503 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1504 c.parentsPflags.SetOutput(c.flagErrorBuf)1505 c.parentsPflags.SortFlags = false1506 }15071508 if c.globNormFunc != nil {1509 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1510 }15111512 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)15131514 c.VisitParents(func(parent *Command) {1515 c.parentsPflags.AddFlagSet(parent.PersistentFlags())1516 })1517}