Skip to content
Myr

command.go

This file

Path

command.go

1,664 lines · 46.4 KiB · Go

Last changed by

fix typos (#1274)namusyakabefore adoption7df62f7

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	"context"21	"fmt"22	"io"23	"os"24	"path/filepath"25	"sort"26	"strings"2728	flag "github.com/spf13/pflag"29)3031// FParseErrWhitelist configures Flag parse errors to be ignored32type FParseErrWhitelist flag.ParseErrorsWhitelist3334// Command is just that, a command for your application.35// E.g.  'go run ...' - 'run' is the command. Cobra requires36// you to define the usage and description as part of your command37// definition to ensure usability.38type Command struct {39	// Use is the one-line usage message.40	// Recommended syntax is as follow:41	//   [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.42	//   ... indicates that you can specify multiple values for the previous argument.43	//   |   indicates mutually exclusive information. You can use the argument to the left of the separator or the44	//       argument to the right of the separator. You cannot use both arguments in a single use of the command.45	//   { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are46	//       optional, they are enclosed in brackets ([ ]).47	// Example: add [-F file | -D dir]... [-f format] profile48	Use string4950	// Aliases is an array of aliases that can be used instead of the first word in Use.51	Aliases []string5253	// SuggestFor is an array of command names for which this command will be suggested -54	// similar to aliases but only suggests.55	SuggestFor []string5657	// Short is the short description shown in the 'help' output.58	Short string5960	// Long is the long message shown in the 'help <this-command>' output.61	Long string6263	// Example is examples of how to use the command.64	Example string6566	// ValidArgs is list of all valid non-flag arguments that are accepted in bash completions67	ValidArgs []string68	// ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.69	// It is a dynamic version of using ValidArgs.70	// Only one of ValidArgs and ValidArgsFunction can be used for a command.71	ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)7273	// Expected arguments74	Args PositionalArgs7576	// ArgAliases is List of aliases for ValidArgs.77	// These are not suggested to the user in the bash completion,78	// but accepted if entered manually.79	ArgAliases []string8081	// BashCompletionFunction is custom functions used by the bash autocompletion generator.82	BashCompletionFunction string8384	// Deprecated defines, if this command is deprecated and should print this string when used.85	Deprecated string8687	// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.88	Hidden bool8990	// Annotations are key/value pairs that can be used by applications to identify or91	// group commands.92	Annotations map[string]string9394	// Version defines the version for this command. If this value is non-empty and the command does not95	// define a "version" flag, a "version" boolean flag will be added to the command and, if specified,96	// will print content of the "Version" variable. A shorthand "v" flag will also be added if the97	// command does not define one.98	Version string99100	// The *Run functions are executed in the following order:101	//   * PersistentPreRun()102	//   * PreRun()103	//   * Run()104	//   * PostRun()105	//   * PersistentPostRun()106	// All functions get the same args, the arguments after the command name.107	//108	// PersistentPreRun: children of this command will inherit and execute.109	PersistentPreRun func(cmd *Command, args []string)110	// PersistentPreRunE: PersistentPreRun but returns an error.111	PersistentPreRunE func(cmd *Command, args []string) error112	// PreRun: children of this command will not inherit.113	PreRun func(cmd *Command, args []string)114	// PreRunE: PreRun but returns an error.115	PreRunE func(cmd *Command, args []string) error116	// Run: Typically the actual work function. Most commands will only implement this.117	Run func(cmd *Command, args []string)118	// RunE: Run but returns an error.119	RunE func(cmd *Command, args []string) error120	// PostRun: run after the Run command.121	PostRun func(cmd *Command, args []string)122	// PostRunE: PostRun but returns an error.123	PostRunE func(cmd *Command, args []string) error124	// PersistentPostRun: children of this command will inherit and execute after PostRun.125	PersistentPostRun func(cmd *Command, args []string)126	// PersistentPostRunE: PersistentPostRun but returns an error.127	PersistentPostRunE func(cmd *Command, args []string) error128129	// SilenceErrors is an option to quiet errors down stream.130	SilenceErrors bool131132	// SilenceUsage is an option to silence usage when an error occurs.133	SilenceUsage bool134135	// DisableFlagParsing disables the flag parsing.136	// If this is true all flags will be passed to the command as arguments.137	DisableFlagParsing bool138139	// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")140	// will be printed by generating docs for this command.141	DisableAutoGenTag bool142143	// DisableFlagsInUseLine will disable the addition of [flags] to the usage144	// line of a command when printing help or generating docs145	DisableFlagsInUseLine bool146147	// DisableSuggestions disables the suggestions based on Levenshtein distance148	// that go along with 'unknown command' messages.149	DisableSuggestions bool150	// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.151	// Must be > 0.152	SuggestionsMinimumDistance int153154	// TraverseChildren parses flags on all parents before executing child command.155	TraverseChildren bool156157	// FParseErrWhitelist flag parse errors to be ignored158	FParseErrWhitelist FParseErrWhitelist159160	ctx context.Context161162	// commands is the list of commands supported by this program.163	commands []*Command164	// parent is a parent command for this command.165	parent *Command166	// Max lengths of commands' string lengths for use in padding.167	commandsMaxUseLen         int168	commandsMaxCommandPathLen int169	commandsMaxNameLen        int170	// commandsAreSorted defines, if command slice are sorted or not.171	commandsAreSorted bool172	// commandCalledAs is the name or alias value used to call this command.173	commandCalledAs struct {174		name   string175		called bool176	}177178	// args is actual args parsed from flags.179	args []string180	// flagErrorBuf contains all error messages from pflag.181	flagErrorBuf *bytes.Buffer182	// flags is full set of flags.183	flags *flag.FlagSet184	// pflags contains persistent flags.185	pflags *flag.FlagSet186	// lflags contains local flags.187	lflags *flag.FlagSet188	// iflags contains inherited flags.189	iflags *flag.FlagSet190	// parentsPflags is all persistent flags of cmd's parents.191	parentsPflags *flag.FlagSet192	// globNormFunc is the global normalization function193	// that we can use on every pflag set and children commands194	globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName195196	// usageFunc is usage func defined by user.197	usageFunc func(*Command) error198	// usageTemplate is usage template defined by user.199	usageTemplate string200	// flagErrorFunc is func defined by user and it's called when the parsing of201	// flags returns an error.202	flagErrorFunc func(*Command, error) error203	// helpTemplate is help template defined by user.204	helpTemplate string205	// helpFunc is help func defined by user.206	helpFunc func(*Command, []string)207	// helpCommand is command with usage 'help'. If it's not defined by user,208	// cobra uses default help command.209	helpCommand *Command210	// versionTemplate is the version template defined by user.211	versionTemplate string212213	// inReader is a reader defined by the user that replaces stdin214	inReader io.Reader215	// outWriter is a writer defined by the user that replaces stdout216	outWriter io.Writer217	// errWriter is a writer defined by the user that replaces stderr218	errWriter io.Writer219}220221// Context returns underlying command context. If command wasn't222// executed with ExecuteContext Context returns Background context.223func (c *Command) Context() context.Context {224	return c.ctx225}226227// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden228// particularly useful when testing.229func (c *Command) SetArgs(a []string) {230	c.args = a231}232233// SetOutput sets the destination for usage and error messages.234// If output is nil, os.Stderr is used.235// Deprecated: Use SetOut and/or SetErr instead236func (c *Command) SetOutput(output io.Writer) {237	c.outWriter = output238	c.errWriter = output239}240241// SetOut sets the destination for usage messages.242// If newOut is nil, os.Stdout is used.243func (c *Command) SetOut(newOut io.Writer) {244	c.outWriter = newOut245}246247// SetErr sets the destination for error messages.248// If newErr is nil, os.Stderr is used.249func (c *Command) SetErr(newErr io.Writer) {250	c.errWriter = newErr251}252253// SetIn sets the source for input data254// If newIn is nil, os.Stdin is used.255func (c *Command) SetIn(newIn io.Reader) {256	c.inReader = newIn257}258259// SetUsageFunc sets usage function. Usage can be defined by application.260func (c *Command) SetUsageFunc(f func(*Command) error) {261	c.usageFunc = f262}263264// SetUsageTemplate sets usage template. Can be defined by Application.265func (c *Command) SetUsageTemplate(s string) {266	c.usageTemplate = s267}268269// SetFlagErrorFunc sets a function to generate an error when flag parsing270// fails.271func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {272	c.flagErrorFunc = f273}274275// SetHelpFunc sets help function. Can be defined by Application.276func (c *Command) SetHelpFunc(f func(*Command, []string)) {277	c.helpFunc = f278}279280// SetHelpCommand sets help command.281func (c *Command) SetHelpCommand(cmd *Command) {282	c.helpCommand = cmd283}284285// SetHelpTemplate sets help template to be used. Application can use it to set custom template.286func (c *Command) SetHelpTemplate(s string) {287	c.helpTemplate = s288}289290// SetVersionTemplate sets version template to be used. Application can use it to set custom template.291func (c *Command) SetVersionTemplate(s string) {292	c.versionTemplate = s293}294295// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.296// The user should not have a cyclic dependency on commands.297func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {298	c.Flags().SetNormalizeFunc(n)299	c.PersistentFlags().SetNormalizeFunc(n)300	c.globNormFunc = n301302	for _, command := range c.commands {303		command.SetGlobalNormalizationFunc(n)304	}305}306307// OutOrStdout returns output to stdout.308func (c *Command) OutOrStdout() io.Writer {309	return c.getOut(os.Stdout)310}311312// OutOrStderr returns output to stderr313func (c *Command) OutOrStderr() io.Writer {314	return c.getOut(os.Stderr)315}316317// ErrOrStderr returns output to stderr318func (c *Command) ErrOrStderr() io.Writer {319	return c.getErr(os.Stderr)320}321322// InOrStdin returns input to stdin323func (c *Command) InOrStdin() io.Reader {324	return c.getIn(os.Stdin)325}326327func (c *Command) getOut(def io.Writer) io.Writer {328	if c.outWriter != nil {329		return c.outWriter330	}331	if c.HasParent() {332		return c.parent.getOut(def)333	}334	return def335}336337func (c *Command) getErr(def io.Writer) io.Writer {338	if c.errWriter != nil {339		return c.errWriter340	}341	if c.HasParent() {342		return c.parent.getErr(def)343	}344	return def345}346347func (c *Command) getIn(def io.Reader) io.Reader {348	if c.inReader != nil {349		return c.inReader350	}351	if c.HasParent() {352		return c.parent.getIn(def)353	}354	return def355}356357// UsageFunc returns either the function set by SetUsageFunc for this command358// or a parent, or it returns a default usage function.359func (c *Command) UsageFunc() (f func(*Command) error) {360	if c.usageFunc != nil {361		return c.usageFunc362	}363	if c.HasParent() {364		return c.Parent().UsageFunc()365	}366	return func(c *Command) error {367		c.mergePersistentFlags()368		err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)369		if err != nil {370			c.PrintErrln(err)371		}372		return err373	}374}375376// Usage puts out the usage for the command.377// Used when a user provides invalid input.378// Can be defined by user by overriding UsageFunc.379func (c *Command) Usage() error {380	return c.UsageFunc()(c)381}382383// HelpFunc returns either the function set by SetHelpFunc for this command384// or a parent, or it returns a function with default help behavior.385func (c *Command) HelpFunc() func(*Command, []string) {386	if c.helpFunc != nil {387		return c.helpFunc388	}389	if c.HasParent() {390		return c.Parent().HelpFunc()391	}392	return func(c *Command, a []string) {393		c.mergePersistentFlags()394		// The help should be sent to stdout395		// See https://github.com/spf13/cobra/issues/1002396		err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)397		if err != nil {398			c.PrintErrln(err)399		}400	}401}402403// Help puts out the help for the command.404// Used when a user calls help [command].405// Can be defined by user by overriding HelpFunc.406func (c *Command) Help() error {407	c.HelpFunc()(c, []string{})408	return nil409}410411// UsageString returns usage string.412func (c *Command) UsageString() string {413	// Storing normal writers414	tmpOutput := c.outWriter415	tmpErr := c.errWriter416417	bb := new(bytes.Buffer)418	c.outWriter = bb419	c.errWriter = bb420421	c.Usage()422423	// Setting things back to normal424	c.outWriter = tmpOutput425	c.errWriter = tmpErr426427	return bb.String()428}429430// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this431// command or a parent, or it returns a function which returns the original432// error.433func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {434	if c.flagErrorFunc != nil {435		return c.flagErrorFunc436	}437438	if c.HasParent() {439		return c.parent.FlagErrorFunc()440	}441	return func(c *Command, err error) error {442		return err443	}444}445446var minUsagePadding = 25447448// UsagePadding return padding for the usage.449func (c *Command) UsagePadding() int {450	if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {451		return minUsagePadding452	}453	return c.parent.commandsMaxUseLen454}455456var minCommandPathPadding = 11457458// CommandPathPadding return padding for the command path.459func (c *Command) CommandPathPadding() int {460	if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {461		return minCommandPathPadding462	}463	return c.parent.commandsMaxCommandPathLen464}465466var minNamePadding = 11467468// NamePadding returns padding for the name.469func (c *Command) NamePadding() int {470	if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {471		return minNamePadding472	}473	return c.parent.commandsMaxNameLen474}475476// UsageTemplate returns usage template for the command.477func (c *Command) UsageTemplate() string {478	if c.usageTemplate != "" {479		return c.usageTemplate480	}481482	if c.HasParent() {483		return c.parent.UsageTemplate()484	}485	return `Usage:{{if .Runnable}}486  {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}487  {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}488489Aliases:490  {{.NameAndAliases}}{{end}}{{if .HasExample}}491492Examples:493{{.Example}}{{end}}{{if .HasAvailableSubCommands}}494495Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}496  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}497498Flags:499{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}500501Global Flags:502{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}503504Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}505  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}506507Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}508`509}510511// HelpTemplate return help template for the command.512func (c *Command) HelpTemplate() string {513	if c.helpTemplate != "" {514		return c.helpTemplate515	}516517	if c.HasParent() {518		return c.parent.HelpTemplate()519	}520	return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}521522{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`523}524525// VersionTemplate return version template for the command.526func (c *Command) VersionTemplate() string {527	if c.versionTemplate != "" {528		return c.versionTemplate529	}530531	if c.HasParent() {532		return c.parent.VersionTemplate()533	}534	return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}535`536}537538func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {539	flag := fs.Lookup(name)540	if flag == nil {541		return false542	}543	return flag.NoOptDefVal != ""544}545546func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {547	if len(name) == 0 {548		return false549	}550551	flag := fs.ShorthandLookup(name[:1])552	if flag == nil {553		return false554	}555	return flag.NoOptDefVal != ""556}557558func stripFlags(args []string, c *Command) []string {559	if len(args) == 0 {560		return args561	}562	c.mergePersistentFlags()563564	commands := []string{}565	flags := c.Flags()566567Loop:568	for len(args) > 0 {569		s := args[0]570		args = args[1:]571		switch {572		case s == "--":573			// "--" terminates the flags574			break Loop575		case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):576			// If '--flag arg' then577			// delete arg from args.578			fallthrough // (do the same as below)579		case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):580			// If '-f arg' then581			// delete 'arg' from args or break the loop if len(args) <= 1.582			if len(args) <= 1 {583				break Loop584			} else {585				args = args[1:]586				continue587			}588		case s != "" && !strings.HasPrefix(s, "-"):589			commands = append(commands, s)590		}591	}592593	return commands594}595596// argsMinusFirstX removes only the first x from args.  Otherwise, commands that look like597// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).598func argsMinusFirstX(args []string, x string) []string {599	for i, y := range args {600		if x == y {601			ret := []string{}602			ret = append(ret, args[:i]...)603			ret = append(ret, args[i+1:]...)604			return ret605		}606	}607	return args608}609610func isFlagArg(arg string) bool {611	return ((len(arg) >= 3 && arg[1] == '-') ||612		(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))613}614615// Find the target command given the args and command tree616// Meant to be run on the highest node. Only searches down.617func (c *Command) Find(args []string) (*Command, []string, error) {618	var innerfind func(*Command, []string) (*Command, []string)619620	innerfind = func(c *Command, innerArgs []string) (*Command, []string) {621		argsWOflags := stripFlags(innerArgs, c)622		if len(argsWOflags) == 0 {623			return c, innerArgs624		}625		nextSubCmd := argsWOflags[0]626627		cmd := c.findNext(nextSubCmd)628		if cmd != nil {629			return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))630		}631		return c, innerArgs632	}633634	commandFound, a := innerfind(c, args)635	if commandFound.Args == nil {636		return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))637	}638	return commandFound, a, nil639}640641func (c *Command) findSuggestions(arg string) string {642	if c.DisableSuggestions {643		return ""644	}645	if c.SuggestionsMinimumDistance <= 0 {646		c.SuggestionsMinimumDistance = 2647	}648	suggestionsString := ""649	if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {650		suggestionsString += "\n\nDid you mean this?\n"651		for _, s := range suggestions {652			suggestionsString += fmt.Sprintf("\t%v\n", s)653		}654	}655	return suggestionsString656}657658func (c *Command) findNext(next string) *Command {659	matches := make([]*Command, 0)660	for _, cmd := range c.commands {661		if cmd.Name() == next || cmd.HasAlias(next) {662			cmd.commandCalledAs.name = next663			return cmd664		}665		if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {666			matches = append(matches, cmd)667		}668	}669670	if len(matches) == 1 {671		return matches[0]672	}673674	return nil675}676677// Traverse the command tree to find the command, and parse args for678// each parent.679func (c *Command) Traverse(args []string) (*Command, []string, error) {680	flags := []string{}681	inFlag := false682683	for i, arg := range args {684		switch {685		// A long flag with a space separated value686		case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):687			// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'688			inFlag = !hasNoOptDefVal(arg[2:], c.Flags())689			flags = append(flags, arg)690			continue691		// A short flag with a space separated value692		case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):693			inFlag = true694			flags = append(flags, arg)695			continue696		// The value for a flag697		case inFlag:698			inFlag = false699			flags = append(flags, arg)700			continue701		// A flag without a value, or with an `=` separated value702		case isFlagArg(arg):703			flags = append(flags, arg)704			continue705		}706707		cmd := c.findNext(arg)708		if cmd == nil {709			return c, args, nil710		}711712		if err := c.ParseFlags(flags); err != nil {713			return nil, args, err714		}715		return cmd.Traverse(args[i+1:])716	}717	return c, args, nil718}719720// SuggestionsFor provides suggestions for the typedName.721func (c *Command) SuggestionsFor(typedName string) []string {722	suggestions := []string{}723	for _, cmd := range c.commands {724		if cmd.IsAvailableCommand() {725			levenshteinDistance := ld(typedName, cmd.Name(), true)726			suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance727			suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))728			if suggestByLevenshtein || suggestByPrefix {729				suggestions = append(suggestions, cmd.Name())730			}731			for _, explicitSuggestion := range cmd.SuggestFor {732				if strings.EqualFold(typedName, explicitSuggestion) {733					suggestions = append(suggestions, cmd.Name())734				}735			}736		}737	}738	return suggestions739}740741// VisitParents visits all parents of the command and invokes fn on each parent.742func (c *Command) VisitParents(fn func(*Command)) {743	if c.HasParent() {744		fn(c.Parent())745		c.Parent().VisitParents(fn)746	}747}748749// Root finds root command.750func (c *Command) Root() *Command {751	if c.HasParent() {752		return c.Parent().Root()753	}754	return c755}756757// ArgsLenAtDash will return the length of c.Flags().Args at the moment758// when a -- was found during args parsing.759func (c *Command) ArgsLenAtDash() int {760	return c.Flags().ArgsLenAtDash()761}762763func (c *Command) execute(a []string) (err error) {764	if c == nil {765		return fmt.Errorf("Called Execute() on a nil Command")766	}767768	if len(c.Deprecated) > 0 {769		c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)770	}771772	// initialize help and version flag at the last point possible to allow for user773	// overriding774	c.InitDefaultHelpFlag()775	c.InitDefaultVersionFlag()776777	err = c.ParseFlags(a)778	if err != nil {779		return c.FlagErrorFunc()(c, err)780	}781782	// If help is called, regardless of other flags, return we want help.783	// Also say we need help if the command isn't runnable.784	helpVal, err := c.Flags().GetBool("help")785	if err != nil {786		// should be impossible to get here as we always declare a help787		// flag in InitDefaultHelpFlag()788		c.Println("\"help\" flag declared as non-bool. Please correct your code")789		return err790	}791792	if helpVal {793		return flag.ErrHelp794	}795796	// for back-compat, only add version flag behavior if version is defined797	if c.Version != "" {798		versionVal, err := c.Flags().GetBool("version")799		if err != nil {800			c.Println("\"version\" flag declared as non-bool. Please correct your code")801			return err802		}803		if versionVal {804			err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)805			if err != nil {806				c.Println(err)807			}808			return err809		}810	}811812	if !c.Runnable() {813		return flag.ErrHelp814	}815816	c.preRun()817818	argWoFlags := c.Flags().Args()819	if c.DisableFlagParsing {820		argWoFlags = a821	}822823	if err := c.ValidateArgs(argWoFlags); err != nil {824		return err825	}826827	for p := c; p != nil; p = p.Parent() {828		if p.PersistentPreRunE != nil {829			if err := p.PersistentPreRunE(c, argWoFlags); err != nil {830				return err831			}832			break833		} else if p.PersistentPreRun != nil {834			p.PersistentPreRun(c, argWoFlags)835			break836		}837	}838	if c.PreRunE != nil {839		if err := c.PreRunE(c, argWoFlags); err != nil {840			return err841		}842	} else if c.PreRun != nil {843		c.PreRun(c, argWoFlags)844	}845846	if err := c.validateRequiredFlags(); err != nil {847		return err848	}849	if c.RunE != nil {850		if err := c.RunE(c, argWoFlags); err != nil {851			return err852		}853	} else {854		c.Run(c, argWoFlags)855	}856	if c.PostRunE != nil {857		if err := c.PostRunE(c, argWoFlags); err != nil {858			return err859		}860	} else if c.PostRun != nil {861		c.PostRun(c, argWoFlags)862	}863	for p := c; p != nil; p = p.Parent() {864		if p.PersistentPostRunE != nil {865			if err := p.PersistentPostRunE(c, argWoFlags); err != nil {866				return err867			}868			break869		} else if p.PersistentPostRun != nil {870			p.PersistentPostRun(c, argWoFlags)871			break872		}873	}874875	return nil876}877878func (c *Command) preRun() {879	for _, x := range initializers {880		x()881	}882}883884// ExecuteContext is the same as Execute(), but sets the ctx on the command.885// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle functions.886func (c *Command) ExecuteContext(ctx context.Context) error {887	c.ctx = ctx888	return c.Execute()889}890891// Execute uses the args (os.Args[1:] by default)892// and run through the command tree finding appropriate matches893// for commands and then corresponding flags.894func (c *Command) Execute() error {895	_, err := c.ExecuteC()896	return err897}898899// ExecuteC executes the command.900func (c *Command) ExecuteC() (cmd *Command, err error) {901	if c.ctx == nil {902		c.ctx = context.Background()903	}904905	// Regardless of what command execute is called on, run on Root only906	if c.HasParent() {907		return c.Root().ExecuteC()908	}909910	// windows hook911	if preExecHookFn != nil {912		preExecHookFn(c)913	}914915	// initialize help as the last point possible to allow for user916	// overriding917	c.InitDefaultHelpCmd()918919	args := c.args920921	// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155922	if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {923		args = os.Args[1:]924	}925926	// initialize the hidden command to be used for bash completion927	c.initCompleteCmd(args)928929	var flags []string930	if c.TraverseChildren {931		cmd, flags, err = c.Traverse(args)932	} else {933		cmd, flags, err = c.Find(args)934	}935	if err != nil {936		// If found parse to a subcommand and then failed, talk about the subcommand937		if cmd != nil {938			c = cmd939		}940		if !c.SilenceErrors {941			c.PrintErrln("Error:", err.Error())942			c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())943		}944		return c, err945	}946947	cmd.commandCalledAs.called = true948	if cmd.commandCalledAs.name == "" {949		cmd.commandCalledAs.name = cmd.Name()950	}951952	// We have to pass global context to children command953	// if context is present on the parent command.954	if cmd.ctx == nil {955		cmd.ctx = c.ctx956	}957958	err = cmd.execute(flags)959	if err != nil {960		// Always show help if requested, even if SilenceErrors is in961		// effect962		if err == flag.ErrHelp {963			cmd.HelpFunc()(cmd, args)964			return cmd, nil965		}966967		// If root command has SilenceErrors flagged,968		// all subcommands should respect it969		if !cmd.SilenceErrors && !c.SilenceErrors {970			c.PrintErrln("Error:", err.Error())971		}972973		// If root command has SilenceUsage flagged,974		// all subcommands should respect it975		if !cmd.SilenceUsage && !c.SilenceUsage {976			c.Println(cmd.UsageString())977		}978	}979	return cmd, err980}981982func (c *Command) ValidateArgs(args []string) error {983	if c.Args == nil {984		return nil985	}986	return c.Args(c, args)987}988989func (c *Command) validateRequiredFlags() error {990	if c.DisableFlagParsing {991		return nil992	}993994	flags := c.Flags()995	missingFlagNames := []string{}996	flags.VisitAll(func(pflag *flag.Flag) {997		requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]998		if !found {999			return1000		}1001		if (requiredAnnotation[0] == "true") && !pflag.Changed {1002			missingFlagNames = append(missingFlagNames, pflag.Name)1003		}1004	})10051006	if len(missingFlagNames) > 0 {1007		return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))1008	}1009	return nil1010}10111012// InitDefaultHelpFlag adds default help flag to c.1013// It is called automatically by executing the c or by calling help and usage.1014// If c already has help flag, it will do nothing.1015func (c *Command) InitDefaultHelpFlag() {1016	c.mergePersistentFlags()1017	if c.Flags().Lookup("help") == nil {1018		usage := "help for "1019		if c.Name() == "" {1020			usage += "this command"1021		} else {1022			usage += c.Name()1023		}1024		c.Flags().BoolP("help", "h", false, usage)1025	}1026}10271028// InitDefaultVersionFlag adds default version flag to c.1029// It is called automatically by executing the c.1030// If c already has a version flag, it will do nothing.1031// If c.Version is empty, it will do nothing.1032func (c *Command) InitDefaultVersionFlag() {1033	if c.Version == "" {1034		return1035	}10361037	c.mergePersistentFlags()1038	if c.Flags().Lookup("version") == nil {1039		usage := "version for "1040		if c.Name() == "" {1041			usage += "this command"1042		} else {1043			usage += c.Name()1044		}1045		if c.Flags().ShorthandLookup("v") == nil {1046			c.Flags().BoolP("version", "v", false, usage)1047		} else {1048			c.Flags().Bool("version", false, usage)1049		}1050	}1051}10521053// InitDefaultHelpCmd adds default help command to c.1054// It is called automatically by executing the c or by calling help and usage.1055// If c already has help command or c has no subcommands, it will do nothing.1056func (c *Command) InitDefaultHelpCmd() {1057	if !c.HasSubCommands() {1058		return1059	}10601061	if c.helpCommand == nil {1062		c.helpCommand = &Command{1063			Use:   "help [command]",1064			Short: "Help about any command",1065			Long: `Help provides help for any command in the application.1066Simply type ` + c.Name() + ` help [path to command] for full details.`,1067			ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1068				var completions []string1069				cmd, _, e := c.Root().Find(args)1070				if e != nil {1071					return nil, ShellCompDirectiveNoFileComp1072				}1073				if cmd == nil {1074					// Root help command.1075					cmd = c.Root()1076				}1077				for _, subCmd := range cmd.Commands() {1078					if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {1079						if strings.HasPrefix(subCmd.Name(), toComplete) {1080							completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))1081						}1082					}1083				}1084				return completions, ShellCompDirectiveNoFileComp1085			},1086			Run: func(c *Command, args []string) {1087				cmd, _, e := c.Root().Find(args)1088				if cmd == nil || e != nil {1089					c.Printf("Unknown help topic %#q\n", args)1090					c.Root().Usage()1091				} else {1092					cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1093					cmd.Help()1094				}1095			},1096		}1097	}1098	c.RemoveCommand(c.helpCommand)1099	c.AddCommand(c.helpCommand)1100}11011102// ResetCommands delete parent, subcommand and help command from c.1103func (c *Command) ResetCommands() {1104	c.parent = nil1105	c.commands = nil1106	c.helpCommand = nil1107	c.parentsPflags = nil1108}11091110// Sorts commands by their names.1111type commandSorterByName []*Command11121113func (c commandSorterByName) Len() int           { return len(c) }1114func (c commandSorterByName) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }1115func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }11161117// Commands returns a sorted slice of child commands.1118func (c *Command) Commands() []*Command {1119	// do not sort commands if it already sorted or sorting was disabled1120	if EnableCommandSorting && !c.commandsAreSorted {1121		sort.Sort(commandSorterByName(c.commands))1122		c.commandsAreSorted = true1123	}1124	return c.commands1125}11261127// AddCommand adds one or more commands to this parent command.1128func (c *Command) AddCommand(cmds ...*Command) {1129	for i, x := range cmds {1130		if cmds[i] == c {1131			panic("Command can't be a child of itself")1132		}1133		cmds[i].parent = c1134		// update max lengths1135		usageLen := len(x.Use)1136		if usageLen > c.commandsMaxUseLen {1137			c.commandsMaxUseLen = usageLen1138		}1139		commandPathLen := len(x.CommandPath())1140		if commandPathLen > c.commandsMaxCommandPathLen {1141			c.commandsMaxCommandPathLen = commandPathLen1142		}1143		nameLen := len(x.Name())1144		if nameLen > c.commandsMaxNameLen {1145			c.commandsMaxNameLen = nameLen1146		}1147		// If global normalization function exists, update all children1148		if c.globNormFunc != nil {1149			x.SetGlobalNormalizationFunc(c.globNormFunc)1150		}1151		c.commands = append(c.commands, x)1152		c.commandsAreSorted = false1153	}1154}11551156// RemoveCommand removes one or more commands from a parent command.1157func (c *Command) RemoveCommand(cmds ...*Command) {1158	commands := []*Command{}1159main:1160	for _, command := range c.commands {1161		for _, cmd := range cmds {1162			if command == cmd {1163				command.parent = nil1164				continue main1165			}1166		}1167		commands = append(commands, command)1168	}1169	c.commands = commands1170	// recompute all lengths1171	c.commandsMaxUseLen = 01172	c.commandsMaxCommandPathLen = 01173	c.commandsMaxNameLen = 01174	for _, command := range c.commands {1175		usageLen := len(command.Use)1176		if usageLen > c.commandsMaxUseLen {1177			c.commandsMaxUseLen = usageLen1178		}1179		commandPathLen := len(command.CommandPath())1180		if commandPathLen > c.commandsMaxCommandPathLen {1181			c.commandsMaxCommandPathLen = commandPathLen1182		}1183		nameLen := len(command.Name())1184		if nameLen > c.commandsMaxNameLen {1185			c.commandsMaxNameLen = nameLen1186		}1187	}1188}11891190// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1191func (c *Command) Print(i ...interface{}) {1192	fmt.Fprint(c.OutOrStderr(), i...)1193}11941195// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1196func (c *Command) Println(i ...interface{}) {1197	c.Print(fmt.Sprintln(i...))1198}11991200// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1201func (c *Command) Printf(format string, i ...interface{}) {1202	c.Print(fmt.Sprintf(format, i...))1203}12041205// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.1206func (c *Command) PrintErr(i ...interface{}) {1207	fmt.Fprint(c.ErrOrStderr(), i...)1208}12091210// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.1211func (c *Command) PrintErrln(i ...interface{}) {1212	c.PrintErr(fmt.Sprintln(i...))1213}12141215// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.1216func (c *Command) PrintErrf(format string, i ...interface{}) {1217	c.PrintErr(fmt.Sprintf(format, i...))1218}12191220// CommandPath returns the full path to this command.1221func (c *Command) CommandPath() string {1222	if c.HasParent() {1223		return c.Parent().CommandPath() + " " + c.Name()1224	}1225	return c.Name()1226}12271228// UseLine puts out the full usage for a given command (including parents).1229func (c *Command) UseLine() string {1230	var useline string1231	if c.HasParent() {1232		useline = c.parent.CommandPath() + " " + c.Use1233	} else {1234		useline = c.Use1235	}1236	if c.DisableFlagsInUseLine {1237		return useline1238	}1239	if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1240		useline += " [flags]"1241	}1242	return useline1243}12441245// DebugFlags used to determine which flags have been assigned to which commands1246// and which persist.1247func (c *Command) DebugFlags() {1248	c.Println("DebugFlags called on", c.Name())1249	var debugflags func(*Command)12501251	debugflags = func(x *Command) {1252		if x.HasFlags() || x.HasPersistentFlags() {1253			c.Println(x.Name())1254		}1255		if x.HasFlags() {1256			x.flags.VisitAll(func(f *flag.Flag) {1257				if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1258					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [LP]")1259				} else {1260					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")1261				}1262			})1263		}1264		if x.HasPersistentFlags() {1265			x.pflags.VisitAll(func(f *flag.Flag) {1266				if x.HasFlags() {1267					if x.flags.Lookup(f.Name) == nil {1268						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")1269					}1270				} else {1271					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")1272				}1273			})1274		}1275		c.Println(x.flagErrorBuf)1276		if x.HasSubCommands() {1277			for _, y := range x.commands {1278				debugflags(y)1279			}1280		}1281	}12821283	debugflags(c)1284}12851286// Name returns the command's name: the first word in the use line.1287func (c *Command) Name() string {1288	name := c.Use1289	i := strings.Index(name, " ")1290	if i >= 0 {1291		name = name[:i]1292	}1293	return name1294}12951296// HasAlias determines if a given string is an alias of the command.1297func (c *Command) HasAlias(s string) bool {1298	for _, a := range c.Aliases {1299		if a == s {1300			return true1301		}1302	}1303	return false1304}13051306// CalledAs returns the command name or alias that was used to invoke1307// this command or an empty string if the command has not been called.1308func (c *Command) CalledAs() string {1309	if c.commandCalledAs.called {1310		return c.commandCalledAs.name1311	}1312	return ""1313}13141315// hasNameOrAliasPrefix returns true if the Name or any of aliases start1316// with prefix1317func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1318	if strings.HasPrefix(c.Name(), prefix) {1319		c.commandCalledAs.name = c.Name()1320		return true1321	}1322	for _, alias := range c.Aliases {1323		if strings.HasPrefix(alias, prefix) {1324			c.commandCalledAs.name = alias1325			return true1326		}1327	}1328	return false1329}13301331// NameAndAliases returns a list of the command name and all aliases1332func (c *Command) NameAndAliases() string {1333	return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1334}13351336// HasExample determines if the command has example.1337func (c *Command) HasExample() bool {1338	return len(c.Example) > 01339}13401341// Runnable determines if the command is itself runnable.1342func (c *Command) Runnable() bool {1343	return c.Run != nil || c.RunE != nil1344}13451346// HasSubCommands determines if the command has children commands.1347func (c *Command) HasSubCommands() bool {1348	return len(c.commands) > 01349}13501351// IsAvailableCommand determines if a command is available as a non-help command1352// (this includes all non deprecated/hidden commands).1353func (c *Command) IsAvailableCommand() bool {1354	if len(c.Deprecated) != 0 || c.Hidden {1355		return false1356	}13571358	if c.HasParent() && c.Parent().helpCommand == c {1359		return false1360	}13611362	if c.Runnable() || c.HasAvailableSubCommands() {1363		return true1364	}13651366	return false1367}13681369// IsAdditionalHelpTopicCommand determines if a command is an additional1370// help topic command; additional help topic command is determined by the1371// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1372// are runnable/hidden/deprecated.1373// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1374func (c *Command) IsAdditionalHelpTopicCommand() bool {1375	// if a command is runnable, deprecated, or hidden it is not a 'help' command1376	if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1377		return false1378	}13791380	// if any non-help sub commands are found, the command is not a 'help' command1381	for _, sub := range c.commands {1382		if !sub.IsAdditionalHelpTopicCommand() {1383			return false1384		}1385	}13861387	// the command either has no sub commands, or no non-help sub commands1388	return true1389}13901391// HasHelpSubCommands determines if a command has any available 'help' sub commands1392// that need to be shown in the usage/help default template under 'additional help1393// topics'.1394func (c *Command) HasHelpSubCommands() bool {1395	// return true on the first found available 'help' sub command1396	for _, sub := range c.commands {1397		if sub.IsAdditionalHelpTopicCommand() {1398			return true1399		}1400	}14011402	// the command either has no sub commands, or no available 'help' sub commands1403	return false1404}14051406// HasAvailableSubCommands determines if a command has available sub commands that1407// need to be shown in the usage/help default template under 'available commands'.1408func (c *Command) HasAvailableSubCommands() bool {1409	// return true on the first found available (non deprecated/help/hidden)1410	// sub command1411	for _, sub := range c.commands {1412		if sub.IsAvailableCommand() {1413			return true1414		}1415	}14161417	// the command either has no sub commands, or no available (non deprecated/help/hidden)1418	// sub commands1419	return false1420}14211422// HasParent determines if the command is a child command.1423func (c *Command) HasParent() bool {1424	return c.parent != nil1425}14261427// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.1428func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1429	return c.globNormFunc1430}14311432// Flags returns the complete FlagSet that applies1433// to this command (local and persistent declared here and by all parents).1434func (c *Command) Flags() *flag.FlagSet {1435	if c.flags == nil {1436		c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1437		if c.flagErrorBuf == nil {1438			c.flagErrorBuf = new(bytes.Buffer)1439		}1440		c.flags.SetOutput(c.flagErrorBuf)1441	}14421443	return c.flags1444}14451446// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1447func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1448	persistentFlags := c.PersistentFlags()14491450	out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1451	c.LocalFlags().VisitAll(func(f *flag.Flag) {1452		if persistentFlags.Lookup(f.Name) == nil {1453			out.AddFlag(f)1454		}1455	})1456	return out1457}14581459// LocalFlags returns the local FlagSet specifically set in the current command.1460func (c *Command) LocalFlags() *flag.FlagSet {1461	c.mergePersistentFlags()14621463	if c.lflags == nil {1464		c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1465		if c.flagErrorBuf == nil {1466			c.flagErrorBuf = new(bytes.Buffer)1467		}1468		c.lflags.SetOutput(c.flagErrorBuf)1469	}1470	c.lflags.SortFlags = c.Flags().SortFlags1471	if c.globNormFunc != nil {1472		c.lflags.SetNormalizeFunc(c.globNormFunc)1473	}14741475	addToLocal := func(f *flag.Flag) {1476		if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1477			c.lflags.AddFlag(f)1478		}1479	}1480	c.Flags().VisitAll(addToLocal)1481	c.PersistentFlags().VisitAll(addToLocal)1482	return c.lflags1483}14841485// InheritedFlags returns all flags which were inherited from parent commands.1486func (c *Command) InheritedFlags() *flag.FlagSet {1487	c.mergePersistentFlags()14881489	if c.iflags == nil {1490		c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1491		if c.flagErrorBuf == nil {1492			c.flagErrorBuf = new(bytes.Buffer)1493		}1494		c.iflags.SetOutput(c.flagErrorBuf)1495	}14961497	local := c.LocalFlags()1498	if c.globNormFunc != nil {1499		c.iflags.SetNormalizeFunc(c.globNormFunc)1500	}15011502	c.parentsPflags.VisitAll(func(f *flag.Flag) {1503		if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1504			c.iflags.AddFlag(f)1505		}1506	})1507	return c.iflags1508}15091510// NonInheritedFlags returns all flags which were not inherited from parent commands.1511func (c *Command) NonInheritedFlags() *flag.FlagSet {1512	return c.LocalFlags()1513}15141515// PersistentFlags returns the persistent FlagSet specifically set in the current command.1516func (c *Command) PersistentFlags() *flag.FlagSet {1517	if c.pflags == nil {1518		c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1519		if c.flagErrorBuf == nil {1520			c.flagErrorBuf = new(bytes.Buffer)1521		}1522		c.pflags.SetOutput(c.flagErrorBuf)1523	}1524	return c.pflags1525}15261527// ResetFlags deletes all flags from command.1528func (c *Command) ResetFlags() {1529	c.flagErrorBuf = new(bytes.Buffer)1530	c.flagErrorBuf.Reset()1531	c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1532	c.flags.SetOutput(c.flagErrorBuf)1533	c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1534	c.pflags.SetOutput(c.flagErrorBuf)15351536	c.lflags = nil1537	c.iflags = nil1538	c.parentsPflags = nil1539}15401541// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1542func (c *Command) HasFlags() bool {1543	return c.Flags().HasFlags()1544}15451546// HasPersistentFlags checks if the command contains persistent flags.1547func (c *Command) HasPersistentFlags() bool {1548	return c.PersistentFlags().HasFlags()1549}15501551// HasLocalFlags checks if the command has flags specifically declared locally.1552func (c *Command) HasLocalFlags() bool {1553	return c.LocalFlags().HasFlags()1554}15551556// HasInheritedFlags checks if the command has flags inherited from its parent command.1557func (c *Command) HasInheritedFlags() bool {1558	return c.InheritedFlags().HasFlags()1559}15601561// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1562// structure) which are not hidden or deprecated.1563func (c *Command) HasAvailableFlags() bool {1564	return c.Flags().HasAvailableFlags()1565}15661567// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1568func (c *Command) HasAvailablePersistentFlags() bool {1569	return c.PersistentFlags().HasAvailableFlags()1570}15711572// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1573// or deprecated.1574func (c *Command) HasAvailableLocalFlags() bool {1575	return c.LocalFlags().HasAvailableFlags()1576}15771578// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1579// not hidden or deprecated.1580func (c *Command) HasAvailableInheritedFlags() bool {1581	return c.InheritedFlags().HasAvailableFlags()1582}15831584// Flag climbs up the command tree looking for matching flag.1585func (c *Command) Flag(name string) (flag *flag.Flag) {1586	flag = c.Flags().Lookup(name)15871588	if flag == nil {1589		flag = c.persistentFlag(name)1590	}15911592	return1593}15941595// Recursively find matching persistent flag.1596func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1597	if c.HasPersistentFlags() {1598		flag = c.PersistentFlags().Lookup(name)1599	}16001601	if flag == nil {1602		c.updateParentsPflags()1603		flag = c.parentsPflags.Lookup(name)1604	}1605	return1606}16071608// ParseFlags parses persistent flag tree and local flags.1609func (c *Command) ParseFlags(args []string) error {1610	if c.DisableFlagParsing {1611		return nil1612	}16131614	if c.flagErrorBuf == nil {1615		c.flagErrorBuf = new(bytes.Buffer)1616	}1617	beforeErrorBufLen := c.flagErrorBuf.Len()1618	c.mergePersistentFlags()16191620	// do it here after merging all flags and just before parse1621	c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)16221623	err := c.Flags().Parse(args)1624	// Print warnings if they occurred (e.g. deprecated flag messages).1625	if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1626		c.Print(c.flagErrorBuf.String())1627	}16281629	return err1630}16311632// Parent returns a commands parent command.1633func (c *Command) Parent() *Command {1634	return c.parent1635}16361637// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1638// and adds missing persistent flags of all parents.1639func (c *Command) mergePersistentFlags() {1640	c.updateParentsPflags()1641	c.Flags().AddFlagSet(c.PersistentFlags())1642	c.Flags().AddFlagSet(c.parentsPflags)1643}16441645// updateParentsPflags updates c.parentsPflags by adding1646// new persistent flags of all parents.1647// If c.parentsPflags == nil, it makes new.1648func (c *Command) updateParentsPflags() {1649	if c.parentsPflags == nil {1650		c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1651		c.parentsPflags.SetOutput(c.flagErrorBuf)1652		c.parentsPflags.SortFlags = false1653	}16541655	if c.globNormFunc != nil {1656		c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1657	}16581659	c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)16601661	c.VisitParents(func(parent *Command) {1662		c.parentsPflags.AddFlagSet(parent.PersistentFlags())1663	})1664}