Skip to content
Myr

command.go

This file

Path

command.go

1,507 lines · 41.4 KiB · Go

Last changed by

Terminate the stripping of flags when -- is found (#649)Di Xubefore adoptionc439c4f

History of this file

Take 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 s == "--":479			// "--" terminates the flags480			break Loop481		case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):482			// If '--flag arg' then483			// delete arg from args.484			fallthrough // (do the same as below)485		case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):486			// If '-f arg' then487			// delete 'arg' from args or break the loop if len(args) <= 1.488			if len(args) <= 1 {489				break Loop490			} else {491				args = args[1:]492				continue493			}494		case s != "" && !strings.HasPrefix(s, "-"):495			commands = append(commands, s)496		}497	}498499	return commands500}501502// argsMinusFirstX removes only the first x from args.  Otherwise, commands that look like503// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).504func argsMinusFirstX(args []string, x string) []string {505	for i, y := range args {506		if x == y {507			ret := []string{}508			ret = append(ret, args[:i]...)509			ret = append(ret, args[i+1:]...)510			return ret511		}512	}513	return args514}515516func isFlagArg(arg string) bool {517	return ((len(arg) >= 3 && arg[1] == '-') ||518		(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))519}520521// Find the target command given the args and command tree522// Meant to be run on the highest node. Only searches down.523func (c *Command) Find(args []string) (*Command, []string, error) {524	var innerfind func(*Command, []string) (*Command, []string)525526	innerfind = func(c *Command, innerArgs []string) (*Command, []string) {527		argsWOflags := stripFlags(innerArgs, c)528		if len(argsWOflags) == 0 {529			return c, innerArgs530		}531		nextSubCmd := argsWOflags[0]532533		cmd := c.findNext(nextSubCmd)534		if cmd != nil {535			return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))536		}537		return c, innerArgs538	}539540	commandFound, a := innerfind(c, args)541	if commandFound.Args == nil {542		return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))543	}544	return commandFound, a, nil545}546547func (c *Command) findSuggestions(arg string) string {548	if c.DisableSuggestions {549		return ""550	}551	if c.SuggestionsMinimumDistance <= 0 {552		c.SuggestionsMinimumDistance = 2553	}554	suggestionsString := ""555	if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {556		suggestionsString += "\n\nDid you mean this?\n"557		for _, s := range suggestions {558			suggestionsString += fmt.Sprintf("\t%v\n", s)559		}560	}561	return suggestionsString562}563564func (c *Command) findNext(next string) *Command {565	matches := make([]*Command, 0)566	for _, cmd := range c.commands {567		if cmd.Name() == next || cmd.HasAlias(next) {568			cmd.commandCalledAs.name = next569			return cmd570		}571		if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {572			matches = append(matches, cmd)573		}574	}575576	if len(matches) == 1 {577		return matches[0]578	}579580	return nil581}582583// Traverse the command tree to find the command, and parse args for584// each parent.585func (c *Command) Traverse(args []string) (*Command, []string, error) {586	flags := []string{}587	inFlag := false588589	for i, arg := range args {590		switch {591		// A long flag with a space separated value592		case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):593			// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'594			inFlag = !hasNoOptDefVal(arg[2:], c.Flags())595			flags = append(flags, arg)596			continue597		// A short flag with a space separated value598		case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):599			inFlag = true600			flags = append(flags, arg)601			continue602		// The value for a flag603		case inFlag:604			inFlag = false605			flags = append(flags, arg)606			continue607		// A flag without a value, or with an `=` separated value608		case isFlagArg(arg):609			flags = append(flags, arg)610			continue611		}612613		cmd := c.findNext(arg)614		if cmd == nil {615			return c, args, nil616		}617618		if err := c.ParseFlags(flags); err != nil {619			return nil, args, err620		}621		return cmd.Traverse(args[i+1:])622	}623	return c, args, nil624}625626// SuggestionsFor provides suggestions for the typedName.627func (c *Command) SuggestionsFor(typedName string) []string {628	suggestions := []string{}629	for _, cmd := range c.commands {630		if cmd.IsAvailableCommand() {631			levenshteinDistance := ld(typedName, cmd.Name(), true)632			suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance633			suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))634			if suggestByLevenshtein || suggestByPrefix {635				suggestions = append(suggestions, cmd.Name())636			}637			for _, explicitSuggestion := range cmd.SuggestFor {638				if strings.EqualFold(typedName, explicitSuggestion) {639					suggestions = append(suggestions, cmd.Name())640				}641			}642		}643	}644	return suggestions645}646647// VisitParents visits all parents of the command and invokes fn on each parent.648func (c *Command) VisitParents(fn func(*Command)) {649	if c.HasParent() {650		fn(c.Parent())651		c.Parent().VisitParents(fn)652	}653}654655// Root finds root command.656func (c *Command) Root() *Command {657	if c.HasParent() {658		return c.Parent().Root()659	}660	return c661}662663// ArgsLenAtDash will return the length of c.Flags().Args at the moment664// when a -- was found during args parsing.665func (c *Command) ArgsLenAtDash() int {666	return c.Flags().ArgsLenAtDash()667}668669func (c *Command) execute(a []string) (err error) {670	if c == nil {671		return fmt.Errorf("Called Execute() on a nil Command")672	}673674	if len(c.Deprecated) > 0 {675		c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)676	}677678	// initialize help and version flag at the last point possible to allow for user679	// overriding680	c.InitDefaultHelpFlag()681	c.InitDefaultVersionFlag()682683	err = c.ParseFlags(a)684	if err != nil {685		return c.FlagErrorFunc()(c, err)686	}687688	// If help is called, regardless of other flags, return we want help.689	// Also say we need help if the command isn't runnable.690	helpVal, err := c.Flags().GetBool("help")691	if err != nil {692		// should be impossible to get here as we always declare a help693		// flag in InitDefaultHelpFlag()694		c.Println("\"help\" flag declared as non-bool. Please correct your code")695		return err696	}697698	if helpVal {699		return flag.ErrHelp700	}701702	// for back-compat, only add version flag behavior if version is defined703	if c.Version != "" {704		versionVal, err := c.Flags().GetBool("version")705		if err != nil {706			c.Println("\"version\" flag declared as non-bool. Please correct your code")707			return err708		}709		if versionVal {710			err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)711			if err != nil {712				c.Println(err)713			}714			return err715		}716	}717718	if !c.Runnable() {719		return flag.ErrHelp720	}721722	c.preRun()723724	argWoFlags := c.Flags().Args()725	if c.DisableFlagParsing {726		argWoFlags = a727	}728729	if err := c.ValidateArgs(argWoFlags); err != nil {730		return err731	}732733	for p := c; p != nil; p = p.Parent() {734		if p.PersistentPreRunE != nil {735			if err := p.PersistentPreRunE(c, argWoFlags); err != nil {736				return err737			}738			break739		} else if p.PersistentPreRun != nil {740			p.PersistentPreRun(c, argWoFlags)741			break742		}743	}744	if c.PreRunE != nil {745		if err := c.PreRunE(c, argWoFlags); err != nil {746			return err747		}748	} else if c.PreRun != nil {749		c.PreRun(c, argWoFlags)750	}751752	if err := c.validateRequiredFlags(); err != nil {753		return err754	}755	if c.RunE != nil {756		if err := c.RunE(c, argWoFlags); err != nil {757			return err758		}759	} else {760		c.Run(c, argWoFlags)761	}762	if c.PostRunE != nil {763		if err := c.PostRunE(c, argWoFlags); err != nil {764			return err765		}766	} else if c.PostRun != nil {767		c.PostRun(c, argWoFlags)768	}769	for p := c; p != nil; p = p.Parent() {770		if p.PersistentPostRunE != nil {771			if err := p.PersistentPostRunE(c, argWoFlags); err != nil {772				return err773			}774			break775		} else if p.PersistentPostRun != nil {776			p.PersistentPostRun(c, argWoFlags)777			break778		}779	}780781	return nil782}783784func (c *Command) preRun() {785	for _, x := range initializers {786		x()787	}788}789790// Execute uses the args (os.Args[1:] by default)791// and run through the command tree finding appropriate matches792// for commands and then corresponding flags.793func (c *Command) Execute() error {794	_, err := c.ExecuteC()795	return err796}797798// ExecuteC executes the command.799func (c *Command) ExecuteC() (cmd *Command, err error) {800	// Regardless of what command execute is called on, run on Root only801	if c.HasParent() {802		return c.Root().ExecuteC()803	}804805	// windows hook806	if preExecHookFn != nil {807		preExecHookFn(c)808	}809810	// initialize help as the last point possible to allow for user811	// overriding812	c.InitDefaultHelpCmd()813814	var args []string815816	// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155817	if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {818		args = os.Args[1:]819	} else {820		args = c.args821	}822823	var flags []string824	if c.TraverseChildren {825		cmd, flags, err = c.Traverse(args)826	} else {827		cmd, flags, err = c.Find(args)828	}829	if err != nil {830		// If found parse to a subcommand and then failed, talk about the subcommand831		if cmd != nil {832			c = cmd833		}834		if !c.SilenceErrors {835			c.Println("Error:", err.Error())836			c.Printf("Run '%v --help' for usage.\n", c.CommandPath())837		}838		return c, err839	}840841	cmd.commandCalledAs.called = true842	if cmd.commandCalledAs.name == "" {843		cmd.commandCalledAs.name = cmd.Name()844	}845846	err = cmd.execute(flags)847	if err != nil {848		// Always show help if requested, even if SilenceErrors is in849		// effect850		if err == flag.ErrHelp {851			cmd.HelpFunc()(cmd, args)852			return cmd, nil853		}854855		// If root command has SilentErrors flagged,856		// all subcommands should respect it857		if !cmd.SilenceErrors && !c.SilenceErrors {858			c.Println("Error:", err.Error())859		}860861		// If root command has SilentUsage flagged,862		// all subcommands should respect it863		if !cmd.SilenceUsage && !c.SilenceUsage {864			c.Println(cmd.UsageString())865		}866	}867	return cmd, err868}869870func (c *Command) ValidateArgs(args []string) error {871	if c.Args == nil {872		return nil873	}874	return c.Args(c, args)875}876877func (c *Command) validateRequiredFlags() error {878	flags := c.Flags()879	missingFlagNames := []string{}880	flags.VisitAll(func(pflag *flag.Flag) {881		requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]882		if !found {883			return884		}885		if (requiredAnnotation[0] == "true") && !pflag.Changed {886			missingFlagNames = append(missingFlagNames, pflag.Name)887		}888	})889890	if len(missingFlagNames) > 0 {891		return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))892	}893	return nil894}895896// InitDefaultHelpFlag adds default help flag to c.897// It is called automatically by executing the c or by calling help and usage.898// If c already has help flag, it will do nothing.899func (c *Command) InitDefaultHelpFlag() {900	c.mergePersistentFlags()901	if c.Flags().Lookup("help") == nil {902		usage := "help for "903		if c.Name() == "" {904			usage += "this command"905		} else {906			usage += c.Name()907		}908		c.Flags().BoolP("help", "h", false, usage)909	}910}911912// InitDefaultVersionFlag adds default version flag to c.913// It is called automatically by executing the c.914// If c already has a version flag, it will do nothing.915// If c.Version is empty, it will do nothing.916func (c *Command) InitDefaultVersionFlag() {917	if c.Version == "" {918		return919	}920921	c.mergePersistentFlags()922	if c.Flags().Lookup("version") == nil {923		usage := "version for "924		if c.Name() == "" {925			usage += "this command"926		} else {927			usage += c.Name()928		}929		c.Flags().Bool("version", false, usage)930	}931}932933// InitDefaultHelpCmd adds default help command to c.934// It is called automatically by executing the c or by calling help and usage.935// If c already has help command or c has no subcommands, it will do nothing.936func (c *Command) InitDefaultHelpCmd() {937	if !c.HasSubCommands() {938		return939	}940941	if c.helpCommand == nil {942		c.helpCommand = &Command{943			Use:   "help [command]",944			Short: "Help about any command",945			Long: `Help provides help for any command in the application.946Simply type ` + c.Name() + ` help [path to command] for full details.`,947948			Run: func(c *Command, args []string) {949				cmd, _, e := c.Root().Find(args)950				if cmd == nil || e != nil {951					c.Printf("Unknown help topic %#q\n", args)952					c.Root().Usage()953				} else {954					cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown955					cmd.Help()956				}957			},958		}959	}960	c.RemoveCommand(c.helpCommand)961	c.AddCommand(c.helpCommand)962}963964// ResetCommands delete parent, subcommand and help command from c.965func (c *Command) ResetCommands() {966	c.parent = nil967	c.commands = nil968	c.helpCommand = nil969	c.parentsPflags = nil970}971972// Sorts commands by their names.973type commandSorterByName []*Command974975func (c commandSorterByName) Len() int           { return len(c) }976func (c commandSorterByName) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }977func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }978979// Commands returns a sorted slice of child commands.980func (c *Command) Commands() []*Command {981	// do not sort commands if it already sorted or sorting was disabled982	if EnableCommandSorting && !c.commandsAreSorted {983		sort.Sort(commandSorterByName(c.commands))984		c.commandsAreSorted = true985	}986	return c.commands987}988989// AddCommand adds one or more commands to this parent command.990func (c *Command) AddCommand(cmds ...*Command) {991	for i, x := range cmds {992		if cmds[i] == c {993			panic("Command can't be a child of itself")994		}995		cmds[i].parent = c996		// update max lengths997		usageLen := len(x.Use)998		if usageLen > c.commandsMaxUseLen {999			c.commandsMaxUseLen = usageLen1000		}1001		commandPathLen := len(x.CommandPath())1002		if commandPathLen > c.commandsMaxCommandPathLen {1003			c.commandsMaxCommandPathLen = commandPathLen1004		}1005		nameLen := len(x.Name())1006		if nameLen > c.commandsMaxNameLen {1007			c.commandsMaxNameLen = nameLen1008		}1009		// If global normalization function exists, update all children1010		if c.globNormFunc != nil {1011			x.SetGlobalNormalizationFunc(c.globNormFunc)1012		}1013		c.commands = append(c.commands, x)1014		c.commandsAreSorted = false1015	}1016}10171018// RemoveCommand removes one or more commands from a parent command.1019func (c *Command) RemoveCommand(cmds ...*Command) {1020	commands := []*Command{}1021main:1022	for _, command := range c.commands {1023		for _, cmd := range cmds {1024			if command == cmd {1025				command.parent = nil1026				continue main1027			}1028		}1029		commands = append(commands, command)1030	}1031	c.commands = commands1032	// recompute all lengths1033	c.commandsMaxUseLen = 01034	c.commandsMaxCommandPathLen = 01035	c.commandsMaxNameLen = 01036	for _, command := range c.commands {1037		usageLen := len(command.Use)1038		if usageLen > c.commandsMaxUseLen {1039			c.commandsMaxUseLen = usageLen1040		}1041		commandPathLen := len(command.CommandPath())1042		if commandPathLen > c.commandsMaxCommandPathLen {1043			c.commandsMaxCommandPathLen = commandPathLen1044		}1045		nameLen := len(command.Name())1046		if nameLen > c.commandsMaxNameLen {1047			c.commandsMaxNameLen = nameLen1048		}1049	}1050}10511052// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1053func (c *Command) Print(i ...interface{}) {1054	fmt.Fprint(c.OutOrStderr(), i...)1055}10561057// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1058func (c *Command) Println(i ...interface{}) {1059	c.Print(fmt.Sprintln(i...))1060}10611062// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1063func (c *Command) Printf(format string, i ...interface{}) {1064	c.Print(fmt.Sprintf(format, i...))1065}10661067// CommandPath returns the full path to this command.1068func (c *Command) CommandPath() string {1069	if c.HasParent() {1070		return c.Parent().CommandPath() + " " + c.Name()1071	}1072	return c.Name()1073}10741075// UseLine puts out the full usage for a given command (including parents).1076func (c *Command) UseLine() string {1077	var useline string1078	if c.HasParent() {1079		useline = c.parent.CommandPath() + " " + c.Use1080	} else {1081		useline = c.Use1082	}1083	if c.DisableFlagsInUseLine {1084		return useline1085	}1086	if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1087		useline += " [flags]"1088	}1089	return useline1090}10911092// DebugFlags used to determine which flags have been assigned to which commands1093// and which persist.1094func (c *Command) DebugFlags() {1095	c.Println("DebugFlags called on", c.Name())1096	var debugflags func(*Command)10971098	debugflags = func(x *Command) {1099		if x.HasFlags() || x.HasPersistentFlags() {1100			c.Println(x.Name())1101		}1102		if x.HasFlags() {1103			x.flags.VisitAll(func(f *flag.Flag) {1104				if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1105					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [LP]")1106				} else {1107					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")1108				}1109			})1110		}1111		if x.HasPersistentFlags() {1112			x.pflags.VisitAll(func(f *flag.Flag) {1113				if x.HasFlags() {1114					if x.flags.Lookup(f.Name) == nil {1115						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")1116					}1117				} else {1118					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")1119				}1120			})1121		}1122		c.Println(x.flagErrorBuf)1123		if x.HasSubCommands() {1124			for _, y := range x.commands {1125				debugflags(y)1126			}1127		}1128	}11291130	debugflags(c)1131}11321133// Name returns the command's name: the first word in the use line.1134func (c *Command) Name() string {1135	name := c.Use1136	i := strings.Index(name, " ")1137	if i >= 0 {1138		name = name[:i]1139	}1140	return name1141}11421143// HasAlias determines if a given string is an alias of the command.1144func (c *Command) HasAlias(s string) bool {1145	for _, a := range c.Aliases {1146		if a == s {1147			return true1148		}1149	}1150	return false1151}11521153// CalledAs returns the command name or alias that was used to invoke1154// this command or an empty string if the command has not been called.1155func (c *Command) CalledAs() string {1156	if c.commandCalledAs.called {1157		return c.commandCalledAs.name1158	}1159	return ""1160}11611162// hasNameOrAliasPrefix returns true if the Name or any of aliases start1163// with prefix1164func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1165	if strings.HasPrefix(c.Name(), prefix) {1166		c.commandCalledAs.name = c.Name()1167		return true1168	}1169	for _, alias := range c.Aliases {1170		if strings.HasPrefix(alias, prefix) {1171			c.commandCalledAs.name = alias1172			return true1173		}1174	}1175	return false1176}11771178// NameAndAliases returns a list of the command name and all aliases1179func (c *Command) NameAndAliases() string {1180	return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1181}11821183// HasExample determines if the command has example.1184func (c *Command) HasExample() bool {1185	return len(c.Example) > 01186}11871188// Runnable determines if the command is itself runnable.1189func (c *Command) Runnable() bool {1190	return c.Run != nil || c.RunE != nil1191}11921193// HasSubCommands determines if the command has children commands.1194func (c *Command) HasSubCommands() bool {1195	return len(c.commands) > 01196}11971198// IsAvailableCommand determines if a command is available as a non-help command1199// (this includes all non deprecated/hidden commands).1200func (c *Command) IsAvailableCommand() bool {1201	if len(c.Deprecated) != 0 || c.Hidden {1202		return false1203	}12041205	if c.HasParent() && c.Parent().helpCommand == c {1206		return false1207	}12081209	if c.Runnable() || c.HasAvailableSubCommands() {1210		return true1211	}12121213	return false1214}12151216// IsAdditionalHelpTopicCommand determines if a command is an additional1217// help topic command; additional help topic command is determined by the1218// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1219// are runnable/hidden/deprecated.1220// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1221func (c *Command) IsAdditionalHelpTopicCommand() bool {1222	// if a command is runnable, deprecated, or hidden it is not a 'help' command1223	if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1224		return false1225	}12261227	// if any non-help sub commands are found, the command is not a 'help' command1228	for _, sub := range c.commands {1229		if !sub.IsAdditionalHelpTopicCommand() {1230			return false1231		}1232	}12331234	// the command either has no sub commands, or no non-help sub commands1235	return true1236}12371238// HasHelpSubCommands determines if a command has any available 'help' sub commands1239// that need to be shown in the usage/help default template under 'additional help1240// topics'.1241func (c *Command) HasHelpSubCommands() bool {1242	// return true on the first found available 'help' sub command1243	for _, sub := range c.commands {1244		if sub.IsAdditionalHelpTopicCommand() {1245			return true1246		}1247	}12481249	// the command either has no sub commands, or no available 'help' sub commands1250	return false1251}12521253// HasAvailableSubCommands determines if a command has available sub commands that1254// need to be shown in the usage/help default template under 'available commands'.1255func (c *Command) HasAvailableSubCommands() bool {1256	// return true on the first found available (non deprecated/help/hidden)1257	// sub command1258	for _, sub := range c.commands {1259		if sub.IsAvailableCommand() {1260			return true1261		}1262	}12631264	// the command either has no sub commands, or no available (non deprecated/help/hidden)1265	// sub commands1266	return false1267}12681269// HasParent determines if the command is a child command.1270func (c *Command) HasParent() bool {1271	return c.parent != nil1272}12731274// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.1275func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1276	return c.globNormFunc1277}12781279// Flags returns the complete FlagSet that applies1280// to this command (local and persistent declared here and by all parents).1281func (c *Command) Flags() *flag.FlagSet {1282	if c.flags == nil {1283		c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1284		if c.flagErrorBuf == nil {1285			c.flagErrorBuf = new(bytes.Buffer)1286		}1287		c.flags.SetOutput(c.flagErrorBuf)1288	}12891290	return c.flags1291}12921293// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1294func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1295	persistentFlags := c.PersistentFlags()12961297	out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1298	c.LocalFlags().VisitAll(func(f *flag.Flag) {1299		if persistentFlags.Lookup(f.Name) == nil {1300			out.AddFlag(f)1301		}1302	})1303	return out1304}13051306// LocalFlags returns the local FlagSet specifically set in the current command.1307func (c *Command) LocalFlags() *flag.FlagSet {1308	c.mergePersistentFlags()13091310	if c.lflags == nil {1311		c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1312		if c.flagErrorBuf == nil {1313			c.flagErrorBuf = new(bytes.Buffer)1314		}1315		c.lflags.SetOutput(c.flagErrorBuf)1316	}1317	c.lflags.SortFlags = c.Flags().SortFlags1318	if c.globNormFunc != nil {1319		c.lflags.SetNormalizeFunc(c.globNormFunc)1320	}13211322	addToLocal := func(f *flag.Flag) {1323		if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1324			c.lflags.AddFlag(f)1325		}1326	}1327	c.Flags().VisitAll(addToLocal)1328	c.PersistentFlags().VisitAll(addToLocal)1329	return c.lflags1330}13311332// InheritedFlags returns all flags which were inherited from parents commands.1333func (c *Command) InheritedFlags() *flag.FlagSet {1334	c.mergePersistentFlags()13351336	if c.iflags == nil {1337		c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1338		if c.flagErrorBuf == nil {1339			c.flagErrorBuf = new(bytes.Buffer)1340		}1341		c.iflags.SetOutput(c.flagErrorBuf)1342	}13431344	local := c.LocalFlags()1345	if c.globNormFunc != nil {1346		c.iflags.SetNormalizeFunc(c.globNormFunc)1347	}13481349	c.parentsPflags.VisitAll(func(f *flag.Flag) {1350		if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1351			c.iflags.AddFlag(f)1352		}1353	})1354	return c.iflags1355}13561357// NonInheritedFlags returns all flags which were not inherited from parent commands.1358func (c *Command) NonInheritedFlags() *flag.FlagSet {1359	return c.LocalFlags()1360}13611362// PersistentFlags returns the persistent FlagSet specifically set in the current command.1363func (c *Command) PersistentFlags() *flag.FlagSet {1364	if c.pflags == nil {1365		c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1366		if c.flagErrorBuf == nil {1367			c.flagErrorBuf = new(bytes.Buffer)1368		}1369		c.pflags.SetOutput(c.flagErrorBuf)1370	}1371	return c.pflags1372}13731374// ResetFlags deletes all flags from command.1375func (c *Command) ResetFlags() {1376	c.flagErrorBuf = new(bytes.Buffer)1377	c.flagErrorBuf.Reset()1378	c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1379	c.flags.SetOutput(c.flagErrorBuf)1380	c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1381	c.pflags.SetOutput(c.flagErrorBuf)13821383	c.lflags = nil1384	c.iflags = nil1385	c.parentsPflags = nil1386}13871388// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1389func (c *Command) HasFlags() bool {1390	return c.Flags().HasFlags()1391}13921393// HasPersistentFlags checks if the command contains persistent flags.1394func (c *Command) HasPersistentFlags() bool {1395	return c.PersistentFlags().HasFlags()1396}13971398// HasLocalFlags checks if the command has flags specifically declared locally.1399func (c *Command) HasLocalFlags() bool {1400	return c.LocalFlags().HasFlags()1401}14021403// HasInheritedFlags checks if the command has flags inherited from its parent command.1404func (c *Command) HasInheritedFlags() bool {1405	return c.InheritedFlags().HasFlags()1406}14071408// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1409// structure) which are not hidden or deprecated.1410func (c *Command) HasAvailableFlags() bool {1411	return c.Flags().HasAvailableFlags()1412}14131414// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1415func (c *Command) HasAvailablePersistentFlags() bool {1416	return c.PersistentFlags().HasAvailableFlags()1417}14181419// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1420// or deprecated.1421func (c *Command) HasAvailableLocalFlags() bool {1422	return c.LocalFlags().HasAvailableFlags()1423}14241425// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1426// not hidden or deprecated.1427func (c *Command) HasAvailableInheritedFlags() bool {1428	return c.InheritedFlags().HasAvailableFlags()1429}14301431// Flag climbs up the command tree looking for matching flag.1432func (c *Command) Flag(name string) (flag *flag.Flag) {1433	flag = c.Flags().Lookup(name)14341435	if flag == nil {1436		flag = c.persistentFlag(name)1437	}14381439	return1440}14411442// Recursively find matching persistent flag.1443func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1444	if c.HasPersistentFlags() {1445		flag = c.PersistentFlags().Lookup(name)1446	}14471448	if flag == nil {1449		c.updateParentsPflags()1450		flag = c.parentsPflags.Lookup(name)1451	}1452	return1453}14541455// ParseFlags parses persistent flag tree and local flags.1456func (c *Command) ParseFlags(args []string) error {1457	if c.DisableFlagParsing {1458		return nil1459	}14601461	if c.flagErrorBuf == nil {1462		c.flagErrorBuf = new(bytes.Buffer)1463	}1464	beforeErrorBufLen := c.flagErrorBuf.Len()1465	c.mergePersistentFlags()1466	err := c.Flags().Parse(args)1467	// Print warnings if they occurred (e.g. deprecated flag messages).1468	if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1469		c.Print(c.flagErrorBuf.String())1470	}14711472	return err1473}14741475// Parent returns a commands parent command.1476func (c *Command) Parent() *Command {1477	return c.parent1478}14791480// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1481// and adds missing persistent flags of all parents.1482func (c *Command) mergePersistentFlags() {1483	c.updateParentsPflags()1484	c.Flags().AddFlagSet(c.PersistentFlags())1485	c.Flags().AddFlagSet(c.parentsPflags)1486}14871488// updateParentsPflags updates c.parentsPflags by adding1489// new persistent flags of all parents.1490// If c.parentsPflags == nil, it makes new.1491func (c *Command) updateParentsPflags() {1492	if c.parentsPflags == nil {1493		c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1494		c.parentsPflags.SetOutput(c.flagErrorBuf)1495		c.parentsPflags.SortFlags = false1496	}14971498	if c.globNormFunc != nil {1499		c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1500	}15011502	c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)15031504	c.VisitParents(func(parent *Command) {1505		c.parentsPflags.AddFlagSet(parent.PersistentFlags())1506	})1507}