Skip to content
Myr

command.go

This file

Path

command.go

903 lines · 22.0 KiB · Go

Last changed by

Remove specail casing in Execute()Eric Parisbefore adoption794a362

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	"strings"2425	flag "github.com/spf13/pflag"26)2728// Command is just that, a command for your application.29// eg.  'go run' ... 'run' is the command. Cobra requires30// you to define the usage and description as part of your command31// definition to ensure usability.32type Command struct {33	// Name is the command name, usually the executable's name.34	name string35	// The one-line usage message.36	Use string37	// An array of aliases that can be used instead of the first word in Use.38	Aliases []string39	// The short description shown in the 'help' output.40	Short string41	// The long message shown in the 'help <this-command>' output.42	Long string43	// Examples of how to use the command44	Example string45	// Full set of flags46	flags *flag.FlagSet47	// Set of flags childrens of this command will inherit48	pflags *flag.FlagSet49	// Flags that are declared specifically by this command (not inherited).50	lflags *flag.FlagSet51	// Run runs the command.52	// The args are the arguments after the command name.53	Run func(cmd *Command, args []string)54	// Commands is the list of commands supported by this program.55	commands []*Command56	// Parent Command for this command57	parent *Command58	// max lengths of commands' string lengths for use in padding59	commandsMaxUseLen         int60	commandsMaxCommandPathLen int61	commandsMaxNameLen        int6263	flagErrorBuf *bytes.Buffer64	cmdErrorBuf  *bytes.Buffer6566	args          []string                 // actual args parsed from flags67	output        *io.Writer               // nil means stderr; use Out() method instead68	usageFunc     func(*Command) error     // Usage can be defined by application69	usageTemplate string                   // Can be defined by Application70	helpTemplate  string                   // Can be defined by Application71	helpFunc      func(*Command, []string) // Help can be defined by application72	helpCommand   *Command                 // The help command73	helpFlagVal   bool74}7576// os.Args[1:] by default, if desired, can be overridden77// particularly useful when testing.78func (c *Command) SetArgs(a []string) {79	c.args = a80}8182func (c *Command) getOut(def io.Writer) io.Writer {83	if c.output != nil {84		return *c.output85	}8687	if c.HasParent() {88		return c.parent.Out()89	} else {90		return def91	}92}9394func (c *Command) Out() io.Writer {95	return c.getOut(os.Stderr)96}9798func (c *Command) getOutOrStdout() io.Writer {99	return c.getOut(os.Stdout)100}101102// SetOutput sets the destination for usage and error messages.103// If output is nil, os.Stderr is used.104func (c *Command) SetOutput(output io.Writer) {105	c.output = &output106}107108// Usage can be defined by application109func (c *Command) SetUsageFunc(f func(*Command) error) {110	c.usageFunc = f111}112113// Can be defined by Application114func (c *Command) SetUsageTemplate(s string) {115	c.usageTemplate = s116}117118// Can be defined by Application119func (c *Command) SetHelpFunc(f func(*Command, []string)) {120	c.helpFunc = f121}122123func (c *Command) SetHelpCommand(cmd *Command) {124	c.helpCommand = cmd125}126127// Can be defined by Application128func (c *Command) SetHelpTemplate(s string) {129	c.helpTemplate = s130}131132func (c *Command) UsageFunc() (f func(*Command) error) {133	if c.usageFunc != nil {134		return c.usageFunc135	}136137	if c.HasParent() {138		return c.parent.UsageFunc()139	} else {140		return func(c *Command) error {141			err := tmpl(c.Out(), c.UsageTemplate(), c)142			return err143		}144	}145}146func (c *Command) HelpFunc() func(*Command, []string) {147	if c.helpFunc != nil {148		return c.helpFunc149	}150151	if c.HasParent() {152		return c.parent.HelpFunc()153	} else {154		return func(c *Command, args []string) {155			if len(args) == 0 {156				// Help called without any topic, calling on root157				c.Root().Help()158				return159			}160161			cmd, _, e := c.Root().Find(args)162			if cmd == nil || e != nil {163				c.Printf("Unknown help topic %#q.", args)164165				c.Root().Usage()166			} else {167				err := cmd.Help()168				if err != nil {169					c.Println(err)170				}171			}172		}173	}174}175176var minUsagePadding int = 25177178func (c *Command) UsagePadding() int {179	if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {180		return minUsagePadding181	} else {182		return c.parent.commandsMaxUseLen183	}184}185186var minCommandPathPadding int = 11187188//189func (c *Command) CommandPathPadding() int {190	if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {191		return minCommandPathPadding192	} else {193		return c.parent.commandsMaxCommandPathLen194	}195}196197var minNamePadding int = 11198199func (c *Command) NamePadding() int {200	if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {201		return minNamePadding202	} else {203		return c.parent.commandsMaxNameLen204	}205}206207func (c *Command) UsageTemplate() string {208	if c.usageTemplate != "" {209		return c.usageTemplate210	}211212	if c.HasParent() {213		return c.parent.UsageTemplate()214	} else {215		return `{{ $cmd := . }}216Usage: {{if .Runnable}}217  {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}218  {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}219220Aliases:221  {{.NameAndAliases}}222{{end}}{{if .HasExample}}223224Examples:225{{ .Example }}226{{end}}{{ if .HasSubCommands}}227228Available Commands: {{range .Commands}}{{if .Runnable}}229  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}230{{end}}231{{ if .HasLocalFlags}}Flags:232{{.LocalFlags.FlagUsages}}{{end}}233{{ if .HasInheritedFlags}}Global Flags:234{{.InheritedFlags.FlagUsages}}{{end}}{{if .HasParent}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}235Additional help topics: {{if gt .Commands 0 }}{{range .Commands}}{{if not .Runnable}} {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if gt .Parent.Commands 1 }}{{range .Parent.Commands}}{{if .Runnable}}{{if not (eq .Name $cmd.Name) }}{{end}}236  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{end}}237{{end}}{{ if .HasSubCommands }}238Use "{{.Root.Name}} help [command]" for more information about a command.239{{end}}`240	}241}242243func (c *Command) HelpTemplate() string {244	if c.helpTemplate != "" {245		return c.helpTemplate246	}247248	if c.HasParent() {249		return c.parent.HelpTemplate()250	} else {251		return `{{with or .Long .Short }}{{. | trim}}{{end}}252{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}253`254	}255}256257// Really only used when casting a command to a commander258func (c *Command) resetChildrensParents() {259	for _, x := range c.commands {260		x.parent = c261	}262}263264// Test if the named flag is a boolean flag.265func isBooleanFlag(name string, f *flag.FlagSet) bool {266	flag := f.Lookup(name)267	if flag == nil {268		return false269	}270	return flag.Value.Type() == "bool"271}272273// Test if the named flag is a boolean flag.274func isBooleanShortFlag(name string, f *flag.FlagSet) bool {275	result := false276	f.VisitAll(func(f *flag.Flag) {277		if f.Shorthand == name && f.Value.Type() == "bool" {278			result = true279		}280	})281	return result282}283284func stripFlags(args []string, c *Command) []string {285	if len(args) < 1 {286		return args287	}288	c.mergePersistentFlags()289290	commands := []string{}291292	inQuote := false293	inFlag := false294	for _, y := range args {295		if !inQuote {296			switch {297			case strings.HasPrefix(y, "\""):298				inQuote = true299			case strings.Contains(y, "=\""):300				inQuote = true301			case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):302				// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'303				inFlag = !isBooleanFlag(y[2:], c.Flags())304			case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):305				inFlag = true306			case inFlag:307				inFlag = false308			case y == "":309				// strip empty commands, as the go tests expect this to be ok....310			case !strings.HasPrefix(y, "-"):311				commands = append(commands, y)312				inFlag = false313			}314		}315316		if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {317			inQuote = false318		}319	}320321	return commands322}323324func argsMinusX(args []string, x string) []string {325	newargs := []string{}326327	for _, y := range args {328		if x != y {329			newargs = append(newargs, y)330		}331	}332	return newargs333}334335// find the target command given the args and command tree336// Meant to be run on the highest node. Only searches down.337func (c *Command) Find(arrs []string) (*Command, []string, error) {338	if c == nil {339		return nil, nil, fmt.Errorf("Called find() on a nil Command")340	}341342	if len(arrs) == 0 {343		return c.Root(), arrs, nil344	}345346	var innerfind func(*Command, []string) (*Command, []string)347348	innerfind = func(c *Command, args []string) (*Command, []string) {349		if len(args) > 0 && c.HasSubCommands() {350			argsWOflags := stripFlags(args, c)351			if len(argsWOflags) > 0 {352				matches := make([]*Command, 0)353				for _, cmd := range c.commands {354					if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match355						return innerfind(cmd, argsMinusX(args, argsWOflags[0]))356					} else if EnablePrefixMatching {357						if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match358							matches = append(matches, cmd)359						}360						for _, x := range cmd.Aliases {361							if strings.HasPrefix(x, argsWOflags[0]) {362								matches = append(matches, cmd)363							}364						}365					}366				}367368				// only accept a single prefix match - multiple matches would be ambiguous369				if len(matches) == 1 {370					return innerfind(matches[0], argsMinusX(args, argsWOflags[0]))371				}372			}373		}374375		return c, args376	}377378	commandFound, a := innerfind(c, arrs)379380	// If we matched on the root, but we asked for a subcommand, return an error381	if commandFound.Name() == c.Name() && len(stripFlags(arrs, c)) > 0 && commandFound.Name() != arrs[0] {382		return nil, a, fmt.Errorf("unknown command %q", a[0])383	}384385	return commandFound, a, nil386}387388func (c *Command) Root() *Command {389	var findRoot func(*Command) *Command390391	findRoot = func(x *Command) *Command {392		if x.HasParent() {393			return findRoot(x.parent)394		} else {395			return x396		}397	}398399	return findRoot(c)400}401402func (c *Command) execute(a []string) (err error) {403	if c == nil {404		return fmt.Errorf("Called Execute() on a nil Command")405	}406407	err = c.ParseFlags(a)408	if err == flag.ErrHelp {409		c.Help()410		return nil411	}412	if err != nil {413		// We're writing subcommand usage to root command's error buffer to have it displayed to the user414		r := c.Root()415		if r.cmdErrorBuf == nil {416			r.cmdErrorBuf = new(bytes.Buffer)417		}418		// for writing the usage to the buffer we need to switch the output temporarily419		// since Out() returns root output, you also need to revert that on root420		out := r.Out()421		r.SetOutput(r.cmdErrorBuf)422		c.Usage()423		r.SetOutput(out)424		return err425	}426	// If help is called, regardless of other flags, we print that.427	// Print help also if c.Run is nil.428	if c.helpFlagVal || !c.Runnable() {429		c.Help()430		return nil431	}432433	c.preRun()434	argWoFlags := c.Flags().Args()435	c.Run(c, argWoFlags)436	return nil437}438439func (c *Command) preRun() {440	for _, x := range initializers {441		x()442	}443}444445func (c *Command) errorMsgFromParse() string {446	s := c.flagErrorBuf.String()447448	x := strings.Split(s, "\n")449450	if len(x) > 0 {451		return x[0]452	} else {453		return ""454	}455}456457// Call execute to use the args (os.Args[1:] by default)458// and run through the command tree finding appropriate matches459// for commands and then corresponding flags.460func (c *Command) Execute() (err error) {461462	// Regardless of what command execute is called on, run on Root only463	if c.HasParent() {464		return c.Root().Execute()465	}466467	// initialize help as the last point possible to allow for user468	// overriding469	c.initHelp()470471	var args []string472473	if len(c.args) == 0 {474		args = os.Args[1:]475	} else {476		args = c.args477	}478479	cmd, flags, err := c.Find(args)480	if err == nil {481		err = cmd.execute(flags)482	}483484	if err != nil {485		if err == flag.ErrHelp {486			c.Help()487488		} else {489			c.Println("Error:", err.Error())490			c.Printf("Run '%v help' for usage.\n", c.Root().Name())491		}492	}493494	return495}496497func (c *Command) initHelp() {498	if c.helpCommand == nil {499		if !c.HasSubCommands() {500			return501		}502503		c.helpCommand = &Command{504			Use:   "help [command]",505			Short: "Help about any command",506			Long: `Help provides help for any command in the application.507    Simply type ` + c.Name() + ` help [path to command] for full details.`,508			Run: c.HelpFunc(),509		}510	}511	c.AddCommand(c.helpCommand)512}513514// Used for testing515func (c *Command) ResetCommands() {516	c.commands = nil517	c.helpCommand = nil518	c.cmdErrorBuf = new(bytes.Buffer)519	c.cmdErrorBuf.Reset()520}521522//Commands returns a slice of child commands.523func (c *Command) Commands() []*Command {524	return c.commands525}526527// AddCommand adds one or more commands to this parent command.528func (c *Command) AddCommand(cmds ...*Command) {529	for i, x := range cmds {530		if cmds[i] == c {531			panic("Command can't be a child of itself")532		}533		cmds[i].parent = c534		// update max lengths535		usageLen := len(x.Use)536		if usageLen > c.commandsMaxUseLen {537			c.commandsMaxUseLen = usageLen538		}539		commandPathLen := len(x.CommandPath())540		if commandPathLen > c.commandsMaxCommandPathLen {541			c.commandsMaxCommandPathLen = commandPathLen542		}543		nameLen := len(x.Name())544		if nameLen > c.commandsMaxNameLen {545			c.commandsMaxNameLen = nameLen546		}547		c.commands = append(c.commands, x)548	}549}550551// AddCommand removes one or more commands from a parent command.552func (c *Command) RemoveCommand(cmds ...*Command) {553	commands := []*Command{}554main:555	for _, command := range c.commands {556		for _, cmd := range cmds {557			if command == cmd {558				command.parent = nil559				continue main560			}561		}562		commands = append(commands, command)563	}564	c.commands = commands565	// recompute all lengths566	c.commandsMaxUseLen = 0567	c.commandsMaxCommandPathLen = 0568	c.commandsMaxNameLen = 0569	for _, command := range c.commands {570		usageLen := len(command.Use)571		if usageLen > c.commandsMaxUseLen {572			c.commandsMaxUseLen = usageLen573		}574		commandPathLen := len(command.CommandPath())575		if commandPathLen > c.commandsMaxCommandPathLen {576			c.commandsMaxCommandPathLen = commandPathLen577		}578		nameLen := len(command.Name())579		if nameLen > c.commandsMaxNameLen {580			c.commandsMaxNameLen = nameLen581		}582	}583}584585// Convenience method to Print to the defined output586func (c *Command) Print(i ...interface{}) {587	fmt.Fprint(c.Out(), i...)588}589590// Convenience method to Println to the defined output591func (c *Command) Println(i ...interface{}) {592	str := fmt.Sprintln(i...)593	c.Print(str)594}595596// Convenience method to Printf to the defined output597func (c *Command) Printf(format string, i ...interface{}) {598	str := fmt.Sprintf(format, i...)599	c.Print(str)600}601602// Output the usage for the command603// Used when a user provides invalid input604// Can be defined by user by overriding UsageFunc605func (c *Command) Usage() error {606	c.mergePersistentFlags()607	err := c.UsageFunc()(c)608	return err609}610611// Output the help for the command612// Used when a user calls help [command]613// by the default HelpFunc in the commander614func (c *Command) Help() error {615	c.mergePersistentFlags()616	err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)617	return err618}619620func (c *Command) UsageString() string {621	tmpOutput := c.output622	bb := new(bytes.Buffer)623	c.SetOutput(bb)624	c.Usage()625	c.output = tmpOutput626	return bb.String()627}628629// CommandPath returns the full path to this command.630func (c *Command) CommandPath() string {631	str := c.Name()632	x := c633	for x.HasParent() {634		str = x.parent.Name() + " " + str635		x = x.parent636	}637	return str638}639640//The full usage for a given command (including parents)641func (c *Command) UseLine() string {642	str := ""643	if c.HasParent() {644		str = c.parent.CommandPath() + " "645	}646	return str + c.Use647}648649// For use in determining which flags have been assigned to which commands650// and which persist651func (c *Command) DebugFlags() {652	c.Println("DebugFlags called on", c.Name())653	var debugflags func(*Command)654655	debugflags = func(x *Command) {656		if x.HasFlags() || x.HasPersistentFlags() {657			c.Println(x.Name())658		}659		if x.HasFlags() {660			x.flags.VisitAll(func(f *flag.Flag) {661				if x.HasPersistentFlags() {662					if x.persistentFlag(f.Name) == nil {663						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")664					} else {665						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [LP]")666					}667				} else {668					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")669				}670			})671		}672		if x.HasPersistentFlags() {673			x.pflags.VisitAll(func(f *flag.Flag) {674				if x.HasFlags() {675					if x.flags.Lookup(f.Name) == nil {676						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")677					}678				} else {679					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")680				}681			})682		}683		c.Println(x.flagErrorBuf)684		if x.HasSubCommands() {685			for _, y := range x.commands {686				debugflags(y)687			}688		}689	}690691	debugflags(c)692}693694// Name returns the command's name: the first word in the use line.695func (c *Command) Name() string {696	if c.name != "" {697		return c.name698	}699	name := c.Use700	i := strings.Index(name, " ")701	if i >= 0 {702		name = name[:i]703	}704	return name705}706707// Determine if a given string is an alias of the command.708func (c *Command) HasAlias(s string) bool {709	for _, a := range c.Aliases {710		if a == s {711			return true712		}713	}714	return false715}716717func (c *Command) NameAndAliases() string {718	return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")719}720721func (c *Command) HasExample() bool {722	return len(c.Example) > 0723}724725// Determine if the command is itself runnable726func (c *Command) Runnable() bool {727	return c.Run != nil728}729730// Determine if the command has children commands731func (c *Command) HasSubCommands() bool {732	return len(c.commands) > 0733}734735// Determine if the command is a child command736func (c *Command) HasParent() bool {737	return c.parent != nil738}739740// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)741func (c *Command) Flags() *flag.FlagSet {742	if c.flags == nil {743		c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)744		if c.flagErrorBuf == nil {745			c.flagErrorBuf = new(bytes.Buffer)746		}747		c.flags.SetOutput(c.flagErrorBuf)748		c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name())749	}750	return c.flags751}752753// Get the local FlagSet specifically set in the current command754func (c *Command) LocalFlags() *flag.FlagSet {755	c.mergePersistentFlags()756757	local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)758	c.lflags.VisitAll(func(f *flag.Flag) {759		local.AddFlag(f)760	})761	return local762}763764// All Flags which were inherited from parents commands765func (c *Command) InheritedFlags() *flag.FlagSet {766	c.mergePersistentFlags()767768	inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)769	local := c.LocalFlags()770771	var rmerge func(x *Command)772773	rmerge = func(x *Command) {774		if x.HasPersistentFlags() {775			x.PersistentFlags().VisitAll(func(f *flag.Flag) {776				if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {777					inherited.AddFlag(f)778				}779			})780		}781		if x.HasParent() {782			rmerge(x.parent)783		}784	}785786	if c.HasParent() {787		rmerge(c.parent)788	}789790	return inherited791}792793// All Flags which were not inherited from parent commands794func (c *Command) NonInheritedFlags() *flag.FlagSet {795	return c.LocalFlags()796}797798// Get the Persistent FlagSet specifically set in the current command799func (c *Command) PersistentFlags() *flag.FlagSet {800	if c.pflags == nil {801		c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)802		if c.flagErrorBuf == nil {803			c.flagErrorBuf = new(bytes.Buffer)804		}805		c.pflags.SetOutput(c.flagErrorBuf)806	}807	return c.pflags808}809810// For use in testing811func (c *Command) ResetFlags() {812	c.flagErrorBuf = new(bytes.Buffer)813	c.flagErrorBuf.Reset()814	c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)815	c.flags.SetOutput(c.flagErrorBuf)816	c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)817	c.pflags.SetOutput(c.flagErrorBuf)818}819820// Does the command contain any flags (local plus persistent from the entire structure)821func (c *Command) HasFlags() bool {822	return c.Flags().HasFlags()823}824825// Does the command contain persistent flags826func (c *Command) HasPersistentFlags() bool {827	return c.PersistentFlags().HasFlags()828}829830// Does the command has flags specifically declared locally831func (c *Command) HasLocalFlags() bool {832	return c.LocalFlags().HasFlags()833}834835func (c *Command) HasInheritedFlags() bool {836	return c.InheritedFlags().HasFlags()837}838839// Climbs up the command tree looking for matching flag840func (c *Command) Flag(name string) (flag *flag.Flag) {841	flag = c.Flags().Lookup(name)842843	if flag == nil {844		flag = c.persistentFlag(name)845	}846847	return848}849850// recursively find matching persistent flag851func (c *Command) persistentFlag(name string) (flag *flag.Flag) {852	if c.HasPersistentFlags() {853		flag = c.PersistentFlags().Lookup(name)854	}855856	if flag == nil && c.HasParent() {857		flag = c.parent.persistentFlag(name)858	}859	return860}861862// Parses persistent flag tree & local flags863func (c *Command) ParseFlags(args []string) (err error) {864	c.mergePersistentFlags()865	err = c.Flags().Parse(args)866	return867}868869func (c *Command) Parent() *Command {870	return c.parent871}872873func (c *Command) mergePersistentFlags() {874	var rmerge func(x *Command)875876	// Save the set of local flags877	if c.lflags == nil {878		c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)879		if c.flagErrorBuf == nil {880			c.flagErrorBuf = new(bytes.Buffer)881		}882		c.lflags.SetOutput(c.flagErrorBuf)883		addtolocal := func(f *flag.Flag) {884			c.lflags.AddFlag(f)885		}886		c.Flags().VisitAll(addtolocal)887		c.PersistentFlags().VisitAll(addtolocal)888	}889	rmerge = func(x *Command) {890		if x.HasPersistentFlags() {891			x.PersistentFlags().VisitAll(func(f *flag.Flag) {892				if c.Flags().Lookup(f.Name) == nil {893					c.Flags().AddFlag(f)894				}895			})896		}897		if x.HasParent() {898			rmerge(x.parent)899		}900	}901902	rmerge(c)903}