command.go
This file
Path
command.go
1,695 lines · 47.7 KiB · Go
Last changed by
Add ability to mark flags as required or exclusive as a group (#1654)John Schnakebefore adoption68b6b24
History of this fileTake 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 shell completions67 ValidArgs []string68 // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell 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 shell completion,78 // but accepted if entered manually.79 ArgAliases []string8081 // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.82 // For portability with other shells, it is recommended to instead use ValidArgsFunction83 BashCompletionFunction string8485 // Deprecated defines, if this command is deprecated and should print this string when used.86 Deprecated string8788 // Annotations are key/value pairs that can be used by applications to identify or89 // group commands.90 Annotations map[string]string9192 // Version defines the version for this command. If this value is non-empty and the command does not93 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,94 // will print content of the "Version" variable. A shorthand "v" flag will also be added if the95 // command does not define one.96 Version string9798 // The *Run functions are executed in the following order:99 // * PersistentPreRun()100 // * PreRun()101 // * Run()102 // * PostRun()103 // * PersistentPostRun()104 // All functions get the same args, the arguments after the command name.105 //106 // PersistentPreRun: children of this command will inherit and execute.107 PersistentPreRun func(cmd *Command, args []string)108 // PersistentPreRunE: PersistentPreRun but returns an error.109 PersistentPreRunE func(cmd *Command, args []string) error110 // PreRun: children of this command will not inherit.111 PreRun func(cmd *Command, args []string)112 // PreRunE: PreRun but returns an error.113 PreRunE func(cmd *Command, args []string) error114 // Run: Typically the actual work function. Most commands will only implement this.115 Run func(cmd *Command, args []string)116 // RunE: Run but returns an error.117 RunE func(cmd *Command, args []string) error118 // PostRun: run after the Run command.119 PostRun func(cmd *Command, args []string)120 // PostRunE: PostRun but returns an error.121 PostRunE func(cmd *Command, args []string) error122 // PersistentPostRun: children of this command will inherit and execute after PostRun.123 PersistentPostRun func(cmd *Command, args []string)124 // PersistentPostRunE: PersistentPostRun but returns an error.125 PersistentPostRunE func(cmd *Command, args []string) error126127 // args is actual args parsed from flags.128 args []string129 // flagErrorBuf contains all error messages from pflag.130 flagErrorBuf *bytes.Buffer131 // flags is full set of flags.132 flags *flag.FlagSet133 // pflags contains persistent flags.134 pflags *flag.FlagSet135 // lflags contains local flags.136 lflags *flag.FlagSet137 // iflags contains inherited flags.138 iflags *flag.FlagSet139 // parentsPflags is all persistent flags of cmd's parents.140 parentsPflags *flag.FlagSet141 // globNormFunc is the global normalization function142 // that we can use on every pflag set and children commands143 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName144145 // usageFunc is usage func defined by user.146 usageFunc func(*Command) error147 // usageTemplate is usage template defined by user.148 usageTemplate string149 // flagErrorFunc is func defined by user and it's called when the parsing of150 // flags returns an error.151 flagErrorFunc func(*Command, error) error152 // helpTemplate is help template defined by user.153 helpTemplate string154 // helpFunc is help func defined by user.155 helpFunc func(*Command, []string)156 // helpCommand is command with usage 'help'. If it's not defined by user,157 // cobra uses default help command.158 helpCommand *Command159 // versionTemplate is the version template defined by user.160 versionTemplate string161162 // inReader is a reader defined by the user that replaces stdin163 inReader io.Reader164 // outWriter is a writer defined by the user that replaces stdout165 outWriter io.Writer166 // errWriter is a writer defined by the user that replaces stderr167 errWriter io.Writer168169 // FParseErrWhitelist flag parse errors to be ignored170 FParseErrWhitelist FParseErrWhitelist171172 // CompletionOptions is a set of options to control the handling of shell completion173 CompletionOptions CompletionOptions174175 // commandsAreSorted defines, if command slice are sorted or not.176 commandsAreSorted bool177 // commandCalledAs is the name or alias value used to call this command.178 commandCalledAs struct {179 name string180 called bool181 }182183 ctx context.Context184185 // commands is the list of commands supported by this program.186 commands []*Command187 // parent is a parent command for this command.188 parent *Command189 // Max lengths of commands' string lengths for use in padding.190 commandsMaxUseLen int191 commandsMaxCommandPathLen int192 commandsMaxNameLen int193194 // TraverseChildren parses flags on all parents before executing child command.195 TraverseChildren bool196197 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.198 Hidden bool199200 // SilenceErrors is an option to quiet errors down stream.201 SilenceErrors bool202203 // SilenceUsage is an option to silence usage when an error occurs.204 SilenceUsage bool205206 // DisableFlagParsing disables the flag parsing.207 // If this is true all flags will be passed to the command as arguments.208 DisableFlagParsing bool209210 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")211 // will be printed by generating docs for this command.212 DisableAutoGenTag bool213214 // DisableFlagsInUseLine will disable the addition of [flags] to the usage215 // line of a command when printing help or generating docs216 DisableFlagsInUseLine bool217218 // DisableSuggestions disables the suggestions based on Levenshtein distance219 // that go along with 'unknown command' messages.220 DisableSuggestions bool221222 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.223 // Must be > 0.224 SuggestionsMinimumDistance int225}226227// Context returns underlying command context. If command was executed228// with ExecuteContext or the context was set with SetContext, the229// previously set context will be returned. Otherwise, nil is returned.230//231// Notice that a call to Execute and ExecuteC will replace a nil context of232// a command with a context.Background, so a background context will be233// returned by Context after one of these functions has been called.234func (c *Command) Context() context.Context {235 return c.ctx236}237238// SetContext sets context for the command. It is set to context.Background by default and will be overwritten by239// Command.ExecuteContext or Command.ExecuteContextC240func (c *Command) SetContext(ctx context.Context) {241 c.ctx = ctx242}243244// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden245// particularly useful when testing.246func (c *Command) SetArgs(a []string) {247 c.args = a248}249250// SetOutput sets the destination for usage and error messages.251// If output is nil, os.Stderr is used.252// Deprecated: Use SetOut and/or SetErr instead253func (c *Command) SetOutput(output io.Writer) {254 c.outWriter = output255 c.errWriter = output256}257258// SetOut sets the destination for usage messages.259// If newOut is nil, os.Stdout is used.260func (c *Command) SetOut(newOut io.Writer) {261 c.outWriter = newOut262}263264// SetErr sets the destination for error messages.265// If newErr is nil, os.Stderr is used.266func (c *Command) SetErr(newErr io.Writer) {267 c.errWriter = newErr268}269270// SetIn sets the source for input data271// If newIn is nil, os.Stdin is used.272func (c *Command) SetIn(newIn io.Reader) {273 c.inReader = newIn274}275276// SetUsageFunc sets usage function. Usage can be defined by application.277func (c *Command) SetUsageFunc(f func(*Command) error) {278 c.usageFunc = f279}280281// SetUsageTemplate sets usage template. Can be defined by Application.282func (c *Command) SetUsageTemplate(s string) {283 c.usageTemplate = s284}285286// SetFlagErrorFunc sets a function to generate an error when flag parsing287// fails.288func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {289 c.flagErrorFunc = f290}291292// SetHelpFunc sets help function. Can be defined by Application.293func (c *Command) SetHelpFunc(f func(*Command, []string)) {294 c.helpFunc = f295}296297// SetHelpCommand sets help command.298func (c *Command) SetHelpCommand(cmd *Command) {299 c.helpCommand = cmd300}301302// SetHelpTemplate sets help template to be used. Application can use it to set custom template.303func (c *Command) SetHelpTemplate(s string) {304 c.helpTemplate = s305}306307// SetVersionTemplate sets version template to be used. Application can use it to set custom template.308func (c *Command) SetVersionTemplate(s string) {309 c.versionTemplate = s310}311312// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.313// The user should not have a cyclic dependency on commands.314func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {315 c.Flags().SetNormalizeFunc(n)316 c.PersistentFlags().SetNormalizeFunc(n)317 c.globNormFunc = n318319 for _, command := range c.commands {320 command.SetGlobalNormalizationFunc(n)321 }322}323324// OutOrStdout returns output to stdout.325func (c *Command) OutOrStdout() io.Writer {326 return c.getOut(os.Stdout)327}328329// OutOrStderr returns output to stderr330func (c *Command) OutOrStderr() io.Writer {331 return c.getOut(os.Stderr)332}333334// ErrOrStderr returns output to stderr335func (c *Command) ErrOrStderr() io.Writer {336 return c.getErr(os.Stderr)337}338339// InOrStdin returns input to stdin340func (c *Command) InOrStdin() io.Reader {341 return c.getIn(os.Stdin)342}343344func (c *Command) getOut(def io.Writer) io.Writer {345 if c.outWriter != nil {346 return c.outWriter347 }348 if c.HasParent() {349 return c.parent.getOut(def)350 }351 return def352}353354func (c *Command) getErr(def io.Writer) io.Writer {355 if c.errWriter != nil {356 return c.errWriter357 }358 if c.HasParent() {359 return c.parent.getErr(def)360 }361 return def362}363364func (c *Command) getIn(def io.Reader) io.Reader {365 if c.inReader != nil {366 return c.inReader367 }368 if c.HasParent() {369 return c.parent.getIn(def)370 }371 return def372}373374// UsageFunc returns either the function set by SetUsageFunc for this command375// or a parent, or it returns a default usage function.376func (c *Command) UsageFunc() (f func(*Command) error) {377 if c.usageFunc != nil {378 return c.usageFunc379 }380 if c.HasParent() {381 return c.Parent().UsageFunc()382 }383 return func(c *Command) error {384 c.mergePersistentFlags()385 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)386 if err != nil {387 c.PrintErrln(err)388 }389 return err390 }391}392393// Usage puts out the usage for the command.394// Used when a user provides invalid input.395// Can be defined by user by overriding UsageFunc.396func (c *Command) Usage() error {397 return c.UsageFunc()(c)398}399400// HelpFunc returns either the function set by SetHelpFunc for this command401// or a parent, or it returns a function with default help behavior.402func (c *Command) HelpFunc() func(*Command, []string) {403 if c.helpFunc != nil {404 return c.helpFunc405 }406 if c.HasParent() {407 return c.Parent().HelpFunc()408 }409 return func(c *Command, a []string) {410 c.mergePersistentFlags()411 // The help should be sent to stdout412 // See https://github.com/spf13/cobra/issues/1002413 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)414 if err != nil {415 c.PrintErrln(err)416 }417 }418}419420// Help puts out the help for the command.421// Used when a user calls help [command].422// Can be defined by user by overriding HelpFunc.423func (c *Command) Help() error {424 c.HelpFunc()(c, []string{})425 return nil426}427428// UsageString returns usage string.429func (c *Command) UsageString() string {430 // Storing normal writers431 tmpOutput := c.outWriter432 tmpErr := c.errWriter433434 bb := new(bytes.Buffer)435 c.outWriter = bb436 c.errWriter = bb437438 CheckErr(c.Usage())439440 // Setting things back to normal441 c.outWriter = tmpOutput442 c.errWriter = tmpErr443444 return bb.String()445}446447// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this448// command or a parent, or it returns a function which returns the original449// error.450func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {451 if c.flagErrorFunc != nil {452 return c.flagErrorFunc453 }454455 if c.HasParent() {456 return c.parent.FlagErrorFunc()457 }458 return func(c *Command, err error) error {459 return err460 }461}462463var minUsagePadding = 25464465// UsagePadding return padding for the usage.466func (c *Command) UsagePadding() int {467 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {468 return minUsagePadding469 }470 return c.parent.commandsMaxUseLen471}472473var minCommandPathPadding = 11474475// CommandPathPadding return padding for the command path.476func (c *Command) CommandPathPadding() int {477 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {478 return minCommandPathPadding479 }480 return c.parent.commandsMaxCommandPathLen481}482483var minNamePadding = 11484485// NamePadding returns padding for the name.486func (c *Command) NamePadding() int {487 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {488 return minNamePadding489 }490 return c.parent.commandsMaxNameLen491}492493// UsageTemplate returns usage template for the command.494func (c *Command) UsageTemplate() string {495 if c.usageTemplate != "" {496 return c.usageTemplate497 }498499 if c.HasParent() {500 return c.parent.UsageTemplate()501 }502 return `Usage:{{if .Runnable}}503 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}504 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}505506Aliases:507 {{.NameAndAliases}}{{end}}{{if .HasExample}}508509Examples:510{{.Example}}{{end}}{{if .HasAvailableSubCommands}}511512Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}513 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}514515Flags:516{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}517518Global Flags:519{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}520521Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}522 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}523524Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}525`526}527528// HelpTemplate return help template for the command.529func (c *Command) HelpTemplate() string {530 if c.helpTemplate != "" {531 return c.helpTemplate532 }533534 if c.HasParent() {535 return c.parent.HelpTemplate()536 }537 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}538539{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`540}541542// VersionTemplate return version template for the command.543func (c *Command) VersionTemplate() string {544 if c.versionTemplate != "" {545 return c.versionTemplate546 }547548 if c.HasParent() {549 return c.parent.VersionTemplate()550 }551 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}552`553}554555func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {556 flag := fs.Lookup(name)557 if flag == nil {558 return false559 }560 return flag.NoOptDefVal != ""561}562563func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {564 if len(name) == 0 {565 return false566 }567568 flag := fs.ShorthandLookup(name[:1])569 if flag == nil {570 return false571 }572 return flag.NoOptDefVal != ""573}574575func stripFlags(args []string, c *Command) []string {576 if len(args) == 0 {577 return args578 }579 c.mergePersistentFlags()580581 commands := []string{}582 flags := c.Flags()583584Loop:585 for len(args) > 0 {586 s := args[0]587 args = args[1:]588 switch {589 case s == "--":590 // "--" terminates the flags591 break Loop592 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):593 // If '--flag arg' then594 // delete arg from args.595 fallthrough // (do the same as below)596 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):597 // If '-f arg' then598 // delete 'arg' from args or break the loop if len(args) <= 1.599 if len(args) <= 1 {600 break Loop601 } else {602 args = args[1:]603 continue604 }605 case s != "" && !strings.HasPrefix(s, "-"):606 commands = append(commands, s)607 }608 }609610 return commands611}612613// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like614// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).615func argsMinusFirstX(args []string, x string) []string {616 for i, y := range args {617 if x == y {618 ret := []string{}619 ret = append(ret, args[:i]...)620 ret = append(ret, args[i+1:]...)621 return ret622 }623 }624 return args625}626627func isFlagArg(arg string) bool {628 return ((len(arg) >= 3 && arg[1] == '-') ||629 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))630}631632// Find the target command given the args and command tree633// Meant to be run on the highest node. Only searches down.634func (c *Command) Find(args []string) (*Command, []string, error) {635 var innerfind func(*Command, []string) (*Command, []string)636637 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {638 argsWOflags := stripFlags(innerArgs, c)639 if len(argsWOflags) == 0 {640 return c, innerArgs641 }642 nextSubCmd := argsWOflags[0]643644 cmd := c.findNext(nextSubCmd)645 if cmd != nil {646 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))647 }648 return c, innerArgs649 }650651 commandFound, a := innerfind(c, args)652 if commandFound.Args == nil {653 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))654 }655 return commandFound, a, nil656}657658func (c *Command) findSuggestions(arg string) string {659 if c.DisableSuggestions {660 return ""661 }662 if c.SuggestionsMinimumDistance <= 0 {663 c.SuggestionsMinimumDistance = 2664 }665 suggestionsString := ""666 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {667 suggestionsString += "\n\nDid you mean this?\n"668 for _, s := range suggestions {669 suggestionsString += fmt.Sprintf("\t%v\n", s)670 }671 }672 return suggestionsString673}674675func (c *Command) findNext(next string) *Command {676 matches := make([]*Command, 0)677 for _, cmd := range c.commands {678 if cmd.Name() == next || cmd.HasAlias(next) {679 cmd.commandCalledAs.name = next680 return cmd681 }682 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {683 matches = append(matches, cmd)684 }685 }686687 if len(matches) == 1 {688 return matches[0]689 }690691 return nil692}693694// Traverse the command tree to find the command, and parse args for695// each parent.696func (c *Command) Traverse(args []string) (*Command, []string, error) {697 flags := []string{}698 inFlag := false699700 for i, arg := range args {701 switch {702 // A long flag with a space separated value703 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):704 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'705 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())706 flags = append(flags, arg)707 continue708 // A short flag with a space separated value709 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):710 inFlag = true711 flags = append(flags, arg)712 continue713 // The value for a flag714 case inFlag:715 inFlag = false716 flags = append(flags, arg)717 continue718 // A flag without a value, or with an `=` separated value719 case isFlagArg(arg):720 flags = append(flags, arg)721 continue722 }723724 cmd := c.findNext(arg)725 if cmd == nil {726 return c, args, nil727 }728729 if err := c.ParseFlags(flags); err != nil {730 return nil, args, err731 }732 return cmd.Traverse(args[i+1:])733 }734 return c, args, nil735}736737// SuggestionsFor provides suggestions for the typedName.738func (c *Command) SuggestionsFor(typedName string) []string {739 suggestions := []string{}740 for _, cmd := range c.commands {741 if cmd.IsAvailableCommand() {742 levenshteinDistance := ld(typedName, cmd.Name(), true)743 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance744 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))745 if suggestByLevenshtein || suggestByPrefix {746 suggestions = append(suggestions, cmd.Name())747 }748 for _, explicitSuggestion := range cmd.SuggestFor {749 if strings.EqualFold(typedName, explicitSuggestion) {750 suggestions = append(suggestions, cmd.Name())751 }752 }753 }754 }755 return suggestions756}757758// VisitParents visits all parents of the command and invokes fn on each parent.759func (c *Command) VisitParents(fn func(*Command)) {760 if c.HasParent() {761 fn(c.Parent())762 c.Parent().VisitParents(fn)763 }764}765766// Root finds root command.767func (c *Command) Root() *Command {768 if c.HasParent() {769 return c.Parent().Root()770 }771 return c772}773774// ArgsLenAtDash will return the length of c.Flags().Args at the moment775// when a -- was found during args parsing.776func (c *Command) ArgsLenAtDash() int {777 return c.Flags().ArgsLenAtDash()778}779780func (c *Command) execute(a []string) (err error) {781 if c == nil {782 return fmt.Errorf("Called Execute() on a nil Command")783 }784785 if len(c.Deprecated) > 0 {786 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)787 }788789 // initialize help and version flag at the last point possible to allow for user790 // overriding791 c.InitDefaultHelpFlag()792 c.InitDefaultVersionFlag()793794 err = c.ParseFlags(a)795 if err != nil {796 return c.FlagErrorFunc()(c, err)797 }798799 // If help is called, regardless of other flags, return we want help.800 // Also say we need help if the command isn't runnable.801 helpVal, err := c.Flags().GetBool("help")802 if err != nil {803 // should be impossible to get here as we always declare a help804 // flag in InitDefaultHelpFlag()805 c.Println("\"help\" flag declared as non-bool. Please correct your code")806 return err807 }808809 if helpVal {810 return flag.ErrHelp811 }812813 // for back-compat, only add version flag behavior if version is defined814 if c.Version != "" {815 versionVal, err := c.Flags().GetBool("version")816 if err != nil {817 c.Println("\"version\" flag declared as non-bool. Please correct your code")818 return err819 }820 if versionVal {821 err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)822 if err != nil {823 c.Println(err)824 }825 return err826 }827 }828829 if !c.Runnable() {830 return flag.ErrHelp831 }832833 c.preRun()834835 argWoFlags := c.Flags().Args()836 if c.DisableFlagParsing {837 argWoFlags = a838 }839840 if err := c.ValidateArgs(argWoFlags); err != nil {841 return err842 }843844 for p := c; p != nil; p = p.Parent() {845 if p.PersistentPreRunE != nil {846 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {847 return err848 }849 break850 } else if p.PersistentPreRun != nil {851 p.PersistentPreRun(c, argWoFlags)852 break853 }854 }855 if c.PreRunE != nil {856 if err := c.PreRunE(c, argWoFlags); err != nil {857 return err858 }859 } else if c.PreRun != nil {860 c.PreRun(c, argWoFlags)861 }862863 if err := c.validateRequiredFlags(); err != nil {864 return err865 }866 if err := c.validateFlagGroups(); err != nil {867 return err868 }869870 if c.RunE != nil {871 if err := c.RunE(c, argWoFlags); err != nil {872 return err873 }874 } else {875 c.Run(c, argWoFlags)876 }877 if c.PostRunE != nil {878 if err := c.PostRunE(c, argWoFlags); err != nil {879 return err880 }881 } else if c.PostRun != nil {882 c.PostRun(c, argWoFlags)883 }884 for p := c; p != nil; p = p.Parent() {885 if p.PersistentPostRunE != nil {886 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {887 return err888 }889 break890 } else if p.PersistentPostRun != nil {891 p.PersistentPostRun(c, argWoFlags)892 break893 }894 }895896 return nil897}898899func (c *Command) preRun() {900 for _, x := range initializers {901 x()902 }903}904905// ExecuteContext is the same as Execute(), but sets the ctx on the command.906// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs907// functions.908func (c *Command) ExecuteContext(ctx context.Context) error {909 c.ctx = ctx910 return c.Execute()911}912913// Execute uses the args (os.Args[1:] by default)914// and run through the command tree finding appropriate matches915// for commands and then corresponding flags.916func (c *Command) Execute() error {917 _, err := c.ExecuteC()918 return err919}920921// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.922// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs923// functions.924func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {925 c.ctx = ctx926 return c.ExecuteC()927}928929// ExecuteC executes the command.930func (c *Command) ExecuteC() (cmd *Command, err error) {931 if c.ctx == nil {932 c.ctx = context.Background()933 }934935 // Regardless of what command execute is called on, run on Root only936 if c.HasParent() {937 return c.Root().ExecuteC()938 }939940 // windows hook941 if preExecHookFn != nil {942 preExecHookFn(c)943 }944945 // initialize help at the last point to allow for user overriding946 c.InitDefaultHelpCmd()947 // initialize completion at the last point to allow for user overriding948 c.initDefaultCompletionCmd()949950 args := c.args951952 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155953 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {954 args = os.Args[1:]955 }956957 // initialize the hidden command to be used for shell completion958 c.initCompleteCmd(args)959960 var flags []string961 if c.TraverseChildren {962 cmd, flags, err = c.Traverse(args)963 } else {964 cmd, flags, err = c.Find(args)965 }966 if err != nil {967 // If found parse to a subcommand and then failed, talk about the subcommand968 if cmd != nil {969 c = cmd970 }971 if !c.SilenceErrors {972 c.PrintErrln("Error:", err.Error())973 c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())974 }975 return c, err976 }977978 cmd.commandCalledAs.called = true979 if cmd.commandCalledAs.name == "" {980 cmd.commandCalledAs.name = cmd.Name()981 }982983 // We have to pass global context to children command984 // if context is present on the parent command.985 if cmd.ctx == nil {986 cmd.ctx = c.ctx987 }988989 err = cmd.execute(flags)990 if err != nil {991 // Always show help if requested, even if SilenceErrors is in992 // effect993 if err == flag.ErrHelp {994 cmd.HelpFunc()(cmd, args)995 return cmd, nil996 }997998 // If root command has SilenceErrors flagged,999 // all subcommands should respect it1000 if !cmd.SilenceErrors && !c.SilenceErrors {1001 c.PrintErrln("Error:", err.Error())1002 }10031004 // If root command has SilenceUsage flagged,1005 // all subcommands should respect it1006 if !cmd.SilenceUsage && !c.SilenceUsage {1007 c.Println(cmd.UsageString())1008 }1009 }1010 return cmd, err1011}10121013func (c *Command) ValidateArgs(args []string) error {1014 if c.Args == nil {1015 return nil1016 }1017 return c.Args(c, args)1018}10191020func (c *Command) validateRequiredFlags() error {1021 if c.DisableFlagParsing {1022 return nil1023 }10241025 flags := c.Flags()1026 missingFlagNames := []string{}1027 flags.VisitAll(func(pflag *flag.Flag) {1028 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]1029 if !found {1030 return1031 }1032 if (requiredAnnotation[0] == "true") && !pflag.Changed {1033 missingFlagNames = append(missingFlagNames, pflag.Name)1034 }1035 })10361037 if len(missingFlagNames) > 0 {1038 return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))1039 }1040 return nil1041}10421043// InitDefaultHelpFlag adds default help flag to c.1044// It is called automatically by executing the c or by calling help and usage.1045// If c already has help flag, it will do nothing.1046func (c *Command) InitDefaultHelpFlag() {1047 c.mergePersistentFlags()1048 if c.Flags().Lookup("help") == nil {1049 usage := "help for "1050 if c.Name() == "" {1051 usage += "this command"1052 } else {1053 usage += c.Name()1054 }1055 c.Flags().BoolP("help", "h", false, usage)1056 }1057}10581059// InitDefaultVersionFlag adds default version flag to c.1060// It is called automatically by executing the c.1061// If c already has a version flag, it will do nothing.1062// If c.Version is empty, it will do nothing.1063func (c *Command) InitDefaultVersionFlag() {1064 if c.Version == "" {1065 return1066 }10671068 c.mergePersistentFlags()1069 if c.Flags().Lookup("version") == nil {1070 usage := "version for "1071 if c.Name() == "" {1072 usage += "this command"1073 } else {1074 usage += c.Name()1075 }1076 if c.Flags().ShorthandLookup("v") == nil {1077 c.Flags().BoolP("version", "v", false, usage)1078 } else {1079 c.Flags().Bool("version", false, usage)1080 }1081 }1082}10831084// InitDefaultHelpCmd adds default help command to c.1085// It is called automatically by executing the c or by calling help and usage.1086// If c already has help command or c has no subcommands, it will do nothing.1087func (c *Command) InitDefaultHelpCmd() {1088 if !c.HasSubCommands() {1089 return1090 }10911092 if c.helpCommand == nil {1093 c.helpCommand = &Command{1094 Use: "help [command]",1095 Short: "Help about any command",1096 Long: `Help provides help for any command in the application.1097Simply type ` + c.Name() + ` help [path to command] for full details.`,1098 ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1099 var completions []string1100 cmd, _, e := c.Root().Find(args)1101 if e != nil {1102 return nil, ShellCompDirectiveNoFileComp1103 }1104 if cmd == nil {1105 // Root help command.1106 cmd = c.Root()1107 }1108 for _, subCmd := range cmd.Commands() {1109 if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {1110 if strings.HasPrefix(subCmd.Name(), toComplete) {1111 completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))1112 }1113 }1114 }1115 return completions, ShellCompDirectiveNoFileComp1116 },1117 Run: func(c *Command, args []string) {1118 cmd, _, e := c.Root().Find(args)1119 if cmd == nil || e != nil {1120 c.Printf("Unknown help topic %#q\n", args)1121 CheckErr(c.Root().Usage())1122 } else {1123 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1124 CheckErr(cmd.Help())1125 }1126 },1127 }1128 }1129 c.RemoveCommand(c.helpCommand)1130 c.AddCommand(c.helpCommand)1131}11321133// ResetCommands delete parent, subcommand and help command from c.1134func (c *Command) ResetCommands() {1135 c.parent = nil1136 c.commands = nil1137 c.helpCommand = nil1138 c.parentsPflags = nil1139}11401141// Sorts commands by their names.1142type commandSorterByName []*Command11431144func (c commandSorterByName) Len() int { return len(c) }1145func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }1146func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }11471148// Commands returns a sorted slice of child commands.1149func (c *Command) Commands() []*Command {1150 // do not sort commands if it already sorted or sorting was disabled1151 if EnableCommandSorting && !c.commandsAreSorted {1152 sort.Sort(commandSorterByName(c.commands))1153 c.commandsAreSorted = true1154 }1155 return c.commands1156}11571158// AddCommand adds one or more commands to this parent command.1159func (c *Command) AddCommand(cmds ...*Command) {1160 for i, x := range cmds {1161 if cmds[i] == c {1162 panic("Command can't be a child of itself")1163 }1164 cmds[i].parent = c1165 // update max lengths1166 usageLen := len(x.Use)1167 if usageLen > c.commandsMaxUseLen {1168 c.commandsMaxUseLen = usageLen1169 }1170 commandPathLen := len(x.CommandPath())1171 if commandPathLen > c.commandsMaxCommandPathLen {1172 c.commandsMaxCommandPathLen = commandPathLen1173 }1174 nameLen := len(x.Name())1175 if nameLen > c.commandsMaxNameLen {1176 c.commandsMaxNameLen = nameLen1177 }1178 // If global normalization function exists, update all children1179 if c.globNormFunc != nil {1180 x.SetGlobalNormalizationFunc(c.globNormFunc)1181 }1182 c.commands = append(c.commands, x)1183 c.commandsAreSorted = false1184 }1185}11861187// RemoveCommand removes one or more commands from a parent command.1188func (c *Command) RemoveCommand(cmds ...*Command) {1189 commands := []*Command{}1190main:1191 for _, command := range c.commands {1192 for _, cmd := range cmds {1193 if command == cmd {1194 command.parent = nil1195 continue main1196 }1197 }1198 commands = append(commands, command)1199 }1200 c.commands = commands1201 // recompute all lengths1202 c.commandsMaxUseLen = 01203 c.commandsMaxCommandPathLen = 01204 c.commandsMaxNameLen = 01205 for _, command := range c.commands {1206 usageLen := len(command.Use)1207 if usageLen > c.commandsMaxUseLen {1208 c.commandsMaxUseLen = usageLen1209 }1210 commandPathLen := len(command.CommandPath())1211 if commandPathLen > c.commandsMaxCommandPathLen {1212 c.commandsMaxCommandPathLen = commandPathLen1213 }1214 nameLen := len(command.Name())1215 if nameLen > c.commandsMaxNameLen {1216 c.commandsMaxNameLen = nameLen1217 }1218 }1219}12201221// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1222func (c *Command) Print(i ...interface{}) {1223 fmt.Fprint(c.OutOrStderr(), i...)1224}12251226// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1227func (c *Command) Println(i ...interface{}) {1228 c.Print(fmt.Sprintln(i...))1229}12301231// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1232func (c *Command) Printf(format string, i ...interface{}) {1233 c.Print(fmt.Sprintf(format, i...))1234}12351236// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.1237func (c *Command) PrintErr(i ...interface{}) {1238 fmt.Fprint(c.ErrOrStderr(), i...)1239}12401241// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.1242func (c *Command) PrintErrln(i ...interface{}) {1243 c.PrintErr(fmt.Sprintln(i...))1244}12451246// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.1247func (c *Command) PrintErrf(format string, i ...interface{}) {1248 c.PrintErr(fmt.Sprintf(format, i...))1249}12501251// CommandPath returns the full path to this command.1252func (c *Command) CommandPath() string {1253 if c.HasParent() {1254 return c.Parent().CommandPath() + " " + c.Name()1255 }1256 return c.Name()1257}12581259// UseLine puts out the full usage for a given command (including parents).1260func (c *Command) UseLine() string {1261 var useline string1262 if c.HasParent() {1263 useline = c.parent.CommandPath() + " " + c.Use1264 } else {1265 useline = c.Use1266 }1267 if c.DisableFlagsInUseLine {1268 return useline1269 }1270 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1271 useline += " [flags]"1272 }1273 return useline1274}12751276// DebugFlags used to determine which flags have been assigned to which commands1277// and which persist.1278func (c *Command) DebugFlags() {1279 c.Println("DebugFlags called on", c.Name())1280 var debugflags func(*Command)12811282 debugflags = func(x *Command) {1283 if x.HasFlags() || x.HasPersistentFlags() {1284 c.Println(x.Name())1285 }1286 if x.HasFlags() {1287 x.flags.VisitAll(func(f *flag.Flag) {1288 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1289 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1290 } else {1291 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1292 }1293 })1294 }1295 if x.HasPersistentFlags() {1296 x.pflags.VisitAll(func(f *flag.Flag) {1297 if x.HasFlags() {1298 if x.flags.Lookup(f.Name) == nil {1299 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1300 }1301 } else {1302 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1303 }1304 })1305 }1306 c.Println(x.flagErrorBuf)1307 if x.HasSubCommands() {1308 for _, y := range x.commands {1309 debugflags(y)1310 }1311 }1312 }13131314 debugflags(c)1315}13161317// Name returns the command's name: the first word in the use line.1318func (c *Command) Name() string {1319 name := c.Use1320 i := strings.Index(name, " ")1321 if i >= 0 {1322 name = name[:i]1323 }1324 return name1325}13261327// HasAlias determines if a given string is an alias of the command.1328func (c *Command) HasAlias(s string) bool {1329 for _, a := range c.Aliases {1330 if a == s {1331 return true1332 }1333 }1334 return false1335}13361337// CalledAs returns the command name or alias that was used to invoke1338// this command or an empty string if the command has not been called.1339func (c *Command) CalledAs() string {1340 if c.commandCalledAs.called {1341 return c.commandCalledAs.name1342 }1343 return ""1344}13451346// hasNameOrAliasPrefix returns true if the Name or any of aliases start1347// with prefix1348func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1349 if strings.HasPrefix(c.Name(), prefix) {1350 c.commandCalledAs.name = c.Name()1351 return true1352 }1353 for _, alias := range c.Aliases {1354 if strings.HasPrefix(alias, prefix) {1355 c.commandCalledAs.name = alias1356 return true1357 }1358 }1359 return false1360}13611362// NameAndAliases returns a list of the command name and all aliases1363func (c *Command) NameAndAliases() string {1364 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1365}13661367// HasExample determines if the command has example.1368func (c *Command) HasExample() bool {1369 return len(c.Example) > 01370}13711372// Runnable determines if the command is itself runnable.1373func (c *Command) Runnable() bool {1374 return c.Run != nil || c.RunE != nil1375}13761377// HasSubCommands determines if the command has children commands.1378func (c *Command) HasSubCommands() bool {1379 return len(c.commands) > 01380}13811382// IsAvailableCommand determines if a command is available as a non-help command1383// (this includes all non deprecated/hidden commands).1384func (c *Command) IsAvailableCommand() bool {1385 if len(c.Deprecated) != 0 || c.Hidden {1386 return false1387 }13881389 if c.HasParent() && c.Parent().helpCommand == c {1390 return false1391 }13921393 if c.Runnable() || c.HasAvailableSubCommands() {1394 return true1395 }13961397 return false1398}13991400// IsAdditionalHelpTopicCommand determines if a command is an additional1401// help topic command; additional help topic command is determined by the1402// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1403// are runnable/hidden/deprecated.1404// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1405func (c *Command) IsAdditionalHelpTopicCommand() bool {1406 // if a command is runnable, deprecated, or hidden it is not a 'help' command1407 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1408 return false1409 }14101411 // if any non-help sub commands are found, the command is not a 'help' command1412 for _, sub := range c.commands {1413 if !sub.IsAdditionalHelpTopicCommand() {1414 return false1415 }1416 }14171418 // the command either has no sub commands, or no non-help sub commands1419 return true1420}14211422// HasHelpSubCommands determines if a command has any available 'help' sub commands1423// that need to be shown in the usage/help default template under 'additional help1424// topics'.1425func (c *Command) HasHelpSubCommands() bool {1426 // return true on the first found available 'help' sub command1427 for _, sub := range c.commands {1428 if sub.IsAdditionalHelpTopicCommand() {1429 return true1430 }1431 }14321433 // the command either has no sub commands, or no available 'help' sub commands1434 return false1435}14361437// HasAvailableSubCommands determines if a command has available sub commands that1438// need to be shown in the usage/help default template under 'available commands'.1439func (c *Command) HasAvailableSubCommands() bool {1440 // return true on the first found available (non deprecated/help/hidden)1441 // sub command1442 for _, sub := range c.commands {1443 if sub.IsAvailableCommand() {1444 return true1445 }1446 }14471448 // the command either has no sub commands, or no available (non deprecated/help/hidden)1449 // sub commands1450 return false1451}14521453// HasParent determines if the command is a child command.1454func (c *Command) HasParent() bool {1455 return c.parent != nil1456}14571458// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.1459func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1460 return c.globNormFunc1461}14621463// Flags returns the complete FlagSet that applies1464// to this command (local and persistent declared here and by all parents).1465func (c *Command) Flags() *flag.FlagSet {1466 if c.flags == nil {1467 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1468 if c.flagErrorBuf == nil {1469 c.flagErrorBuf = new(bytes.Buffer)1470 }1471 c.flags.SetOutput(c.flagErrorBuf)1472 }14731474 return c.flags1475}14761477// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1478func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1479 persistentFlags := c.PersistentFlags()14801481 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1482 c.LocalFlags().VisitAll(func(f *flag.Flag) {1483 if persistentFlags.Lookup(f.Name) == nil {1484 out.AddFlag(f)1485 }1486 })1487 return out1488}14891490// LocalFlags returns the local FlagSet specifically set in the current command.1491func (c *Command) LocalFlags() *flag.FlagSet {1492 c.mergePersistentFlags()14931494 if c.lflags == nil {1495 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1496 if c.flagErrorBuf == nil {1497 c.flagErrorBuf = new(bytes.Buffer)1498 }1499 c.lflags.SetOutput(c.flagErrorBuf)1500 }1501 c.lflags.SortFlags = c.Flags().SortFlags1502 if c.globNormFunc != nil {1503 c.lflags.SetNormalizeFunc(c.globNormFunc)1504 }15051506 addToLocal := func(f *flag.Flag) {1507 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1508 c.lflags.AddFlag(f)1509 }1510 }1511 c.Flags().VisitAll(addToLocal)1512 c.PersistentFlags().VisitAll(addToLocal)1513 return c.lflags1514}15151516// InheritedFlags returns all flags which were inherited from parent commands.1517func (c *Command) InheritedFlags() *flag.FlagSet {1518 c.mergePersistentFlags()15191520 if c.iflags == nil {1521 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1522 if c.flagErrorBuf == nil {1523 c.flagErrorBuf = new(bytes.Buffer)1524 }1525 c.iflags.SetOutput(c.flagErrorBuf)1526 }15271528 local := c.LocalFlags()1529 if c.globNormFunc != nil {1530 c.iflags.SetNormalizeFunc(c.globNormFunc)1531 }15321533 c.parentsPflags.VisitAll(func(f *flag.Flag) {1534 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1535 c.iflags.AddFlag(f)1536 }1537 })1538 return c.iflags1539}15401541// NonInheritedFlags returns all flags which were not inherited from parent commands.1542func (c *Command) NonInheritedFlags() *flag.FlagSet {1543 return c.LocalFlags()1544}15451546// PersistentFlags returns the persistent FlagSet specifically set in the current command.1547func (c *Command) PersistentFlags() *flag.FlagSet {1548 if c.pflags == nil {1549 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1550 if c.flagErrorBuf == nil {1551 c.flagErrorBuf = new(bytes.Buffer)1552 }1553 c.pflags.SetOutput(c.flagErrorBuf)1554 }1555 return c.pflags1556}15571558// ResetFlags deletes all flags from command.1559func (c *Command) ResetFlags() {1560 c.flagErrorBuf = new(bytes.Buffer)1561 c.flagErrorBuf.Reset()1562 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1563 c.flags.SetOutput(c.flagErrorBuf)1564 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1565 c.pflags.SetOutput(c.flagErrorBuf)15661567 c.lflags = nil1568 c.iflags = nil1569 c.parentsPflags = nil1570}15711572// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1573func (c *Command) HasFlags() bool {1574 return c.Flags().HasFlags()1575}15761577// HasPersistentFlags checks if the command contains persistent flags.1578func (c *Command) HasPersistentFlags() bool {1579 return c.PersistentFlags().HasFlags()1580}15811582// HasLocalFlags checks if the command has flags specifically declared locally.1583func (c *Command) HasLocalFlags() bool {1584 return c.LocalFlags().HasFlags()1585}15861587// HasInheritedFlags checks if the command has flags inherited from its parent command.1588func (c *Command) HasInheritedFlags() bool {1589 return c.InheritedFlags().HasFlags()1590}15911592// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1593// structure) which are not hidden or deprecated.1594func (c *Command) HasAvailableFlags() bool {1595 return c.Flags().HasAvailableFlags()1596}15971598// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1599func (c *Command) HasAvailablePersistentFlags() bool {1600 return c.PersistentFlags().HasAvailableFlags()1601}16021603// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1604// or deprecated.1605func (c *Command) HasAvailableLocalFlags() bool {1606 return c.LocalFlags().HasAvailableFlags()1607}16081609// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1610// not hidden or deprecated.1611func (c *Command) HasAvailableInheritedFlags() bool {1612 return c.InheritedFlags().HasAvailableFlags()1613}16141615// Flag climbs up the command tree looking for matching flag.1616func (c *Command) Flag(name string) (flag *flag.Flag) {1617 flag = c.Flags().Lookup(name)16181619 if flag == nil {1620 flag = c.persistentFlag(name)1621 }16221623 return1624}16251626// Recursively find matching persistent flag.1627func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1628 if c.HasPersistentFlags() {1629 flag = c.PersistentFlags().Lookup(name)1630 }16311632 if flag == nil {1633 c.updateParentsPflags()1634 flag = c.parentsPflags.Lookup(name)1635 }1636 return1637}16381639// ParseFlags parses persistent flag tree and local flags.1640func (c *Command) ParseFlags(args []string) error {1641 if c.DisableFlagParsing {1642 return nil1643 }16441645 if c.flagErrorBuf == nil {1646 c.flagErrorBuf = new(bytes.Buffer)1647 }1648 beforeErrorBufLen := c.flagErrorBuf.Len()1649 c.mergePersistentFlags()16501651 // do it here after merging all flags and just before parse1652 c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)16531654 err := c.Flags().Parse(args)1655 // Print warnings if they occurred (e.g. deprecated flag messages).1656 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1657 c.Print(c.flagErrorBuf.String())1658 }16591660 return err1661}16621663// Parent returns a commands parent command.1664func (c *Command) Parent() *Command {1665 return c.parent1666}16671668// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1669// and adds missing persistent flags of all parents.1670func (c *Command) mergePersistentFlags() {1671 c.updateParentsPflags()1672 c.Flags().AddFlagSet(c.PersistentFlags())1673 c.Flags().AddFlagSet(c.parentsPflags)1674}16751676// updateParentsPflags updates c.parentsPflags by adding1677// new persistent flags of all parents.1678// If c.parentsPflags == nil, it makes new.1679func (c *Command) updateParentsPflags() {1680 if c.parentsPflags == nil {1681 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1682 c.parentsPflags.SetOutput(c.flagErrorBuf)1683 c.parentsPflags.SortFlags = false1684 }16851686 if c.globNormFunc != nil {1687 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1688 }16891690 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)16911692 c.VisitParents(func(parent *Command) {1693 c.parentsPflags.AddFlagSet(parent.PersistentFlags())1694 })1695}