Skip to content
Myr

command.go

This file

Path

command.go

970 lines · 23.6 KiB · Go

Last changed by

Deprecated subcommandsEric Parisbefore adoptionc3e48f9

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	"github.com/inconshreveable/mousetrap"22	flag "github.com/spf13/pflag"23	"io"24	"os"25	"runtime"26	"strings"27	"time"28)2930// Command is just that, a command for your application.31// eg.  '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	// Name is the command name, usually the executable's name.36	name string37	// The one-line usage message.38	Use string39	// An array of aliases that can be used instead of the first word in Use.40	Aliases []string41	// The short description shown in the 'help' output.42	Short string43	// The long message shown in the 'help <this-command>' output.44	Long string45	// Examples of how to use the command46	Example string47	// List of all valid non-flag arguments, used for bash completions *TODO* actually validate these48	ValidArgs []string49	// Custom functions used by the bash autocompletion generator50	BashCompletionFunction string51	// Is this command deprecated and should print this string when used?52	Deprecated string53	// Full set of flags54	flags *flag.FlagSet55	// Set of flags childrens of this command will inherit56	pflags *flag.FlagSet57	// Flags that are declared specifically by this command (not inherited).58	lflags *flag.FlagSet59	// Run runs the command.60	// The args are the arguments after the command name.61	Run func(cmd *Command, args []string)62	// Commands is the list of commands supported by this program.63	commands []*Command64	// Parent Command for this command65	parent *Command66	// max lengths of commands' string lengths for use in padding67	commandsMaxUseLen         int68	commandsMaxCommandPathLen int69	commandsMaxNameLen        int7071	flagErrorBuf *bytes.Buffer72	cmdErrorBuf  *bytes.Buffer7374	args          []string                 // actual args parsed from flags75	output        *io.Writer               // nil means stderr; use Out() method instead76	usageFunc     func(*Command) error     // Usage can be defined by application77	usageTemplate string                   // Can be defined by Application78	helpTemplate  string                   // Can be defined by Application79	helpFunc      func(*Command, []string) // Help can be defined by application80	helpCommand   *Command                 // The help command81	helpFlagVal   bool82}8384// os.Args[1:] by default, if desired, can be overridden85// particularly useful when testing.86func (c *Command) SetArgs(a []string) {87	c.args = a88}8990func (c *Command) getOut(def io.Writer) io.Writer {91	if c.output != nil {92		return *c.output93	}9495	if c.HasParent() {96		return c.parent.Out()97	} else {98		return def99	}100}101102func (c *Command) Out() io.Writer {103	return c.getOut(os.Stderr)104}105106func (c *Command) getOutOrStdout() io.Writer {107	return c.getOut(os.Stdout)108}109110// SetOutput sets the destination for usage and error messages.111// If output is nil, os.Stderr is used.112func (c *Command) SetOutput(output io.Writer) {113	c.output = &output114}115116// Usage can be defined by application117func (c *Command) SetUsageFunc(f func(*Command) error) {118	c.usageFunc = f119}120121// Can be defined by Application122func (c *Command) SetUsageTemplate(s string) {123	c.usageTemplate = s124}125126// Can be defined by Application127func (c *Command) SetHelpFunc(f func(*Command, []string)) {128	c.helpFunc = f129}130131func (c *Command) SetHelpCommand(cmd *Command) {132	c.helpCommand = cmd133}134135// Can be defined by Application136func (c *Command) SetHelpTemplate(s string) {137	c.helpTemplate = s138}139140func (c *Command) UsageFunc() (f func(*Command) error) {141	if c.usageFunc != nil {142		return c.usageFunc143	}144145	if c.HasParent() {146		return c.parent.UsageFunc()147	} else {148		return func(c *Command) error {149			err := tmpl(c.Out(), c.UsageTemplate(), c)150			return err151		}152	}153}154func (c *Command) HelpFunc() func(*Command, []string) {155	if c.helpFunc != nil {156		return c.helpFunc157	}158159	if c.HasParent() {160		return c.parent.HelpFunc()161	} else {162		return func(c *Command, args []string) {163			if len(args) == 0 {164				// Help called without any topic, calling on root165				c.Root().Help()166				return167			}168169			cmd, _, e := c.Root().Find(args)170			if cmd == nil || e != nil {171				c.Printf("Unknown help topic %#q.", args)172173				c.Root().Usage()174			} else {175				err := cmd.Help()176				if err != nil {177					c.Println(err)178				}179			}180		}181	}182}183184var minUsagePadding int = 25185186func (c *Command) UsagePadding() int {187	if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {188		return minUsagePadding189	} else {190		return c.parent.commandsMaxUseLen191	}192}193194var minCommandPathPadding int = 11195196//197func (c *Command) CommandPathPadding() int {198	if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {199		return minCommandPathPadding200	} else {201		return c.parent.commandsMaxCommandPathLen202	}203}204205var minNamePadding int = 11206207func (c *Command) NamePadding() int {208	if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {209		return minNamePadding210	} else {211		return c.parent.commandsMaxNameLen212	}213}214215func (c *Command) UsageTemplate() string {216	if c.usageTemplate != "" {217		return c.usageTemplate218	}219220	if c.HasParent() {221		return c.parent.UsageTemplate()222	} else {223		return `{{ $cmd := . }}224Usage: {{if .Runnable}}225  {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}226  {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}227228Aliases:229  {{.NameAndAliases}}230{{end}}{{if .HasExample}}231232Examples:233{{ .Example }}234{{end}}{{ if .HasRunnableSubCommands}}235236Available Commands: {{range .Commands}}{{if and (.Runnable) (not .Deprecated)}}237  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}238{{end}}239{{ if .HasLocalFlags}}Flags:240{{.LocalFlags.FlagUsages}}{{end}}241{{ if .HasInheritedFlags}}Global Flags:242{{.InheritedFlags.FlagUsages}}{{end}}{{if or (.HasHelpSubCommands) (.HasRunnableSiblings)}}243Additional help topics:244{{if .HasHelpSubCommands}}{{range .Commands}}{{if and (not .Runnable) (not .Deprecated)}} {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasRunnableSiblings }}{{range .Parent.Commands}}{{if and (not .Runnable) (not .Deprecated)}}{{if not (eq .Name $cmd.Name) }}245  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{end}}246{{end}}{{ if .HasSubCommands }}247Use "{{.Root.Name}} help [command]" for more information about a command.248{{end}}`249	}250}251252func (c *Command) HelpTemplate() string {253	if c.helpTemplate != "" {254		return c.helpTemplate255	}256257	if c.HasParent() {258		return c.parent.HelpTemplate()259	} else {260		return `{{with or .Long .Short }}{{. | trim}}{{end}}261{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}262`263	}264}265266// Really only used when casting a command to a commander267func (c *Command) resetChildrensParents() {268	for _, x := range c.commands {269		x.parent = c270	}271}272273// Test if the named flag is a boolean flag.274func isBooleanFlag(name string, f *flag.FlagSet) bool {275	flag := f.Lookup(name)276	if flag == nil {277		return false278	}279	return flag.Value.Type() == "bool"280}281282// Test if the named flag is a boolean flag.283func isBooleanShortFlag(name string, f *flag.FlagSet) bool {284	result := false285	f.VisitAll(func(f *flag.Flag) {286		if f.Shorthand == name && f.Value.Type() == "bool" {287			result = true288		}289	})290	return result291}292293func stripFlags(args []string, c *Command) []string {294	if len(args) < 1 {295		return args296	}297	c.mergePersistentFlags()298299	commands := []string{}300301	inQuote := false302	inFlag := false303	for _, y := range args {304		if !inQuote {305			switch {306			case strings.HasPrefix(y, "\""):307				inQuote = true308			case strings.Contains(y, "=\""):309				inQuote = true310			case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):311				// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'312				inFlag = !isBooleanFlag(y[2:], c.Flags())313			case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):314				inFlag = true315			case inFlag:316				inFlag = false317			case y == "":318				// strip empty commands, as the go tests expect this to be ok....319			case !strings.HasPrefix(y, "-"):320				commands = append(commands, y)321				inFlag = false322			}323		}324325		if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {326			inQuote = false327		}328	}329330	return commands331}332333// argsMinusFirstX removes only the first x from args.  Otherwise, commands that look like334// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).335func argsMinusFirstX(args []string, x string) []string {336	for i, y := range args {337		if x == y {338			ret := []string{}339			ret = append(ret, args[:i]...)340			ret = append(ret, args[i+1:]...)341			return ret342		}343	}344	return args345}346347// find the target command given the args and command tree348// Meant to be run on the highest node. Only searches down.349func (c *Command) Find(arrs []string) (*Command, []string, error) {350	if c == nil {351		return nil, nil, fmt.Errorf("Called find() on a nil Command")352	}353354	if len(arrs) == 0 {355		return c.Root(), arrs, nil356	}357358	var innerfind func(*Command, []string) (*Command, []string)359360	innerfind = func(c *Command, args []string) (*Command, []string) {361		if len(args) > 0 && c.HasSubCommands() {362			argsWOflags := stripFlags(args, c)363			if len(argsWOflags) > 0 {364				matches := make([]*Command, 0)365				for _, cmd := range c.commands {366					if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match367						return innerfind(cmd, argsMinusFirstX(args, argsWOflags[0]))368					} else if EnablePrefixMatching {369						if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match370							matches = append(matches, cmd)371						}372						for _, x := range cmd.Aliases {373							if strings.HasPrefix(x, argsWOflags[0]) {374								matches = append(matches, cmd)375							}376						}377					}378				}379380				// only accept a single prefix match - multiple matches would be ambiguous381				if len(matches) == 1 {382					return innerfind(matches[0], argsMinusFirstX(args, argsWOflags[0]))383				}384			}385		}386387		return c, args388	}389390	commandFound, a := innerfind(c, arrs)391392	// If we matched on the root, but we asked for a subcommand, return an error393	if commandFound.Name() == c.Name() && len(stripFlags(arrs, c)) > 0 && commandFound.Name() != arrs[0] {394		return nil, a, fmt.Errorf("unknown command %q", a[0])395	}396397	return commandFound, a, nil398}399400func (c *Command) Root() *Command {401	var findRoot func(*Command) *Command402403	findRoot = func(x *Command) *Command {404		if x.HasParent() {405			return findRoot(x.parent)406		} else {407			return x408		}409	}410411	return findRoot(c)412}413414func (c *Command) execute(a []string) (err error) {415	if c == nil {416		return fmt.Errorf("Called Execute() on a nil Command")417	}418419	if len(c.Deprecated) > 0 {420		c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)421	}422423	err = c.ParseFlags(a)424	if err == flag.ErrHelp {425		c.Help()426		return nil427	}428	if err != nil {429		// We're writing subcommand usage to root command's error buffer to have it displayed to the user430		r := c.Root()431		if r.cmdErrorBuf == nil {432			r.cmdErrorBuf = new(bytes.Buffer)433		}434		// for writing the usage to the buffer we need to switch the output temporarily435		// since Out() returns root output, you also need to revert that on root436		out := r.Out()437		r.SetOutput(r.cmdErrorBuf)438		c.Usage()439		r.SetOutput(out)440		return err441	} else {442		// If help is called, regardless of other flags, we print that.443		// Print help also if c.Run is nil.444		if c.helpFlagVal || !c.Runnable() {445			c.Help()446			return nil447		}448449		c.preRun()450		argWoFlags := c.Flags().Args()451		c.Run(c, argWoFlags)452		return nil453	}454}455456func (c *Command) preRun() {457	for _, x := range initializers {458		x()459	}460}461462func (c *Command) errorMsgFromParse() string {463	s := c.flagErrorBuf.String()464465	x := strings.Split(s, "\n")466467	if len(x) > 0 {468		return x[0]469	} else {470		return ""471	}472}473474// Call execute to use the args (os.Args[1:] by default)475// and run through the command tree finding appropriate matches476// for commands and then corresponding flags.477func (c *Command) Execute() (err error) {478479	// Regardless of what command execute is called on, run on Root only480	if c.HasParent() {481		return c.Root().Execute()482	}483484	if EnableWindowsMouseTrap && runtime.GOOS == "windows" {485		if mousetrap.StartedByExplorer() {486			c.Print(MousetrapHelpText)487			time.Sleep(5 * time.Second)488			os.Exit(1)489		}490	}491492	// initialize help as the last point possible to allow for user493	// overriding494	c.initHelp()495496	var args []string497498	if len(c.args) == 0 {499		args = os.Args[1:]500	} else {501		args = c.args502	}503504	if len(args) == 0 {505		// Only the executable is called and the root is runnable, run it506		if c.Runnable() {507			err = c.execute([]string(nil))508		} else {509			c.Help()510		}511	} else {512		cmd, flags, e := c.Find(args)513		if e != nil {514			err = e515		} else {516			err = cmd.execute(flags)517		}518	}519520	if err != nil {521		if err == flag.ErrHelp {522			c.Help()523524		} else {525			c.Println("Error:", err.Error())526			c.Printf("Run '%v help' for usage.\n", c.Root().Name())527		}528	}529530	return531}532533func (c *Command) initHelp() {534	if c.helpCommand == nil {535		if !c.HasSubCommands() {536			return537		}538539		c.helpCommand = &Command{540			Use:   "help [command]",541			Short: "Help about any command",542			Long: `Help provides help for any command in the application.543    Simply type ` + c.Name() + ` help [path to command] for full details.`,544			Run: c.HelpFunc(),545		}546	}547	c.AddCommand(c.helpCommand)548}549550// Used for testing551func (c *Command) ResetCommands() {552	c.commands = nil553	c.helpCommand = nil554	c.cmdErrorBuf = new(bytes.Buffer)555	c.cmdErrorBuf.Reset()556}557558//Commands returns a slice of child commands.559func (c *Command) Commands() []*Command {560	return c.commands561}562563// AddCommand adds one or more commands to this parent command.564func (c *Command) AddCommand(cmds ...*Command) {565	for i, x := range cmds {566		if cmds[i] == c {567			panic("Command can't be a child of itself")568		}569		cmds[i].parent = c570		// update max lengths571		usageLen := len(x.Use)572		if usageLen > c.commandsMaxUseLen {573			c.commandsMaxUseLen = usageLen574		}575		commandPathLen := len(x.CommandPath())576		if commandPathLen > c.commandsMaxCommandPathLen {577			c.commandsMaxCommandPathLen = commandPathLen578		}579		nameLen := len(x.Name())580		if nameLen > c.commandsMaxNameLen {581			c.commandsMaxNameLen = nameLen582		}583		c.commands = append(c.commands, x)584	}585}586587// AddCommand removes one or more commands from a parent command.588func (c *Command) RemoveCommand(cmds ...*Command) {589	commands := []*Command{}590main:591	for _, command := range c.commands {592		for _, cmd := range cmds {593			if command == cmd {594				command.parent = nil595				continue main596			}597		}598		commands = append(commands, command)599	}600	c.commands = commands601	// recompute all lengths602	c.commandsMaxUseLen = 0603	c.commandsMaxCommandPathLen = 0604	c.commandsMaxNameLen = 0605	for _, command := range c.commands {606		usageLen := len(command.Use)607		if usageLen > c.commandsMaxUseLen {608			c.commandsMaxUseLen = usageLen609		}610		commandPathLen := len(command.CommandPath())611		if commandPathLen > c.commandsMaxCommandPathLen {612			c.commandsMaxCommandPathLen = commandPathLen613		}614		nameLen := len(command.Name())615		if nameLen > c.commandsMaxNameLen {616			c.commandsMaxNameLen = nameLen617		}618	}619}620621// Convenience method to Print to the defined output622func (c *Command) Print(i ...interface{}) {623	fmt.Fprint(c.Out(), i...)624}625626// Convenience method to Println to the defined output627func (c *Command) Println(i ...interface{}) {628	str := fmt.Sprintln(i...)629	c.Print(str)630}631632// Convenience method to Printf to the defined output633func (c *Command) Printf(format string, i ...interface{}) {634	str := fmt.Sprintf(format, i...)635	c.Print(str)636}637638// Output the usage for the command639// Used when a user provides invalid input640// Can be defined by user by overriding UsageFunc641func (c *Command) Usage() error {642	c.mergePersistentFlags()643	err := c.UsageFunc()(c)644	return err645}646647// Output the help for the command648// Used when a user calls help [command]649// by the default HelpFunc in the commander650func (c *Command) Help() error {651	c.mergePersistentFlags()652	err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)653	return err654}655656func (c *Command) UsageString() string {657	tmpOutput := c.output658	bb := new(bytes.Buffer)659	c.SetOutput(bb)660	c.Usage()661	c.output = tmpOutput662	return bb.String()663}664665// CommandPath returns the full path to this command.666func (c *Command) CommandPath() string {667	str := c.Name()668	x := c669	for x.HasParent() {670		str = x.parent.Name() + " " + str671		x = x.parent672	}673	return str674}675676//The full usage for a given command (including parents)677func (c *Command) UseLine() string {678	str := ""679	if c.HasParent() {680		str = c.parent.CommandPath() + " "681	}682	return str + c.Use683}684685// For use in determining which flags have been assigned to which commands686// and which persist687func (c *Command) DebugFlags() {688	c.Println("DebugFlags called on", c.Name())689	var debugflags func(*Command)690691	debugflags = func(x *Command) {692		if x.HasFlags() || x.HasPersistentFlags() {693			c.Println(x.Name())694		}695		if x.HasFlags() {696			x.flags.VisitAll(func(f *flag.Flag) {697				if x.HasPersistentFlags() {698					if x.persistentFlag(f.Name) == nil {699						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")700					} else {701						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [LP]")702					}703				} else {704					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")705				}706			})707		}708		if x.HasPersistentFlags() {709			x.pflags.VisitAll(func(f *flag.Flag) {710				if x.HasFlags() {711					if x.flags.Lookup(f.Name) == nil {712						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")713					}714				} else {715					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")716				}717			})718		}719		c.Println(x.flagErrorBuf)720		if x.HasSubCommands() {721			for _, y := range x.commands {722				debugflags(y)723			}724		}725	}726727	debugflags(c)728}729730// Name returns the command's name: the first word in the use line.731func (c *Command) Name() string {732	if c.name != "" {733		return c.name734	}735	name := c.Use736	i := strings.Index(name, " ")737	if i >= 0 {738		name = name[:i]739	}740	return name741}742743// Determine if a given string is an alias of the command.744func (c *Command) HasAlias(s string) bool {745	for _, a := range c.Aliases {746		if a == s {747			return true748		}749	}750	return false751}752753func (c *Command) NameAndAliases() string {754	return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")755}756757func (c *Command) HasExample() bool {758	return len(c.Example) > 0759}760761// Determine if the command is itself runnable762func (c *Command) Runnable() bool {763	return c.Run != nil764}765766// Determine if the command has children commands767func (c *Command) HasSubCommands() bool {768	return len(c.commands) > 0769}770771func (c *Command) HasRunnableSiblings() bool {772	if !c.HasParent() {773		return false774	}775	for _, sub := range c.parent.commands {776		if sub.Runnable() {777			return true778		}779	}780	return false781}782783func (c *Command) HasHelpSubCommands() bool {784	for _, sub := range c.commands {785		if !sub.Runnable() {786			return true787		}788	}789	return false790}791792// Determine if the command has runnable children commands793func (c *Command) HasRunnableSubCommands() bool {794	for _, sub := range c.commands {795		if sub.Runnable() {796			return true797		}798	}799	return false800}801802// Determine if the command is a child command803func (c *Command) HasParent() bool {804	return c.parent != nil805}806807// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)808func (c *Command) Flags() *flag.FlagSet {809	if c.flags == nil {810		c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)811		if c.flagErrorBuf == nil {812			c.flagErrorBuf = new(bytes.Buffer)813		}814		c.flags.SetOutput(c.flagErrorBuf)815		c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name())816	}817	return c.flags818}819820// Get the local FlagSet specifically set in the current command821func (c *Command) LocalFlags() *flag.FlagSet {822	c.mergePersistentFlags()823824	local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)825	c.lflags.VisitAll(func(f *flag.Flag) {826		local.AddFlag(f)827	})828	return local829}830831// All Flags which were inherited from parents commands832func (c *Command) InheritedFlags() *flag.FlagSet {833	c.mergePersistentFlags()834835	inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)836	local := c.LocalFlags()837838	var rmerge func(x *Command)839840	rmerge = func(x *Command) {841		if x.HasPersistentFlags() {842			x.PersistentFlags().VisitAll(func(f *flag.Flag) {843				if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {844					inherited.AddFlag(f)845				}846			})847		}848		if x.HasParent() {849			rmerge(x.parent)850		}851	}852853	if c.HasParent() {854		rmerge(c.parent)855	}856857	return inherited858}859860// All Flags which were not inherited from parent commands861func (c *Command) NonInheritedFlags() *flag.FlagSet {862	return c.LocalFlags()863}864865// Get the Persistent FlagSet specifically set in the current command866func (c *Command) PersistentFlags() *flag.FlagSet {867	if c.pflags == nil {868		c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)869		if c.flagErrorBuf == nil {870			c.flagErrorBuf = new(bytes.Buffer)871		}872		c.pflags.SetOutput(c.flagErrorBuf)873	}874	return c.pflags875}876877// For use in testing878func (c *Command) ResetFlags() {879	c.flagErrorBuf = new(bytes.Buffer)880	c.flagErrorBuf.Reset()881	c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)882	c.flags.SetOutput(c.flagErrorBuf)883	c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)884	c.pflags.SetOutput(c.flagErrorBuf)885}886887// Does the command contain any flags (local plus persistent from the entire structure)888func (c *Command) HasFlags() bool {889	return c.Flags().HasFlags()890}891892// Does the command contain persistent flags893func (c *Command) HasPersistentFlags() bool {894	return c.PersistentFlags().HasFlags()895}896897// Does the command has flags specifically declared locally898func (c *Command) HasLocalFlags() bool {899	return c.LocalFlags().HasFlags()900}901902func (c *Command) HasInheritedFlags() bool {903	return c.InheritedFlags().HasFlags()904}905906// Climbs up the command tree looking for matching flag907func (c *Command) Flag(name string) (flag *flag.Flag) {908	flag = c.Flags().Lookup(name)909910	if flag == nil {911		flag = c.persistentFlag(name)912	}913914	return915}916917// recursively find matching persistent flag918func (c *Command) persistentFlag(name string) (flag *flag.Flag) {919	if c.HasPersistentFlags() {920		flag = c.PersistentFlags().Lookup(name)921	}922923	if flag == nil && c.HasParent() {924		flag = c.parent.persistentFlag(name)925	}926	return927}928929// Parses persistent flag tree & local flags930func (c *Command) ParseFlags(args []string) (err error) {931	c.mergePersistentFlags()932	err = c.Flags().Parse(args)933	return934}935936func (c *Command) Parent() *Command {937	return c.parent938}939940func (c *Command) mergePersistentFlags() {941	var rmerge func(x *Command)942943	// Save the set of local flags944	if c.lflags == nil {945		c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)946		if c.flagErrorBuf == nil {947			c.flagErrorBuf = new(bytes.Buffer)948		}949		c.lflags.SetOutput(c.flagErrorBuf)950		addtolocal := func(f *flag.Flag) {951			c.lflags.AddFlag(f)952		}953		c.Flags().VisitAll(addtolocal)954		c.PersistentFlags().VisitAll(addtolocal)955	}956	rmerge = func(x *Command) {957		if x.HasPersistentFlags() {958			x.PersistentFlags().VisitAll(func(f *flag.Flag) {959				if c.Flags().Lookup(f.Name) == nil {960					c.Flags().AddFlag(f)961				}962			})963		}964		if x.HasParent() {965			rmerge(x.parent)966		}967	}968969	rmerge(c)970}