command.go
This file
Path
command.go
1,504 lines · 41.4 KiB · Go
Last changed by
Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983
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// Command is just that, a command for your application.31// E.g. 'go run ...' - 'run' is the command. Cobra requires32// you to define the usage and description as part of your command33// definition to ensure usability.34type Command struct {35 // Use is the one-line usage message.36 Use string3738 // Aliases is an array of aliases that can be used instead of the first word in Use.39 Aliases []string4041 // SuggestFor is an array of command names for which this command will be suggested -42 // similar to aliases but only suggests.43 SuggestFor []string4445 // Short is the short description shown in the 'help' output.46 Short string4748 // Long is the long message shown in the 'help <this-command>' output.49 Long string5051 // Example is examples of how to use the command.52 Example string5354 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions55 ValidArgs []string5657 // Expected arguments58 Args PositionalArgs5960 // ArgAliases is List of aliases for ValidArgs.61 // These are not suggested to the user in the bash completion,62 // but accepted if entered manually.63 ArgAliases []string6465 // BashCompletionFunction is custom functions used by the bash autocompletion generator.66 BashCompletionFunction string6768 // Deprecated defines, if this command is deprecated and should print this string when used.69 Deprecated string7071 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.72 Hidden bool7374 // Annotations are key/value pairs that can be used by applications to identify or75 // group commands.76 Annotations map[string]string7778 // Version defines the version for this command. If this value is non-empty and the command does not79 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,80 // will print content of the "Version" variable.81 Version string8283 // The *Run functions are executed in the following order:84 // * PersistentPreRun()85 // * PreRun()86 // * Run()87 // * PostRun()88 // * PersistentPostRun()89 // All functions get the same args, the arguments after the command name.90 //91 // PersistentPreRun: children of this command will inherit and execute.92 PersistentPreRun func(cmd *Command, args []string)93 // PersistentPreRunE: PersistentPreRun but returns an error.94 PersistentPreRunE func(cmd *Command, args []string) error95 // PreRun: children of this command will not inherit.96 PreRun func(cmd *Command, args []string)97 // PreRunE: PreRun but returns an error.98 PreRunE func(cmd *Command, args []string) error99 // Run: Typically the actual work function. Most commands will only implement this.100 Run func(cmd *Command, args []string)101 // RunE: Run but returns an error.102 RunE func(cmd *Command, args []string) error103 // PostRun: run after the Run command.104 PostRun func(cmd *Command, args []string)105 // PostRunE: PostRun but returns an error.106 PostRunE func(cmd *Command, args []string) error107 // PersistentPostRun: children of this command will inherit and execute after PostRun.108 PersistentPostRun func(cmd *Command, args []string)109 // PersistentPostRunE: PersistentPostRun but returns an error.110 PersistentPostRunE func(cmd *Command, args []string) error111112 // SilenceErrors is an option to quiet errors down stream.113 SilenceErrors bool114115 // SilenceUsage is an option to silence usage when an error occurs.116 SilenceUsage bool117118 // DisableFlagParsing disables the flag parsing.119 // If this is true all flags will be passed to the command as arguments.120 DisableFlagParsing bool121122 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")123 // will be printed by generating docs for this command.124 DisableAutoGenTag bool125126 // DisableFlagsInUseLine will disable the addition of [flags] to the usage127 // line of a command when printing help or generating docs128 DisableFlagsInUseLine bool129130 // DisableSuggestions disables the suggestions based on Levenshtein distance131 // that go along with 'unknown command' messages.132 DisableSuggestions bool133 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.134 // Must be > 0.135 SuggestionsMinimumDistance int136137 // TraverseChildren parses flags on all parents before executing child command.138 TraverseChildren bool139140 // commands is the list of commands supported by this program.141 commands []*Command142 // parent is a parent command for this command.143 parent *Command144 // Max lengths of commands' string lengths for use in padding.145 commandsMaxUseLen int146 commandsMaxCommandPathLen int147 commandsMaxNameLen int148 // commandsAreSorted defines, if command slice are sorted or not.149 commandsAreSorted bool150 // commandCalledAs is the name or alias value used to call this command.151 commandCalledAs struct {152 name string153 called bool154 }155156 // args is actual args parsed from flags.157 args []string158 // flagErrorBuf contains all error messages from pflag.159 flagErrorBuf *bytes.Buffer160 // flags is full set of flags.161 flags *flag.FlagSet162 // pflags contains persistent flags.163 pflags *flag.FlagSet164 // lflags contains local flags.165 lflags *flag.FlagSet166 // iflags contains inherited flags.167 iflags *flag.FlagSet168 // parentsPflags is all persistent flags of cmd's parents.169 parentsPflags *flag.FlagSet170 // globNormFunc is the global normalization function171 // that we can use on every pflag set and children commands172 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName173174 // output is an output writer defined by user.175 output io.Writer176 // usageFunc is usage func defined by user.177 usageFunc func(*Command) error178 // usageTemplate is usage template defined by user.179 usageTemplate string180 // flagErrorFunc is func defined by user and it's called when the parsing of181 // flags returns an error.182 flagErrorFunc func(*Command, error) error183 // helpTemplate is help template defined by user.184 helpTemplate string185 // helpFunc is help func defined by user.186 helpFunc func(*Command, []string)187 // helpCommand is command with usage 'help'. If it's not defined by user,188 // cobra uses default help command.189 helpCommand *Command190 // versionTemplate is the version template defined by user.191 versionTemplate string192}193194// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden195// particularly useful when testing.196func (c *Command) SetArgs(a []string) {197 c.args = a198}199200// SetOutput sets the destination for usage and error messages.201// If output is nil, os.Stderr is used.202func (c *Command) SetOutput(output io.Writer) {203 c.output = output204}205206// SetUsageFunc sets usage function. Usage can be defined by application.207func (c *Command) SetUsageFunc(f func(*Command) error) {208 c.usageFunc = f209}210211// SetUsageTemplate sets usage template. Can be defined by Application.212func (c *Command) SetUsageTemplate(s string) {213 c.usageTemplate = s214}215216// SetFlagErrorFunc sets a function to generate an error when flag parsing217// fails.218func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {219 c.flagErrorFunc = f220}221222// SetHelpFunc sets help function. Can be defined by Application.223func (c *Command) SetHelpFunc(f func(*Command, []string)) {224 c.helpFunc = f225}226227// SetHelpCommand sets help command.228func (c *Command) SetHelpCommand(cmd *Command) {229 c.helpCommand = cmd230}231232// SetHelpTemplate sets help template to be used. Application can use it to set custom template.233func (c *Command) SetHelpTemplate(s string) {234 c.helpTemplate = s235}236237// SetVersionTemplate sets version template to be used. Application can use it to set custom template.238func (c *Command) SetVersionTemplate(s string) {239 c.versionTemplate = s240}241242// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.243// The user should not have a cyclic dependency on commands.244func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {245 c.Flags().SetNormalizeFunc(n)246 c.PersistentFlags().SetNormalizeFunc(n)247 c.globNormFunc = n248249 for _, command := range c.commands {250 command.SetGlobalNormalizationFunc(n)251 }252}253254// OutOrStdout returns output to stdout.255func (c *Command) OutOrStdout() io.Writer {256 return c.getOut(os.Stdout)257}258259// OutOrStderr returns output to stderr260func (c *Command) OutOrStderr() io.Writer {261 return c.getOut(os.Stderr)262}263264func (c *Command) getOut(def io.Writer) io.Writer {265 if c.output != nil {266 return c.output267 }268 if c.HasParent() {269 return c.parent.getOut(def)270 }271 return def272}273274// UsageFunc returns either the function set by SetUsageFunc for this command275// or a parent, or it returns a default usage function.276func (c *Command) UsageFunc() (f func(*Command) error) {277 if c.usageFunc != nil {278 return c.usageFunc279 }280 if c.HasParent() {281 return c.Parent().UsageFunc()282 }283 return func(c *Command) error {284 c.mergePersistentFlags()285 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)286 if err != nil {287 c.Println(err)288 }289 return err290 }291}292293// Usage puts out the usage for the command.294// Used when a user provides invalid input.295// Can be defined by user by overriding UsageFunc.296func (c *Command) Usage() error {297 return c.UsageFunc()(c)298}299300// HelpFunc returns either the function set by SetHelpFunc for this command301// or a parent, or it returns a function with default help behavior.302func (c *Command) HelpFunc() func(*Command, []string) {303 if c.helpFunc != nil {304 return c.helpFunc305 }306 if c.HasParent() {307 return c.Parent().HelpFunc()308 }309 return func(c *Command, a []string) {310 c.mergePersistentFlags()311 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)312 if err != nil {313 c.Println(err)314 }315 }316}317318// Help puts out the help for the command.319// Used when a user calls help [command].320// Can be defined by user by overriding HelpFunc.321func (c *Command) Help() error {322 c.HelpFunc()(c, []string{})323 return nil324}325326// UsageString return usage string.327func (c *Command) UsageString() string {328 tmpOutput := c.output329 bb := new(bytes.Buffer)330 c.SetOutput(bb)331 c.Usage()332 c.output = tmpOutput333 return bb.String()334}335336// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this337// command or a parent, or it returns a function which returns the original338// error.339func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {340 if c.flagErrorFunc != nil {341 return c.flagErrorFunc342 }343344 if c.HasParent() {345 return c.parent.FlagErrorFunc()346 }347 return func(c *Command, err error) error {348 return err349 }350}351352var minUsagePadding = 25353354// UsagePadding return padding for the usage.355func (c *Command) UsagePadding() int {356 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {357 return minUsagePadding358 }359 return c.parent.commandsMaxUseLen360}361362var minCommandPathPadding = 11363364// CommandPathPadding return padding for the command path.365func (c *Command) CommandPathPadding() int {366 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {367 return minCommandPathPadding368 }369 return c.parent.commandsMaxCommandPathLen370}371372var minNamePadding = 11373374// NamePadding returns padding for the name.375func (c *Command) NamePadding() int {376 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {377 return minNamePadding378 }379 return c.parent.commandsMaxNameLen380}381382// UsageTemplate returns usage template for the command.383func (c *Command) UsageTemplate() string {384 if c.usageTemplate != "" {385 return c.usageTemplate386 }387388 if c.HasParent() {389 return c.parent.UsageTemplate()390 }391 return `Usage:{{if .Runnable}}392 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}393 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}394395Aliases:396 {{.NameAndAliases}}{{end}}{{if .HasExample}}397398Examples:399{{.Example}}{{end}}{{if .HasAvailableSubCommands}}400401Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}402 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}403404Flags:405{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}406407Global Flags:408{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}409410Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}411 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}412413Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}414`415}416417// HelpTemplate return help template for the command.418func (c *Command) HelpTemplate() string {419 if c.helpTemplate != "" {420 return c.helpTemplate421 }422423 if c.HasParent() {424 return c.parent.HelpTemplate()425 }426 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}427428{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`429}430431// VersionTemplate return version template for the command.432func (c *Command) VersionTemplate() string {433 if c.versionTemplate != "" {434 return c.versionTemplate435 }436437 if c.HasParent() {438 return c.parent.VersionTemplate()439 }440 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}441`442}443444func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {445 flag := fs.Lookup(name)446 if flag == nil {447 return false448 }449 return flag.NoOptDefVal != ""450}451452func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {453 if len(name) == 0 {454 return false455 }456457 flag := fs.ShorthandLookup(name[:1])458 if flag == nil {459 return false460 }461 return flag.NoOptDefVal != ""462}463464func stripFlags(args []string, c *Command) []string {465 if len(args) == 0 {466 return args467 }468 c.mergePersistentFlags()469470 commands := []string{}471 flags := c.Flags()472473Loop:474 for len(args) > 0 {475 s := args[0]476 args = args[1:]477 switch {478 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):479 // If '--flag arg' then480 // delete arg from args.481 fallthrough // (do the same as below)482 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):483 // If '-f arg' then484 // delete 'arg' from args or break the loop if len(args) <= 1.485 if len(args) <= 1 {486 break Loop487 } else {488 args = args[1:]489 continue490 }491 case s != "" && !strings.HasPrefix(s, "-"):492 commands = append(commands, s)493 }494 }495496 return commands497}498499// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like500// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).501func argsMinusFirstX(args []string, x string) []string {502 for i, y := range args {503 if x == y {504 ret := []string{}505 ret = append(ret, args[:i]...)506 ret = append(ret, args[i+1:]...)507 return ret508 }509 }510 return args511}512513func isFlagArg(arg string) bool {514 return ((len(arg) >= 3 && arg[1] == '-') ||515 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))516}517518// Find the target command given the args and command tree519// Meant to be run on the highest node. Only searches down.520func (c *Command) Find(args []string) (*Command, []string, error) {521 var innerfind func(*Command, []string) (*Command, []string)522523 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {524 argsWOflags := stripFlags(innerArgs, c)525 if len(argsWOflags) == 0 {526 return c, innerArgs527 }528 nextSubCmd := argsWOflags[0]529530 cmd := c.findNext(nextSubCmd)531 if cmd != nil {532 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))533 }534 return c, innerArgs535 }536537 commandFound, a := innerfind(c, args)538 if commandFound.Args == nil {539 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))540 }541 return commandFound, a, nil542}543544func (c *Command) findSuggestions(arg string) string {545 if c.DisableSuggestions {546 return ""547 }548 if c.SuggestionsMinimumDistance <= 0 {549 c.SuggestionsMinimumDistance = 2550 }551 suggestionsString := ""552 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {553 suggestionsString += "\n\nDid you mean this?\n"554 for _, s := range suggestions {555 suggestionsString += fmt.Sprintf("\t%v\n", s)556 }557 }558 return suggestionsString559}560561func (c *Command) findNext(next string) *Command {562 matches := make([]*Command, 0)563 for _, cmd := range c.commands {564 if cmd.Name() == next || cmd.HasAlias(next) {565 cmd.commandCalledAs.name = next566 return cmd567 }568 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {569 matches = append(matches, cmd)570 }571 }572573 if len(matches) == 1 {574 return matches[0]575 }576577 return nil578}579580// Traverse the command tree to find the command, and parse args for581// each parent.582func (c *Command) Traverse(args []string) (*Command, []string, error) {583 flags := []string{}584 inFlag := false585586 for i, arg := range args {587 switch {588 // A long flag with a space separated value589 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):590 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'591 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())592 flags = append(flags, arg)593 continue594 // A short flag with a space separated value595 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):596 inFlag = true597 flags = append(flags, arg)598 continue599 // The value for a flag600 case inFlag:601 inFlag = false602 flags = append(flags, arg)603 continue604 // A flag without a value, or with an `=` separated value605 case isFlagArg(arg):606 flags = append(flags, arg)607 continue608 }609610 cmd := c.findNext(arg)611 if cmd == nil {612 return c, args, nil613 }614615 if err := c.ParseFlags(flags); err != nil {616 return nil, args, err617 }618 return cmd.Traverse(args[i+1:])619 }620 return c, args, nil621}622623// SuggestionsFor provides suggestions for the typedName.624func (c *Command) SuggestionsFor(typedName string) []string {625 suggestions := []string{}626 for _, cmd := range c.commands {627 if cmd.IsAvailableCommand() {628 levenshteinDistance := ld(typedName, cmd.Name(), true)629 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance630 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))631 if suggestByLevenshtein || suggestByPrefix {632 suggestions = append(suggestions, cmd.Name())633 }634 for _, explicitSuggestion := range cmd.SuggestFor {635 if strings.EqualFold(typedName, explicitSuggestion) {636 suggestions = append(suggestions, cmd.Name())637 }638 }639 }640 }641 return suggestions642}643644// VisitParents visits all parents of the command and invokes fn on each parent.645func (c *Command) VisitParents(fn func(*Command)) {646 if c.HasParent() {647 fn(c.Parent())648 c.Parent().VisitParents(fn)649 }650}651652// Root finds root command.653func (c *Command) Root() *Command {654 if c.HasParent() {655 return c.Parent().Root()656 }657 return c658}659660// ArgsLenAtDash will return the length of c.Flags().Args at the moment661// when a -- was found during args parsing.662func (c *Command) ArgsLenAtDash() int {663 return c.Flags().ArgsLenAtDash()664}665666func (c *Command) execute(a []string) (err error) {667 if c == nil {668 return fmt.Errorf("Called Execute() on a nil Command")669 }670671 if len(c.Deprecated) > 0 {672 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)673 }674675 // initialize help and version flag at the last point possible to allow for user676 // overriding677 c.InitDefaultHelpFlag()678 c.InitDefaultVersionFlag()679680 err = c.ParseFlags(a)681 if err != nil {682 return c.FlagErrorFunc()(c, err)683 }684685 // If help is called, regardless of other flags, return we want help.686 // Also say we need help if the command isn't runnable.687 helpVal, err := c.Flags().GetBool("help")688 if err != nil {689 // should be impossible to get here as we always declare a help690 // flag in InitDefaultHelpFlag()691 c.Println("\"help\" flag declared as non-bool. Please correct your code")692 return err693 }694695 if helpVal {696 return flag.ErrHelp697 }698699 // for back-compat, only add version flag behavior if version is defined700 if c.Version != "" {701 versionVal, err := c.Flags().GetBool("version")702 if err != nil {703 c.Println("\"version\" flag declared as non-bool. Please correct your code")704 return err705 }706 if versionVal {707 err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)708 if err != nil {709 c.Println(err)710 }711 return err712 }713 }714715 if !c.Runnable() {716 return flag.ErrHelp717 }718719 c.preRun()720721 argWoFlags := c.Flags().Args()722 if c.DisableFlagParsing {723 argWoFlags = a724 }725726 if err := c.ValidateArgs(argWoFlags); err != nil {727 return err728 }729730 for p := c; p != nil; p = p.Parent() {731 if p.PersistentPreRunE != nil {732 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {733 return err734 }735 break736 } else if p.PersistentPreRun != nil {737 p.PersistentPreRun(c, argWoFlags)738 break739 }740 }741 if c.PreRunE != nil {742 if err := c.PreRunE(c, argWoFlags); err != nil {743 return err744 }745 } else if c.PreRun != nil {746 c.PreRun(c, argWoFlags)747 }748749 if err := c.validateRequiredFlags(); err != nil {750 return err751 }752 if c.RunE != nil {753 if err := c.RunE(c, argWoFlags); err != nil {754 return err755 }756 } else {757 c.Run(c, argWoFlags)758 }759 if c.PostRunE != nil {760 if err := c.PostRunE(c, argWoFlags); err != nil {761 return err762 }763 } else if c.PostRun != nil {764 c.PostRun(c, argWoFlags)765 }766 for p := c; p != nil; p = p.Parent() {767 if p.PersistentPostRunE != nil {768 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {769 return err770 }771 break772 } else if p.PersistentPostRun != nil {773 p.PersistentPostRun(c, argWoFlags)774 break775 }776 }777778 return nil779}780781func (c *Command) preRun() {782 for _, x := range initializers {783 x()784 }785}786787// Execute uses the args (os.Args[1:] by default)788// and run through the command tree finding appropriate matches789// for commands and then corresponding flags.790func (c *Command) Execute() error {791 _, err := c.ExecuteC()792 return err793}794795// ExecuteC executes the command.796func (c *Command) ExecuteC() (cmd *Command, err error) {797 // Regardless of what command execute is called on, run on Root only798 if c.HasParent() {799 return c.Root().ExecuteC()800 }801802 // windows hook803 if preExecHookFn != nil {804 preExecHookFn(c)805 }806807 // initialize help as the last point possible to allow for user808 // overriding809 c.InitDefaultHelpCmd()810811 var args []string812813 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155814 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {815 args = os.Args[1:]816 } else {817 args = c.args818 }819820 var flags []string821 if c.TraverseChildren {822 cmd, flags, err = c.Traverse(args)823 } else {824 cmd, flags, err = c.Find(args)825 }826 if err != nil {827 // If found parse to a subcommand and then failed, talk about the subcommand828 if cmd != nil {829 c = cmd830 }831 if !c.SilenceErrors {832 c.Println("Error:", err.Error())833 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())834 }835 return c, err836 }837838 cmd.commandCalledAs.called = true839 if cmd.commandCalledAs.name == "" {840 cmd.commandCalledAs.name = cmd.Name()841 }842843 err = cmd.execute(flags)844 if err != nil {845 // Always show help if requested, even if SilenceErrors is in846 // effect847 if err == flag.ErrHelp {848 cmd.HelpFunc()(cmd, args)849 return cmd, nil850 }851852 // If root command has SilentErrors flagged,853 // all subcommands should respect it854 if !cmd.SilenceErrors && !c.SilenceErrors {855 c.Println("Error:", err.Error())856 }857858 // If root command has SilentUsage flagged,859 // all subcommands should respect it860 if !cmd.SilenceUsage && !c.SilenceUsage {861 c.Println(cmd.UsageString())862 }863 }864 return cmd, err865}866867func (c *Command) ValidateArgs(args []string) error {868 if c.Args == nil {869 return nil870 }871 return c.Args(c, args)872}873874func (c *Command) validateRequiredFlags() error {875 flags := c.Flags()876 missingFlagNames := []string{}877 flags.VisitAll(func(pflag *flag.Flag) {878 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]879 if !found {880 return881 }882 if (requiredAnnotation[0] == "true") && !pflag.Changed {883 missingFlagNames = append(missingFlagNames, pflag.Name)884 }885 })886887 if len(missingFlagNames) > 0 {888 return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))889 }890 return nil891}892893// InitDefaultHelpFlag adds default help flag to c.894// It is called automatically by executing the c or by calling help and usage.895// If c already has help flag, it will do nothing.896func (c *Command) InitDefaultHelpFlag() {897 c.mergePersistentFlags()898 if c.Flags().Lookup("help") == nil {899 usage := "help for "900 if c.Name() == "" {901 usage += "this command"902 } else {903 usage += c.Name()904 }905 c.Flags().BoolP("help", "h", false, usage)906 }907}908909// InitDefaultVersionFlag adds default version flag to c.910// It is called automatically by executing the c.911// If c already has a version flag, it will do nothing.912// If c.Version is empty, it will do nothing.913func (c *Command) InitDefaultVersionFlag() {914 if c.Version == "" {915 return916 }917918 c.mergePersistentFlags()919 if c.Flags().Lookup("version") == nil {920 usage := "version for "921 if c.Name() == "" {922 usage += "this command"923 } else {924 usage += c.Name()925 }926 c.Flags().Bool("version", false, usage)927 }928}929930// InitDefaultHelpCmd adds default help command to c.931// It is called automatically by executing the c or by calling help and usage.932// If c already has help command or c has no subcommands, it will do nothing.933func (c *Command) InitDefaultHelpCmd() {934 if !c.HasSubCommands() {935 return936 }937938 if c.helpCommand == nil {939 c.helpCommand = &Command{940 Use: "help [command]",941 Short: "Help about any command",942 Long: `Help provides help for any command in the application.943Simply type ` + c.Name() + ` help [path to command] for full details.`,944945 Run: func(c *Command, args []string) {946 cmd, _, e := c.Root().Find(args)947 if cmd == nil || e != nil {948 c.Printf("Unknown help topic %#q\n", args)949 c.Root().Usage()950 } else {951 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown952 cmd.Help()953 }954 },955 }956 }957 c.RemoveCommand(c.helpCommand)958 c.AddCommand(c.helpCommand)959}960961// ResetCommands delete parent, subcommand and help command from c.962func (c *Command) ResetCommands() {963 c.parent = nil964 c.commands = nil965 c.helpCommand = nil966 c.parentsPflags = nil967}968969// Sorts commands by their names.970type commandSorterByName []*Command971972func (c commandSorterByName) Len() int { return len(c) }973func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }974func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }975976// Commands returns a sorted slice of child commands.977func (c *Command) Commands() []*Command {978 // do not sort commands if it already sorted or sorting was disabled979 if EnableCommandSorting && !c.commandsAreSorted {980 sort.Sort(commandSorterByName(c.commands))981 c.commandsAreSorted = true982 }983 return c.commands984}985986// AddCommand adds one or more commands to this parent command.987func (c *Command) AddCommand(cmds ...*Command) {988 for i, x := range cmds {989 if cmds[i] == c {990 panic("Command can't be a child of itself")991 }992 cmds[i].parent = c993 // update max lengths994 usageLen := len(x.Use)995 if usageLen > c.commandsMaxUseLen {996 c.commandsMaxUseLen = usageLen997 }998 commandPathLen := len(x.CommandPath())999 if commandPathLen > c.commandsMaxCommandPathLen {1000 c.commandsMaxCommandPathLen = commandPathLen1001 }1002 nameLen := len(x.Name())1003 if nameLen > c.commandsMaxNameLen {1004 c.commandsMaxNameLen = nameLen1005 }1006 // If global normalization function exists, update all children1007 if c.globNormFunc != nil {1008 x.SetGlobalNormalizationFunc(c.globNormFunc)1009 }1010 c.commands = append(c.commands, x)1011 c.commandsAreSorted = false1012 }1013}10141015// RemoveCommand removes one or more commands from a parent command.1016func (c *Command) RemoveCommand(cmds ...*Command) {1017 commands := []*Command{}1018main:1019 for _, command := range c.commands {1020 for _, cmd := range cmds {1021 if command == cmd {1022 command.parent = nil1023 continue main1024 }1025 }1026 commands = append(commands, command)1027 }1028 c.commands = commands1029 // recompute all lengths1030 c.commandsMaxUseLen = 01031 c.commandsMaxCommandPathLen = 01032 c.commandsMaxNameLen = 01033 for _, command := range c.commands {1034 usageLen := len(command.Use)1035 if usageLen > c.commandsMaxUseLen {1036 c.commandsMaxUseLen = usageLen1037 }1038 commandPathLen := len(command.CommandPath())1039 if commandPathLen > c.commandsMaxCommandPathLen {1040 c.commandsMaxCommandPathLen = commandPathLen1041 }1042 nameLen := len(command.Name())1043 if nameLen > c.commandsMaxNameLen {1044 c.commandsMaxNameLen = nameLen1045 }1046 }1047}10481049// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1050func (c *Command) Print(i ...interface{}) {1051 fmt.Fprint(c.OutOrStderr(), i...)1052}10531054// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1055func (c *Command) Println(i ...interface{}) {1056 c.Print(fmt.Sprintln(i...))1057}10581059// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1060func (c *Command) Printf(format string, i ...interface{}) {1061 c.Print(fmt.Sprintf(format, i...))1062}10631064// CommandPath returns the full path to this command.1065func (c *Command) CommandPath() string {1066 if c.HasParent() {1067 return c.Parent().CommandPath() + " " + c.Name()1068 }1069 return c.Name()1070}10711072// UseLine puts out the full usage for a given command (including parents).1073func (c *Command) UseLine() string {1074 var useline string1075 if c.HasParent() {1076 useline = c.parent.CommandPath() + " " + c.Use1077 } else {1078 useline = c.Use1079 }1080 if c.DisableFlagsInUseLine {1081 return useline1082 }1083 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1084 useline += " [flags]"1085 }1086 return useline1087}10881089// DebugFlags used to determine which flags have been assigned to which commands1090// and which persist.1091func (c *Command) DebugFlags() {1092 c.Println("DebugFlags called on", c.Name())1093 var debugflags func(*Command)10941095 debugflags = func(x *Command) {1096 if x.HasFlags() || x.HasPersistentFlags() {1097 c.Println(x.Name())1098 }1099 if x.HasFlags() {1100 x.flags.VisitAll(func(f *flag.Flag) {1101 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1102 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1103 } else {1104 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1105 }1106 })1107 }1108 if x.HasPersistentFlags() {1109 x.pflags.VisitAll(func(f *flag.Flag) {1110 if x.HasFlags() {1111 if x.flags.Lookup(f.Name) == nil {1112 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1113 }1114 } else {1115 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1116 }1117 })1118 }1119 c.Println(x.flagErrorBuf)1120 if x.HasSubCommands() {1121 for _, y := range x.commands {1122 debugflags(y)1123 }1124 }1125 }11261127 debugflags(c)1128}11291130// Name returns the command's name: the first word in the use line.1131func (c *Command) Name() string {1132 name := c.Use1133 i := strings.Index(name, " ")1134 if i >= 0 {1135 name = name[:i]1136 }1137 return name1138}11391140// HasAlias determines if a given string is an alias of the command.1141func (c *Command) HasAlias(s string) bool {1142 for _, a := range c.Aliases {1143 if a == s {1144 return true1145 }1146 }1147 return false1148}11491150// CalledAs returns the command name or alias that was used to invoke1151// this command or an empty string if the command has not been called.1152func (c *Command) CalledAs() string {1153 if c.commandCalledAs.called {1154 return c.commandCalledAs.name1155 }1156 return ""1157}11581159// hasNameOrAliasPrefix returns true if the Name or any of aliases start1160// with prefix1161func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1162 if strings.HasPrefix(c.Name(), prefix) {1163 c.commandCalledAs.name = c.Name()1164 return true1165 }1166 for _, alias := range c.Aliases {1167 if strings.HasPrefix(alias, prefix) {1168 c.commandCalledAs.name = alias1169 return true1170 }1171 }1172 return false1173}11741175// NameAndAliases returns a list of the command name and all aliases1176func (c *Command) NameAndAliases() string {1177 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1178}11791180// HasExample determines if the command has example.1181func (c *Command) HasExample() bool {1182 return len(c.Example) > 01183}11841185// Runnable determines if the command is itself runnable.1186func (c *Command) Runnable() bool {1187 return c.Run != nil || c.RunE != nil1188}11891190// HasSubCommands determines if the command has children commands.1191func (c *Command) HasSubCommands() bool {1192 return len(c.commands) > 01193}11941195// IsAvailableCommand determines if a command is available as a non-help command1196// (this includes all non deprecated/hidden commands).1197func (c *Command) IsAvailableCommand() bool {1198 if len(c.Deprecated) != 0 || c.Hidden {1199 return false1200 }12011202 if c.HasParent() && c.Parent().helpCommand == c {1203 return false1204 }12051206 if c.Runnable() || c.HasAvailableSubCommands() {1207 return true1208 }12091210 return false1211}12121213// IsAdditionalHelpTopicCommand determines if a command is an additional1214// help topic command; additional help topic command is determined by the1215// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1216// are runnable/hidden/deprecated.1217// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1218func (c *Command) IsAdditionalHelpTopicCommand() bool {1219 // if a command is runnable, deprecated, or hidden it is not a 'help' command1220 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1221 return false1222 }12231224 // if any non-help sub commands are found, the command is not a 'help' command1225 for _, sub := range c.commands {1226 if !sub.IsAdditionalHelpTopicCommand() {1227 return false1228 }1229 }12301231 // the command either has no sub commands, or no non-help sub commands1232 return true1233}12341235// HasHelpSubCommands determines if a command has any available 'help' sub commands1236// that need to be shown in the usage/help default template under 'additional help1237// topics'.1238func (c *Command) HasHelpSubCommands() bool {1239 // return true on the first found available 'help' sub command1240 for _, sub := range c.commands {1241 if sub.IsAdditionalHelpTopicCommand() {1242 return true1243 }1244 }12451246 // the command either has no sub commands, or no available 'help' sub commands1247 return false1248}12491250// HasAvailableSubCommands determines if a command has available sub commands that1251// need to be shown in the usage/help default template under 'available commands'.1252func (c *Command) HasAvailableSubCommands() bool {1253 // return true on the first found available (non deprecated/help/hidden)1254 // sub command1255 for _, sub := range c.commands {1256 if sub.IsAvailableCommand() {1257 return true1258 }1259 }12601261 // the command either has no sub commands, or no available (non deprecated/help/hidden)1262 // sub commands1263 return false1264}12651266// HasParent determines if the command is a child command.1267func (c *Command) HasParent() bool {1268 return c.parent != nil1269}12701271// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.1272func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1273 return c.globNormFunc1274}12751276// Flags returns the complete FlagSet that applies1277// to this command (local and persistent declared here and by all parents).1278func (c *Command) Flags() *flag.FlagSet {1279 if c.flags == nil {1280 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1281 if c.flagErrorBuf == nil {1282 c.flagErrorBuf = new(bytes.Buffer)1283 }1284 c.flags.SetOutput(c.flagErrorBuf)1285 }12861287 return c.flags1288}12891290// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1291func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1292 persistentFlags := c.PersistentFlags()12931294 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1295 c.LocalFlags().VisitAll(func(f *flag.Flag) {1296 if persistentFlags.Lookup(f.Name) == nil {1297 out.AddFlag(f)1298 }1299 })1300 return out1301}13021303// LocalFlags returns the local FlagSet specifically set in the current command.1304func (c *Command) LocalFlags() *flag.FlagSet {1305 c.mergePersistentFlags()13061307 if c.lflags == nil {1308 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1309 if c.flagErrorBuf == nil {1310 c.flagErrorBuf = new(bytes.Buffer)1311 }1312 c.lflags.SetOutput(c.flagErrorBuf)1313 }1314 c.lflags.SortFlags = c.Flags().SortFlags1315 if c.globNormFunc != nil {1316 c.lflags.SetNormalizeFunc(c.globNormFunc)1317 }13181319 addToLocal := func(f *flag.Flag) {1320 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1321 c.lflags.AddFlag(f)1322 }1323 }1324 c.Flags().VisitAll(addToLocal)1325 c.PersistentFlags().VisitAll(addToLocal)1326 return c.lflags1327}13281329// InheritedFlags returns all flags which were inherited from parents commands.1330func (c *Command) InheritedFlags() *flag.FlagSet {1331 c.mergePersistentFlags()13321333 if c.iflags == nil {1334 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1335 if c.flagErrorBuf == nil {1336 c.flagErrorBuf = new(bytes.Buffer)1337 }1338 c.iflags.SetOutput(c.flagErrorBuf)1339 }13401341 local := c.LocalFlags()1342 if c.globNormFunc != nil {1343 c.iflags.SetNormalizeFunc(c.globNormFunc)1344 }13451346 c.parentsPflags.VisitAll(func(f *flag.Flag) {1347 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1348 c.iflags.AddFlag(f)1349 }1350 })1351 return c.iflags1352}13531354// NonInheritedFlags returns all flags which were not inherited from parent commands.1355func (c *Command) NonInheritedFlags() *flag.FlagSet {1356 return c.LocalFlags()1357}13581359// PersistentFlags returns the persistent FlagSet specifically set in the current command.1360func (c *Command) PersistentFlags() *flag.FlagSet {1361 if c.pflags == nil {1362 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1363 if c.flagErrorBuf == nil {1364 c.flagErrorBuf = new(bytes.Buffer)1365 }1366 c.pflags.SetOutput(c.flagErrorBuf)1367 }1368 return c.pflags1369}13701371// ResetFlags deletes all flags from command.1372func (c *Command) ResetFlags() {1373 c.flagErrorBuf = new(bytes.Buffer)1374 c.flagErrorBuf.Reset()1375 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1376 c.flags.SetOutput(c.flagErrorBuf)1377 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1378 c.pflags.SetOutput(c.flagErrorBuf)13791380 c.lflags = nil1381 c.iflags = nil1382 c.parentsPflags = nil1383}13841385// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1386func (c *Command) HasFlags() bool {1387 return c.Flags().HasFlags()1388}13891390// HasPersistentFlags checks if the command contains persistent flags.1391func (c *Command) HasPersistentFlags() bool {1392 return c.PersistentFlags().HasFlags()1393}13941395// HasLocalFlags checks if the command has flags specifically declared locally.1396func (c *Command) HasLocalFlags() bool {1397 return c.LocalFlags().HasFlags()1398}13991400// HasInheritedFlags checks if the command has flags inherited from its parent command.1401func (c *Command) HasInheritedFlags() bool {1402 return c.InheritedFlags().HasFlags()1403}14041405// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1406// structure) which are not hidden or deprecated.1407func (c *Command) HasAvailableFlags() bool {1408 return c.Flags().HasAvailableFlags()1409}14101411// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1412func (c *Command) HasAvailablePersistentFlags() bool {1413 return c.PersistentFlags().HasAvailableFlags()1414}14151416// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1417// or deprecated.1418func (c *Command) HasAvailableLocalFlags() bool {1419 return c.LocalFlags().HasAvailableFlags()1420}14211422// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1423// not hidden or deprecated.1424func (c *Command) HasAvailableInheritedFlags() bool {1425 return c.InheritedFlags().HasAvailableFlags()1426}14271428// Flag climbs up the command tree looking for matching flag.1429func (c *Command) Flag(name string) (flag *flag.Flag) {1430 flag = c.Flags().Lookup(name)14311432 if flag == nil {1433 flag = c.persistentFlag(name)1434 }14351436 return1437}14381439// Recursively find matching persistent flag.1440func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1441 if c.HasPersistentFlags() {1442 flag = c.PersistentFlags().Lookup(name)1443 }14441445 if flag == nil {1446 c.updateParentsPflags()1447 flag = c.parentsPflags.Lookup(name)1448 }1449 return1450}14511452// ParseFlags parses persistent flag tree and local flags.1453func (c *Command) ParseFlags(args []string) error {1454 if c.DisableFlagParsing {1455 return nil1456 }14571458 if c.flagErrorBuf == nil {1459 c.flagErrorBuf = new(bytes.Buffer)1460 }1461 beforeErrorBufLen := c.flagErrorBuf.Len()1462 c.mergePersistentFlags()1463 err := c.Flags().Parse(args)1464 // Print warnings if they occurred (e.g. deprecated flag messages).1465 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1466 c.Print(c.flagErrorBuf.String())1467 }14681469 return err1470}14711472// Parent returns a commands parent command.1473func (c *Command) Parent() *Command {1474 return c.parent1475}14761477// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1478// and adds missing persistent flags of all parents.1479func (c *Command) mergePersistentFlags() {1480 c.updateParentsPflags()1481 c.Flags().AddFlagSet(c.PersistentFlags())1482 c.Flags().AddFlagSet(c.parentsPflags)1483}14841485// updateParentsPflags updates c.parentsPflags by adding1486// new persistent flags of all parents.1487// If c.parentsPflags == nil, it makes new.1488func (c *Command) updateParentsPflags() {1489 if c.parentsPflags == nil {1490 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1491 c.parentsPflags.SetOutput(c.flagErrorBuf)1492 c.parentsPflags.SortFlags = false1493 }14941495 if c.globNormFunc != nil {1496 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1497 }14981499 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)15001501 c.VisitParents(func(parent *Command) {1502 c.parentsPflags.AddFlagSet(parent.PersistentFlags())1503 })1504}