Skip to content
Myr

command.go

This file

Path

command.go

1,289 lines · 36.3 KiB · Go

Last changed by

Fix tests so they give correct args (#445)Albert Nigmatzianovbefore adoption51b7cf5

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	// ArgAliases is List of aliases for ValidArgs.58	// These are not suggested to the user in the bash completion,59	// but accepted if entered manually.60	ArgAliases []string6162	// BashCompletionFunction is custom functions used by the bash autocompletion generator.63	BashCompletionFunction string6465	// Deprecated defines, if this command is deprecated and should print this string when used.66	Deprecated string6768	// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.69	Hidden bool7071	// Annotations are key/value pairs that can be used by applications to identify or72	// group commands.73	Annotations map[string]string7475	// The *Run functions are executed in the following order:76	//   * PersistentPreRun()77	//   * PreRun()78	//   * Run()79	//   * PostRun()80	//   * PersistentPostRun()81	// All functions get the same args, the arguments after the command name.82	//83	// PersistentPreRun: children of this command will inherit and execute.84	PersistentPreRun func(cmd *Command, args []string)85	// PersistentPreRunE: PersistentPreRun but returns an error.86	PersistentPreRunE func(cmd *Command, args []string) error87	// PreRun: children of this command will not inherit.88	PreRun func(cmd *Command, args []string)89	// PreRunE: PreRun but returns an error.90	PreRunE func(cmd *Command, args []string) error91	// Run: Typically the actual work function. Most commands will only implement this.92	Run func(cmd *Command, args []string)93	// RunE: Run but returns an error.94	RunE func(cmd *Command, args []string) error95	// PostRun: run after the Run command.96	PostRun func(cmd *Command, args []string)97	// PostRunE: PostRun but returns an error.98	PostRunE func(cmd *Command, args []string) error99	// PersistentPostRun: children of this command will inherit and execute after PostRun.100	PersistentPostRun func(cmd *Command, args []string)101	// PersistentPostRunE: PersistentPostRun but returns an error.102	PersistentPostRunE func(cmd *Command, args []string) error103104	// SilenceErrors is an option to quiet errors down stream.105	SilenceErrors bool106107	// SilenceUsage is an option to silence usage when an error occurs.108	SilenceUsage bool109110	// DisableFlagParsing disables the flag parsing.111	// If this is true all flags will be passed to the command as arguments.112	DisableFlagParsing bool113114	// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")115	// will be printed by generating docs for this command.116	DisableAutoGenTag bool117118	// DisableSuggestions disables the suggestions based on Levenshtein distance119	// that go along with 'unknown command' messages.120	DisableSuggestions bool121	// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.122	// Must be > 0.123	SuggestionsMinimumDistance int124125	// name is the command name, usually the executable's name.126	name string127	// commands is the list of commands supported by this program.128	commands []*Command129	// parent is a parent command for this command.130	parent *Command131	// Max lengths of commands' string lengths for use in padding.132	commandsMaxUseLen         int133	commandsMaxCommandPathLen int134	commandsMaxNameLen        int135	// commandsAreSorted defines, if command slice are sorted or not.136	commandsAreSorted bool137138	// args is actual args parsed from flags.139	args []string140	// flagErrorBuf contains all error messages from pflag.141	flagErrorBuf *bytes.Buffer142	// flags is full set of flags.143	flags *flag.FlagSet144	// pflags contains persistent flags.145	pflags *flag.FlagSet146	// lflags contains local flags.147	lflags *flag.FlagSet148	// iflags contains inherited flags.149	iflags *flag.FlagSet150	// parentsPflags is all persistent flags of cmd's parents.151	parentsPflags *flag.FlagSet152	// globNormFunc is the global normalization function153	// that we can use on every pflag set and children commands154	globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName155156	// output is an output writer defined by user.157	output io.Writer158	// usageFunc is usage func defined by user.159	usageFunc func(*Command) error160	// usageTemplate is usage template defined by user.161	usageTemplate string162	// flagErrorFunc is func defined by user and it's called when the parsing of163	// flags returns an error.164	flagErrorFunc func(*Command, error) error165	// helpTemplate is help template defined by user.166	helpTemplate string167	// helpFunc is help func defined by user.168	helpFunc func(*Command, []string)169	// helpCommand is command with usage 'help'. If it's not defined by user,170	// cobra uses default help command.171	helpCommand *Command172}173174// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden175// particularly useful when testing.176func (c *Command) SetArgs(a []string) {177	c.args = a178}179180// SetOutput sets the destination for usage and error messages.181// If output is nil, os.Stderr is used.182func (c *Command) SetOutput(output io.Writer) {183	c.output = output184}185186// SetUsageFunc sets usage function. Usage can be defined by application.187func (c *Command) SetUsageFunc(f func(*Command) error) {188	c.usageFunc = f189}190191// SetUsageTemplate sets usage template. Can be defined by Application.192func (c *Command) SetUsageTemplate(s string) {193	c.usageTemplate = s194}195196// SetFlagErrorFunc sets a function to generate an error when flag parsing197// fails.198func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {199	c.flagErrorFunc = f200}201202// SetHelpFunc sets help function. Can be defined by Application.203func (c *Command) SetHelpFunc(f func(*Command, []string)) {204	c.helpFunc = f205}206207// SetHelpCommand sets help command.208func (c *Command) SetHelpCommand(cmd *Command) {209	c.helpCommand = cmd210}211212// SetHelpTemplate sets help template to be used. Application can use it to set custom template.213func (c *Command) SetHelpTemplate(s string) {214	c.helpTemplate = s215}216217// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.218// The user should not have a cyclic dependency on commands.219func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {220	c.Flags().SetNormalizeFunc(n)221	c.PersistentFlags().SetNormalizeFunc(n)222	c.globNormFunc = n223224	for _, command := range c.commands {225		command.SetGlobalNormalizationFunc(n)226	}227}228229// OutOrStdout returns output to stdout.230func (c *Command) OutOrStdout() io.Writer {231	return c.getOut(os.Stdout)232}233234// OutOrStderr returns output to stderr235func (c *Command) OutOrStderr() io.Writer {236	return c.getOut(os.Stderr)237}238239func (c *Command) getOut(def io.Writer) io.Writer {240	if c.output != nil {241		return c.output242	}243	if c.HasParent() {244		return c.parent.getOut(def)245	}246	return def247}248249// UsageFunc returns either the function set by SetUsageFunc for this command250// or a parent, or it returns a default usage function.251func (c *Command) UsageFunc() (f func(*Command) error) {252	if c.usageFunc != nil {253		return c.usageFunc254	}255	if c.HasParent() {256		return c.Parent().UsageFunc()257	}258	return func(c *Command) error {259		c.mergePersistentFlags()260		err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)261		if err != nil {262			c.Println(err)263		}264		return err265	}266}267268// Usage puts out the usage for the command.269// Used when a user provides invalid input.270// Can be defined by user by overriding UsageFunc.271func (c *Command) Usage() error {272	return c.UsageFunc()(c)273}274275// HelpFunc returns either the function set by SetHelpFunc for this command276// or a parent, or it returns a function with default help behavior.277func (c *Command) HelpFunc() func(*Command, []string) {278	if c.helpFunc != nil {279		return c.helpFunc280	}281	if c.HasParent() {282		return c.Parent().HelpFunc()283	}284	return func(c *Command, a []string) {285		c.mergePersistentFlags()286		err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)287		if err != nil {288			c.Println(err)289		}290	}291}292293// Help puts out the help for the command.294// Used when a user calls help [command].295// Can be defined by user by overriding HelpFunc.296func (c *Command) Help() error {297	c.HelpFunc()(c, []string{})298	return nil299}300301// UsageString return usage string.302func (c *Command) UsageString() string {303	tmpOutput := c.output304	bb := new(bytes.Buffer)305	c.SetOutput(bb)306	c.Usage()307	c.output = tmpOutput308	return bb.String()309}310311// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this312// command or a parent, or it returns a function which returns the original313// error.314func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {315	if c.flagErrorFunc != nil {316		return c.flagErrorFunc317	}318319	if c.HasParent() {320		return c.parent.FlagErrorFunc()321	}322	return func(c *Command, err error) error {323		return err324	}325}326327var minUsagePadding = 25328329// UsagePadding return padding for the usage.330func (c *Command) UsagePadding() int {331	if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {332		return minUsagePadding333	}334	return c.parent.commandsMaxUseLen335}336337var minCommandPathPadding = 11338339// CommandPathPadding return padding for the command path.340func (c *Command) CommandPathPadding() int {341	if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {342		return minCommandPathPadding343	}344	return c.parent.commandsMaxCommandPathLen345}346347var minNamePadding = 11348349// NamePadding returns padding for the name.350func (c *Command) NamePadding() int {351	if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {352		return minNamePadding353	}354	return c.parent.commandsMaxNameLen355}356357// UsageTemplate returns usage template for the command.358func (c *Command) UsageTemplate() string {359	if c.usageTemplate != "" {360		return c.usageTemplate361	}362363	if c.HasParent() {364		return c.parent.UsageTemplate()365	}366	return `Usage:{{if .Runnable}}367  {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}368  {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}369370Aliases:371  {{.NameAndAliases}}{{end}}{{if .HasExample}}372373Examples:374{{.Example}}{{end}}{{if .HasAvailableSubCommands}}375376Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}377  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}378379Flags:380{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}381382Global Flags:383{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}384385Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}386  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}387388Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}389`390}391392// HelpTemplate return help template for the command.393func (c *Command) HelpTemplate() string {394	if c.helpTemplate != "" {395		return c.helpTemplate396	}397398	if c.HasParent() {399		return c.parent.HelpTemplate()400	}401	return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}402403{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`404}405406func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {407	flag := fs.Lookup(name)408	if flag == nil {409		return false410	}411	return flag.NoOptDefVal != ""412}413414func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {415	if len(name) == 0 {416		return false417	}418419	flag := fs.ShorthandLookup(name[:1])420	if flag == nil {421		return false422	}423	return flag.NoOptDefVal != ""424}425426func stripFlags(args []string, c *Command) []string {427	if len(args) == 0 {428		return args429	}430	c.mergePersistentFlags()431432	commands := []string{}433	flags := c.Flags()434435Loop:436	for len(args) > 0 {437		s := args[0]438		args = args[1:]439		switch {440		case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):441			// If '--flag arg' then442			// delete arg from args.443			fallthrough // (do the same as below)444		case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):445			// If '-f arg' then446			// delete 'arg' from args or break the loop if len(args) <= 1.447			if len(args) <= 1 {448				break Loop449			} else {450				args = args[1:]451				continue452			}453		case s != "" && !strings.HasPrefix(s, "-"):454			commands = append(commands, s)455		}456	}457458	return commands459}460461// argsMinusFirstX removes only the first x from args.  Otherwise, commands that look like462// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).463func argsMinusFirstX(args []string, x string) []string {464	for i, y := range args {465		if x == y {466			ret := []string{}467			ret = append(ret, args[:i]...)468			ret = append(ret, args[i+1:]...)469			return ret470		}471	}472	return args473}474475// Find the target command given the args and command tree476// Meant to be run on the highest node. Only searches down.477func (c *Command) Find(args []string) (*Command, []string, error) {478	if c == nil {479		return nil, nil, fmt.Errorf("Called find() on a nil Command")480	}481482	var innerfind func(*Command, []string) (*Command, []string)483484	innerfind = func(c *Command, innerArgs []string) (*Command, []string) {485		argsWOflags := stripFlags(innerArgs, c)486		if len(argsWOflags) == 0 {487			return c, innerArgs488		}489		nextSubCmd := argsWOflags[0]490		matches := make([]*Command, 0)491		for _, cmd := range c.commands {492			if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match493				return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))494			}495			if EnablePrefixMatching {496				if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match497					matches = append(matches, cmd)498				}499				for _, x := range cmd.Aliases {500					if strings.HasPrefix(x, nextSubCmd) {501						matches = append(matches, cmd)502					}503				}504			}505		}506507		// only accept a single prefix match - multiple matches would be ambiguous508		if len(matches) == 1 {509			return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))510		}511512		return c, innerArgs513	}514515	commandFound, a := innerfind(c, args)516	argsWOflags := stripFlags(a, commandFound)517518	// no subcommand, always take args519	if !commandFound.HasSubCommands() {520		return commandFound, a, nil521	}522523	// root command with subcommands, do subcommand checking524	if commandFound == c && len(argsWOflags) > 0 {525		suggestionsString := ""526		if !c.DisableSuggestions {527			if c.SuggestionsMinimumDistance <= 0 {528				c.SuggestionsMinimumDistance = 2529			}530			if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {531				suggestionsString += "\n\nDid you mean this?\n"532				for _, s := range suggestions {533					suggestionsString += fmt.Sprintf("\t%v\n", s)534				}535			}536		}537		return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)538	}539540	return commandFound, a, nil541}542543// SuggestionsFor provides suggestions for the typedName.544func (c *Command) SuggestionsFor(typedName string) []string {545	suggestions := []string{}546	for _, cmd := range c.commands {547		if cmd.IsAvailableCommand() {548			levenshteinDistance := ld(typedName, cmd.Name(), true)549			suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance550			suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))551			if suggestByLevenshtein || suggestByPrefix {552				suggestions = append(suggestions, cmd.Name())553			}554			for _, explicitSuggestion := range cmd.SuggestFor {555				if strings.EqualFold(typedName, explicitSuggestion) {556					suggestions = append(suggestions, cmd.Name())557				}558			}559		}560	}561	return suggestions562}563564// VisitParents visits all parents of the command and invokes fn on each parent.565func (c *Command) VisitParents(fn func(*Command)) {566	if c.HasParent() {567		fn(c.Parent())568		c.Parent().VisitParents(fn)569	}570}571572// Root finds root command.573func (c *Command) Root() *Command {574	if c.HasParent() {575		return c.Parent().Root()576	}577	return c578}579580// ArgsLenAtDash will return the length of f.Args at the moment when a -- was581// found during arg parsing. This allows your program to know which args were582// before the -- and which came after. (Description from583// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).584func (c *Command) ArgsLenAtDash() int {585	return c.Flags().ArgsLenAtDash()586}587588func (c *Command) execute(a []string) (err error) {589	if c == nil {590		return fmt.Errorf("Called Execute() on a nil Command")591	}592593	if len(c.Deprecated) > 0 {594		c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)595	}596597	// initialize help flag as the last point possible to allow for user598	// overriding599	c.InitDefaultHelpFlag()600601	err = c.ParseFlags(a)602	if err != nil {603		return c.FlagErrorFunc()(c, err)604	}605606	// If help is called, regardless of other flags, return we want help.607	// Also say we need help if the command isn't runnable.608	helpVal, err := c.Flags().GetBool("help")609	if err != nil {610		// should be impossible to get here as we always declare a help611		// flag in InitDefaultHelpFlag()612		c.Println("\"help\" flag declared as non-bool. Please correct your code")613		return err614	}615616	if helpVal || !c.Runnable() {617		return flag.ErrHelp618	}619620	c.preRun()621622	argWoFlags := c.Flags().Args()623	if c.DisableFlagParsing {624		argWoFlags = a625	}626627	for p := c; p != nil; p = p.Parent() {628		if p.PersistentPreRunE != nil {629			if err := p.PersistentPreRunE(c, argWoFlags); err != nil {630				return err631			}632			break633		} else if p.PersistentPreRun != nil {634			p.PersistentPreRun(c, argWoFlags)635			break636		}637	}638	if c.PreRunE != nil {639		if err := c.PreRunE(c, argWoFlags); err != nil {640			return err641		}642	} else if c.PreRun != nil {643		c.PreRun(c, argWoFlags)644	}645646	if c.RunE != nil {647		if err := c.RunE(c, argWoFlags); err != nil {648			return err649		}650	} else {651		c.Run(c, argWoFlags)652	}653	if c.PostRunE != nil {654		if err := c.PostRunE(c, argWoFlags); err != nil {655			return err656		}657	} else if c.PostRun != nil {658		c.PostRun(c, argWoFlags)659	}660	for p := c; p != nil; p = p.Parent() {661		if p.PersistentPostRunE != nil {662			if err := p.PersistentPostRunE(c, argWoFlags); err != nil {663				return err664			}665			break666		} else if p.PersistentPostRun != nil {667			p.PersistentPostRun(c, argWoFlags)668			break669		}670	}671672	return nil673}674675func (c *Command) preRun() {676	for _, x := range initializers {677		x()678	}679}680681// Execute Call execute to use the args (os.Args[1:] by default)682// and run through the command tree finding appropriate matches683// for commands and then corresponding flags.684func (c *Command) Execute() error {685	_, err := c.ExecuteC()686	return err687}688689// ExecuteC executes the command.690func (c *Command) ExecuteC() (cmd *Command, err error) {691	// Regardless of what command execute is called on, run on Root only692	if c.HasParent() {693		return c.Root().ExecuteC()694	}695696	// windows hook697	if preExecHookFn != nil {698		preExecHookFn(c)699	}700701	// initialize help as the last point possible to allow for user702	// overriding703	c.initHelpCmd()704705	var args []string706707	// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155708	if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {709		args = os.Args[1:]710	} else {711		args = c.args712	}713714	cmd, flags, err := c.Find(args)715	if err != nil {716		// If found parse to a subcommand and then failed, talk about the subcommand717		if cmd != nil {718			c = cmd719		}720		if !c.SilenceErrors {721			c.Println("Error:", err.Error())722			c.Printf("Run '%v --help' for usage.\n", c.CommandPath())723		}724		return c, err725	}726	err = cmd.execute(flags)727	if err != nil {728		// Always show help if requested, even if SilenceErrors is in729		// effect730		if err == flag.ErrHelp {731			cmd.HelpFunc()(cmd, args)732			return cmd, nil733		}734735		// If root command has SilentErrors flagged,736		// all subcommands should respect it737		if !cmd.SilenceErrors && !c.SilenceErrors {738			c.Println("Error:", err.Error())739		}740741		// If root command has SilentUsage flagged,742		// all subcommands should respect it743		if !cmd.SilenceUsage && !c.SilenceUsage {744			c.Println(cmd.UsageString())745		}746		return cmd, err747	}748	return cmd, nil749}750751// InitDefaultHelpFlag adds default help flag to c.752// It is called automatically by executing the c or by calling help and usage.753// If c already has help flag, it will do nothing.754func (c *Command) InitDefaultHelpFlag() {755	c.mergePersistentFlags()756	if c.Flags().Lookup("help") == nil {757		usage := "help for "758		if c.Name() == "" {759			usage += "this command"760		} else {761			usage += c.Name()762		}763		c.Flags().BoolP("help", "h", false, usage)764	}765}766767func (c *Command) initHelpCmd() {768	if c.helpCommand == nil {769		if !c.HasSubCommands() {770			return771		}772773		c.helpCommand = &Command{774			Use:   "help [command]",775			Short: "Help about any command",776			Long: `Help provides help for any command in the application.777    Simply type ` + c.Name() + ` help [path to command] for full details.`,778			PersistentPreRun:  func(cmd *Command, args []string) {},779			PersistentPostRun: func(cmd *Command, args []string) {},780781			Run: func(c *Command, args []string) {782				cmd, _, e := c.Root().Find(args)783				if cmd == nil || e != nil {784					c.Printf("Unknown help topic %#q\n", args)785					c.Root().Usage()786				} else {787					cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown788					cmd.Help()789				}790			},791		}792	}793	c.RemoveCommand(c.helpCommand)794	c.AddCommand(c.helpCommand)795}796797// ResetCommands used for testing.798func (c *Command) ResetCommands() {799	c.commands = nil800	c.helpCommand = nil801	c.parentsPflags = nil802}803804// Sorts commands by their names.805type commandSorterByName []*Command806807func (c commandSorterByName) Len() int           { return len(c) }808func (c commandSorterByName) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }809func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }810811// Commands returns a sorted slice of child commands.812func (c *Command) Commands() []*Command {813	// do not sort commands if it already sorted or sorting was disabled814	if EnableCommandSorting && !c.commandsAreSorted {815		sort.Sort(commandSorterByName(c.commands))816		c.commandsAreSorted = true817	}818	return c.commands819}820821// AddCommand adds one or more commands to this parent command.822func (c *Command) AddCommand(cmds ...*Command) {823	for i, x := range cmds {824		if cmds[i] == c {825			panic("Command can't be a child of itself")826		}827		cmds[i].parent = c828		// update max lengths829		usageLen := len(x.Use)830		if usageLen > c.commandsMaxUseLen {831			c.commandsMaxUseLen = usageLen832		}833		commandPathLen := len(x.CommandPath())834		if commandPathLen > c.commandsMaxCommandPathLen {835			c.commandsMaxCommandPathLen = commandPathLen836		}837		nameLen := len(x.Name())838		if nameLen > c.commandsMaxNameLen {839			c.commandsMaxNameLen = nameLen840		}841		// If global normalization function exists, update all children842		if c.globNormFunc != nil {843			x.SetGlobalNormalizationFunc(c.globNormFunc)844		}845		c.commands = append(c.commands, x)846		c.commandsAreSorted = false847	}848}849850// RemoveCommand removes one or more commands from a parent command.851func (c *Command) RemoveCommand(cmds ...*Command) {852	commands := []*Command{}853main:854	for _, command := range c.commands {855		for _, cmd := range cmds {856			if command == cmd {857				command.parent = nil858				continue main859			}860		}861		commands = append(commands, command)862	}863	c.commands = commands864	// recompute all lengths865	c.commandsMaxUseLen = 0866	c.commandsMaxCommandPathLen = 0867	c.commandsMaxNameLen = 0868	for _, command := range c.commands {869		usageLen := len(command.Use)870		if usageLen > c.commandsMaxUseLen {871			c.commandsMaxUseLen = usageLen872		}873		commandPathLen := len(command.CommandPath())874		if commandPathLen > c.commandsMaxCommandPathLen {875			c.commandsMaxCommandPathLen = commandPathLen876		}877		nameLen := len(command.Name())878		if nameLen > c.commandsMaxNameLen {879			c.commandsMaxNameLen = nameLen880		}881	}882}883884// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.885func (c *Command) Print(i ...interface{}) {886	fmt.Fprint(c.OutOrStderr(), i...)887}888889// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.890func (c *Command) Println(i ...interface{}) {891	c.Print(fmt.Sprintln(i...))892}893894// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.895func (c *Command) Printf(format string, i ...interface{}) {896	c.Print(fmt.Sprintf(format, i...))897}898899// CommandPath returns the full path to this command.900func (c *Command) CommandPath() string {901	if c.HasParent() {902		return c.Parent().CommandPath() + " " + c.Name()903	}904	return c.Name()905}906907// UseLine puts out the full usage for a given command (including parents).908func (c *Command) UseLine() string {909	var useline string910	if c.HasParent() {911		useline = c.parent.CommandPath() + " " + c.Use912	} else {913		useline = c.Use914	}915	if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {916		useline += " [flags]"917	}918	return useline919}920921// DebugFlags used to determine which flags have been assigned to which commands922// and which persist.923func (c *Command) DebugFlags() {924	c.Println("DebugFlags called on", c.Name())925	var debugflags func(*Command)926927	debugflags = func(x *Command) {928		if x.HasFlags() || x.HasPersistentFlags() {929			c.Println(x.Name())930		}931		if x.HasFlags() {932			x.flags.VisitAll(func(f *flag.Flag) {933				if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {934					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [LP]")935				} else {936					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")937				}938			})939		}940		if x.HasPersistentFlags() {941			x.pflags.VisitAll(func(f *flag.Flag) {942				if x.HasFlags() {943					if x.flags.Lookup(f.Name) == nil {944						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")945					}946				} else {947					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")948				}949			})950		}951		c.Println(x.flagErrorBuf)952		if x.HasSubCommands() {953			for _, y := range x.commands {954				debugflags(y)955			}956		}957	}958959	debugflags(c)960}961962// Name returns the command's name: the first word in the use line.963func (c *Command) Name() string {964	if c.name == "" {965		name := c.Use966		i := strings.Index(name, " ")967		if i >= 0 {968			name = name[:i]969		}970		c.name = name971	}972	return c.name973}974975// HasAlias determines if a given string is an alias of the command.976func (c *Command) HasAlias(s string) bool {977	for _, a := range c.Aliases {978		if a == s {979			return true980		}981	}982	return false983}984985// NameAndAliases returns string containing name and all aliases986func (c *Command) NameAndAliases() string {987	return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")988}989990// HasExample determines if the command has example.991func (c *Command) HasExample() bool {992	return len(c.Example) > 0993}994995// Runnable determines if the command is itself runnable.996func (c *Command) Runnable() bool {997	return c.Run != nil || c.RunE != nil998}9991000// HasSubCommands determines if the command has children commands.1001func (c *Command) HasSubCommands() bool {1002	return len(c.commands) > 01003}10041005// IsAvailableCommand determines if a command is available as a non-help command1006// (this includes all non deprecated/hidden commands).1007func (c *Command) IsAvailableCommand() bool {1008	if len(c.Deprecated) != 0 || c.Hidden {1009		return false1010	}10111012	if c.HasParent() && c.Parent().helpCommand == c {1013		return false1014	}10151016	if c.Runnable() || c.HasAvailableSubCommands() {1017		return true1018	}10191020	return false1021}10221023// IsAdditionalHelpTopicCommand determines if a command is an additional1024// help topic command; additional help topic command is determined by the1025// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1026// are runnable/hidden/deprecated.1027// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1028func (c *Command) IsAdditionalHelpTopicCommand() bool {1029	// if a command is runnable, deprecated, or hidden it is not a 'help' command1030	if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1031		return false1032	}10331034	// if any non-help sub commands are found, the command is not a 'help' command1035	for _, sub := range c.commands {1036		if !sub.IsAdditionalHelpTopicCommand() {1037			return false1038		}1039	}10401041	// the command either has no sub commands, or no non-help sub commands1042	return true1043}10441045// HasHelpSubCommands determines if a command has any available 'help' sub commands1046// that need to be shown in the usage/help default template under 'additional help1047// topics'.1048func (c *Command) HasHelpSubCommands() bool {1049	// return true on the first found available 'help' sub command1050	for _, sub := range c.commands {1051		if sub.IsAdditionalHelpTopicCommand() {1052			return true1053		}1054	}10551056	// the command either has no sub commands, or no available 'help' sub commands1057	return false1058}10591060// HasAvailableSubCommands determines if a command has available sub commands that1061// need to be shown in the usage/help default template under 'available commands'.1062func (c *Command) HasAvailableSubCommands() bool {1063	// return true on the first found available (non deprecated/help/hidden)1064	// sub command1065	for _, sub := range c.commands {1066		if sub.IsAvailableCommand() {1067			return true1068		}1069	}10701071	// the command either has no sub comamnds, or no available (non deprecated/help/hidden)1072	// sub commands1073	return false1074}10751076// HasParent determines if the command is a child command.1077func (c *Command) HasParent() bool {1078	return c.parent != nil1079}10801081// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists.1082func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1083	return c.globNormFunc1084}10851086// Flags returns the complete FlagSet that applies1087// to this command (local and persistent declared here and by all parents).1088func (c *Command) Flags() *flag.FlagSet {1089	if c.flags == nil {1090		c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1091		if c.flagErrorBuf == nil {1092			c.flagErrorBuf = new(bytes.Buffer)1093		}1094		c.flags.SetOutput(c.flagErrorBuf)1095	}10961097	return c.flags1098}10991100// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1101func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1102	persistentFlags := c.PersistentFlags()11031104	out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1105	c.LocalFlags().VisitAll(func(f *flag.Flag) {1106		if persistentFlags.Lookup(f.Name) == nil {1107			out.AddFlag(f)1108		}1109	})1110	return out1111}11121113// LocalFlags returns the local FlagSet specifically set in the current command.1114func (c *Command) LocalFlags() *flag.FlagSet {1115	c.mergePersistentFlags()11161117	if c.lflags == nil {1118		c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1119		if c.flagErrorBuf == nil {1120			c.flagErrorBuf = new(bytes.Buffer)1121		}1122		c.lflags.SetOutput(c.flagErrorBuf)1123	}1124	c.lflags.SortFlags = c.Flags().SortFlags11251126	addToLocal := func(f *flag.Flag) {1127		if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1128			c.lflags.AddFlag(f)1129		}1130	}1131	c.Flags().VisitAll(addToLocal)1132	c.PersistentFlags().VisitAll(addToLocal)1133	return c.lflags1134}11351136// InheritedFlags returns all flags which were inherited from parents commands.1137func (c *Command) InheritedFlags() *flag.FlagSet {1138	c.mergePersistentFlags()11391140	if c.iflags == nil {1141		c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1142		if c.flagErrorBuf == nil {1143			c.flagErrorBuf = new(bytes.Buffer)1144		}1145		c.iflags.SetOutput(c.flagErrorBuf)1146	}11471148	local := c.LocalFlags()1149	c.parentsPflags.VisitAll(func(f *flag.Flag) {1150		if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1151			c.iflags.AddFlag(f)1152		}1153	})1154	return c.iflags1155}11561157// NonInheritedFlags returns all flags which were not inherited from parent commands.1158func (c *Command) NonInheritedFlags() *flag.FlagSet {1159	return c.LocalFlags()1160}11611162// PersistentFlags returns the persistent FlagSet specifically set in the current command.1163func (c *Command) PersistentFlags() *flag.FlagSet {1164	if c.pflags == nil {1165		c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1166		if c.flagErrorBuf == nil {1167			c.flagErrorBuf = new(bytes.Buffer)1168		}1169		c.pflags.SetOutput(c.flagErrorBuf)1170	}1171	return c.pflags1172}11731174// ResetFlags is used in testing.1175func (c *Command) ResetFlags() {1176	c.flagErrorBuf = new(bytes.Buffer)1177	c.flagErrorBuf.Reset()1178	c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1179	c.flags.SetOutput(c.flagErrorBuf)1180	c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1181	c.pflags.SetOutput(c.flagErrorBuf)1182}11831184// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1185func (c *Command) HasFlags() bool {1186	return c.Flags().HasFlags()1187}11881189// HasPersistentFlags checks if the command contains persistent flags.1190func (c *Command) HasPersistentFlags() bool {1191	return c.PersistentFlags().HasFlags()1192}11931194// HasLocalFlags checks if the command has flags specifically declared locally.1195func (c *Command) HasLocalFlags() bool {1196	return c.LocalFlags().HasFlags()1197}11981199// HasInheritedFlags checks if the command has flags inherited from its parent command.1200func (c *Command) HasInheritedFlags() bool {1201	return c.InheritedFlags().HasFlags()1202}12031204// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1205// structure) which are not hidden or deprecated.1206func (c *Command) HasAvailableFlags() bool {1207	return c.Flags().HasAvailableFlags()1208}12091210// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1211func (c *Command) HasAvailablePersistentFlags() bool {1212	return c.PersistentFlags().HasAvailableFlags()1213}12141215// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1216// or deprecated.1217func (c *Command) HasAvailableLocalFlags() bool {1218	return c.LocalFlags().HasAvailableFlags()1219}12201221// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1222// not hidden or deprecated.1223func (c *Command) HasAvailableInheritedFlags() bool {1224	return c.InheritedFlags().HasAvailableFlags()1225}12261227// Flag climbs up the command tree looking for matching flag.1228func (c *Command) Flag(name string) (flag *flag.Flag) {1229	flag = c.Flags().Lookup(name)12301231	if flag == nil {1232		flag = c.persistentFlag(name)1233	}12341235	return1236}12371238// Recursively find matching persistent flag.1239func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1240	if c.HasPersistentFlags() {1241		flag = c.PersistentFlags().Lookup(name)1242	}12431244	if flag == nil {1245		c.updateParentsPflags()1246		flag = c.parentsPflags.Lookup(name)1247	}1248	return1249}12501251// ParseFlags parses persistent flag tree and local flags.1252func (c *Command) ParseFlags(args []string) (err error) {1253	if c.DisableFlagParsing {1254		return nil1255	}1256	c.mergePersistentFlags()1257	err = c.Flags().Parse(args)1258	return1259}12601261// Parent returns a commands parent command.1262func (c *Command) Parent() *Command {1263	return c.parent1264}12651266// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1267// and adds missing persistent flags of all parents.1268func (c *Command) mergePersistentFlags() {1269	c.updateParentsPflags()1270	c.Flags().AddFlagSet(c.PersistentFlags())1271	c.Flags().AddFlagSet(c.parentsPflags)1272}12731274// updateParentsPflags updates c.parentsPflags by adding1275// new persistent flags of all parents.1276// If c.parentsPflags == nil, it makes new.1277func (c *Command) updateParentsPflags() {1278	if c.parentsPflags == nil {1279		c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1280		c.parentsPflags.SetOutput(c.flagErrorBuf)1281		c.parentsPflags.SortFlags = false1282	}12831284	c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)12851286	c.VisitParents(func(parent *Command) {1287		c.parentsPflags.AddFlagSet(parent.PersistentFlags())1288	})1289}