command.go
This file
Path
command.go
1,834 lines · 52.4 KiB · Go
Last changed by
fix: don't remove flag value that matches subcommand name (#1781)Brian Pursleybefore adoption6b0bd30
History of this fileTake it
1// Copyright 2013-2022 The Cobra Authors2//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//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.16// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.17package cobra1819import (20 "bytes"21 "context"22 "errors"23 "fmt"24 "io"25 "os"26 "path/filepath"27 "sort"28 "strings"2930 flag "github.com/spf13/pflag"31)3233const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"3435// FParseErrWhitelist configures Flag parse errors to be ignored36type FParseErrWhitelist flag.ParseErrorsWhitelist3738// Structure to manage groups for commands39type Group struct {40 ID string41 Title string42}4344// Command is just that, a command for your application.45// E.g. 'go run ...' - 'run' is the command. Cobra requires46// you to define the usage and description as part of your command47// definition to ensure usability.48type Command struct {49 // Use is the one-line usage message.50 // Recommended syntax is as follow:51 // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.52 // ... indicates that you can specify multiple values for the previous argument.53 // | indicates mutually exclusive information. You can use the argument to the left of the separator or the54 // argument to the right of the separator. You cannot use both arguments in a single use of the command.55 // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are56 // optional, they are enclosed in brackets ([ ]).57 // Example: add [-F file | -D dir]... [-f format] profile58 Use string5960 // Aliases is an array of aliases that can be used instead of the first word in Use.61 Aliases []string6263 // SuggestFor is an array of command names for which this command will be suggested -64 // similar to aliases but only suggests.65 SuggestFor []string6667 // Short is the short description shown in the 'help' output.68 Short string6970 // The group id under which this subcommand is grouped in the 'help' output of its parent.71 GroupID string7273 // Long is the long message shown in the 'help <this-command>' output.74 Long string7576 // Example is examples of how to use the command.77 Example string7879 // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions80 ValidArgs []string81 // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.82 // It is a dynamic version of using ValidArgs.83 // Only one of ValidArgs and ValidArgsFunction can be used for a command.84 ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)8586 // Expected arguments87 Args PositionalArgs8889 // ArgAliases is List of aliases for ValidArgs.90 // These are not suggested to the user in the shell completion,91 // but accepted if entered manually.92 ArgAliases []string9394 // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.95 // For portability with other shells, it is recommended to instead use ValidArgsFunction96 BashCompletionFunction string9798 // Deprecated defines, if this command is deprecated and should print this string when used.99 Deprecated string100101 // Annotations are key/value pairs that can be used by applications to identify or102 // group commands.103 Annotations map[string]string104105 // Version defines the version for this command. If this value is non-empty and the command does not106 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,107 // will print content of the "Version" variable. A shorthand "v" flag will also be added if the108 // command does not define one.109 Version string110111 // The *Run functions are executed in the following order:112 // * PersistentPreRun()113 // * PreRun()114 // * Run()115 // * PostRun()116 // * PersistentPostRun()117 // All functions get the same args, the arguments after the command name.118 //119 // PersistentPreRun: children of this command will inherit and execute.120 PersistentPreRun func(cmd *Command, args []string)121 // PersistentPreRunE: PersistentPreRun but returns an error.122 PersistentPreRunE func(cmd *Command, args []string) error123 // PreRun: children of this command will not inherit.124 PreRun func(cmd *Command, args []string)125 // PreRunE: PreRun but returns an error.126 PreRunE func(cmd *Command, args []string) error127 // Run: Typically the actual work function. Most commands will only implement this.128 Run func(cmd *Command, args []string)129 // RunE: Run but returns an error.130 RunE func(cmd *Command, args []string) error131 // PostRun: run after the Run command.132 PostRun func(cmd *Command, args []string)133 // PostRunE: PostRun but returns an error.134 PostRunE func(cmd *Command, args []string) error135 // PersistentPostRun: children of this command will inherit and execute after PostRun.136 PersistentPostRun func(cmd *Command, args []string)137 // PersistentPostRunE: PersistentPostRun but returns an error.138 PersistentPostRunE func(cmd *Command, args []string) error139140 // groups for subcommands141 commandgroups []*Group142143 // args is actual args parsed from flags.144 args []string145 // flagErrorBuf contains all error messages from pflag.146 flagErrorBuf *bytes.Buffer147 // flags is full set of flags.148 flags *flag.FlagSet149 // pflags contains persistent flags.150 pflags *flag.FlagSet151 // lflags contains local flags.152 lflags *flag.FlagSet153 // iflags contains inherited flags.154 iflags *flag.FlagSet155 // parentsPflags is all persistent flags of cmd's parents.156 parentsPflags *flag.FlagSet157 // globNormFunc is the global normalization function158 // that we can use on every pflag set and children commands159 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName160161 // usageFunc is usage func defined by user.162 usageFunc func(*Command) error163 // usageTemplate is usage template defined by user.164 usageTemplate string165 // flagErrorFunc is func defined by user and it's called when the parsing of166 // flags returns an error.167 flagErrorFunc func(*Command, error) error168 // helpTemplate is help template defined by user.169 helpTemplate string170 // helpFunc is help func defined by user.171 helpFunc func(*Command, []string)172 // helpCommand is command with usage 'help'. If it's not defined by user,173 // cobra uses default help command.174 helpCommand *Command175 // helpCommandGroupID is the group id for the helpCommand176 helpCommandGroupID string177178 // completionCommandGroupID is the group id for the completion command179 completionCommandGroupID string180181 // versionTemplate is the version template defined by user.182 versionTemplate string183184 // inReader is a reader defined by the user that replaces stdin185 inReader io.Reader186 // outWriter is a writer defined by the user that replaces stdout187 outWriter io.Writer188 // errWriter is a writer defined by the user that replaces stderr189 errWriter io.Writer190191 // FParseErrWhitelist flag parse errors to be ignored192 FParseErrWhitelist FParseErrWhitelist193194 // CompletionOptions is a set of options to control the handling of shell completion195 CompletionOptions CompletionOptions196197 // commandsAreSorted defines, if command slice are sorted or not.198 commandsAreSorted bool199 // commandCalledAs is the name or alias value used to call this command.200 commandCalledAs struct {201 name string202 called bool203 }204205 ctx context.Context206207 // commands is the list of commands supported by this program.208 commands []*Command209 // parent is a parent command for this command.210 parent *Command211 // Max lengths of commands' string lengths for use in padding.212 commandsMaxUseLen int213 commandsMaxCommandPathLen int214 commandsMaxNameLen int215216 // TraverseChildren parses flags on all parents before executing child command.217 TraverseChildren bool218219 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.220 Hidden bool221222 // SilenceErrors is an option to quiet errors down stream.223 SilenceErrors bool224225 // SilenceUsage is an option to silence usage when an error occurs.226 SilenceUsage bool227228 // DisableFlagParsing disables the flag parsing.229 // If this is true all flags will be passed to the command as arguments.230 DisableFlagParsing bool231232 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")233 // will be printed by generating docs for this command.234 DisableAutoGenTag bool235236 // DisableFlagsInUseLine will disable the addition of [flags] to the usage237 // line of a command when printing help or generating docs238 DisableFlagsInUseLine bool239240 // DisableSuggestions disables the suggestions based on Levenshtein distance241 // that go along with 'unknown command' messages.242 DisableSuggestions bool243244 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.245 // Must be > 0.246 SuggestionsMinimumDistance int247}248249// Context returns underlying command context. If command was executed250// with ExecuteContext or the context was set with SetContext, the251// previously set context will be returned. Otherwise, nil is returned.252//253// Notice that a call to Execute and ExecuteC will replace a nil context of254// a command with a context.Background, so a background context will be255// returned by Context after one of these functions has been called.256func (c *Command) Context() context.Context {257 return c.ctx258}259260// SetContext sets context for the command. This context will be overwritten by261// Command.ExecuteContext or Command.ExecuteContextC.262func (c *Command) SetContext(ctx context.Context) {263 c.ctx = ctx264}265266// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden267// particularly useful when testing.268func (c *Command) SetArgs(a []string) {269 c.args = a270}271272// SetOutput sets the destination for usage and error messages.273// If output is nil, os.Stderr is used.274// Deprecated: Use SetOut and/or SetErr instead275func (c *Command) SetOutput(output io.Writer) {276 c.outWriter = output277 c.errWriter = output278}279280// SetOut sets the destination for usage messages.281// If newOut is nil, os.Stdout is used.282func (c *Command) SetOut(newOut io.Writer) {283 c.outWriter = newOut284}285286// SetErr sets the destination for error messages.287// If newErr is nil, os.Stderr is used.288func (c *Command) SetErr(newErr io.Writer) {289 c.errWriter = newErr290}291292// SetIn sets the source for input data293// If newIn is nil, os.Stdin is used.294func (c *Command) SetIn(newIn io.Reader) {295 c.inReader = newIn296}297298// SetUsageFunc sets usage function. Usage can be defined by application.299func (c *Command) SetUsageFunc(f func(*Command) error) {300 c.usageFunc = f301}302303// SetUsageTemplate sets usage template. Can be defined by Application.304func (c *Command) SetUsageTemplate(s string) {305 c.usageTemplate = s306}307308// SetFlagErrorFunc sets a function to generate an error when flag parsing309// fails.310func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {311 c.flagErrorFunc = f312}313314// SetHelpFunc sets help function. Can be defined by Application.315func (c *Command) SetHelpFunc(f func(*Command, []string)) {316 c.helpFunc = f317}318319// SetHelpCommand sets help command.320func (c *Command) SetHelpCommand(cmd *Command) {321 c.helpCommand = cmd322}323324// SetHelpCommandGroup sets the group id of the help command.325func (c *Command) SetHelpCommandGroupID(groupID string) {326 if c.helpCommand != nil {327 c.helpCommand.GroupID = groupID328 }329 // helpCommandGroupID is used if no helpCommand is defined by the user330 c.helpCommandGroupID = groupID331}332333// SetCompletionCommandGroup sets the group id of the completion command.334func (c *Command) SetCompletionCommandGroupID(groupID string) {335 // completionCommandGroupID is used if no completion command is defined by the user336 c.Root().completionCommandGroupID = groupID337}338339// SetHelpTemplate sets help template to be used. Application can use it to set custom template.340func (c *Command) SetHelpTemplate(s string) {341 c.helpTemplate = s342}343344// SetVersionTemplate sets version template to be used. Application can use it to set custom template.345func (c *Command) SetVersionTemplate(s string) {346 c.versionTemplate = s347}348349// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.350// The user should not have a cyclic dependency on commands.351func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {352 c.Flags().SetNormalizeFunc(n)353 c.PersistentFlags().SetNormalizeFunc(n)354 c.globNormFunc = n355356 for _, command := range c.commands {357 command.SetGlobalNormalizationFunc(n)358 }359}360361// OutOrStdout returns output to stdout.362func (c *Command) OutOrStdout() io.Writer {363 return c.getOut(os.Stdout)364}365366// OutOrStderr returns output to stderr367func (c *Command) OutOrStderr() io.Writer {368 return c.getOut(os.Stderr)369}370371// ErrOrStderr returns output to stderr372func (c *Command) ErrOrStderr() io.Writer {373 return c.getErr(os.Stderr)374}375376// InOrStdin returns input to stdin377func (c *Command) InOrStdin() io.Reader {378 return c.getIn(os.Stdin)379}380381func (c *Command) getOut(def io.Writer) io.Writer {382 if c.outWriter != nil {383 return c.outWriter384 }385 if c.HasParent() {386 return c.parent.getOut(def)387 }388 return def389}390391func (c *Command) getErr(def io.Writer) io.Writer {392 if c.errWriter != nil {393 return c.errWriter394 }395 if c.HasParent() {396 return c.parent.getErr(def)397 }398 return def399}400401func (c *Command) getIn(def io.Reader) io.Reader {402 if c.inReader != nil {403 return c.inReader404 }405 if c.HasParent() {406 return c.parent.getIn(def)407 }408 return def409}410411// UsageFunc returns either the function set by SetUsageFunc for this command412// or a parent, or it returns a default usage function.413func (c *Command) UsageFunc() (f func(*Command) error) {414 if c.usageFunc != nil {415 return c.usageFunc416 }417 if c.HasParent() {418 return c.Parent().UsageFunc()419 }420 return func(c *Command) error {421 c.mergePersistentFlags()422 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)423 if err != nil {424 c.PrintErrln(err)425 }426 return err427 }428}429430// Usage puts out the usage for the command.431// Used when a user provides invalid input.432// Can be defined by user by overriding UsageFunc.433func (c *Command) Usage() error {434 return c.UsageFunc()(c)435}436437// HelpFunc returns either the function set by SetHelpFunc for this command438// or a parent, or it returns a function with default help behavior.439func (c *Command) HelpFunc() func(*Command, []string) {440 if c.helpFunc != nil {441 return c.helpFunc442 }443 if c.HasParent() {444 return c.Parent().HelpFunc()445 }446 return func(c *Command, a []string) {447 c.mergePersistentFlags()448 // The help should be sent to stdout449 // See https://github.com/spf13/cobra/issues/1002450 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)451 if err != nil {452 c.PrintErrln(err)453 }454 }455}456457// Help puts out the help for the command.458// Used when a user calls help [command].459// Can be defined by user by overriding HelpFunc.460func (c *Command) Help() error {461 c.HelpFunc()(c, []string{})462 return nil463}464465// UsageString returns usage string.466func (c *Command) UsageString() string {467 // Storing normal writers468 tmpOutput := c.outWriter469 tmpErr := c.errWriter470471 bb := new(bytes.Buffer)472 c.outWriter = bb473 c.errWriter = bb474475 CheckErr(c.Usage())476477 // Setting things back to normal478 c.outWriter = tmpOutput479 c.errWriter = tmpErr480481 return bb.String()482}483484// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this485// command or a parent, or it returns a function which returns the original486// error.487func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {488 if c.flagErrorFunc != nil {489 return c.flagErrorFunc490 }491492 if c.HasParent() {493 return c.parent.FlagErrorFunc()494 }495 return func(c *Command, err error) error {496 return err497 }498}499500var minUsagePadding = 25501502// UsagePadding return padding for the usage.503func (c *Command) UsagePadding() int {504 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {505 return minUsagePadding506 }507 return c.parent.commandsMaxUseLen508}509510var minCommandPathPadding = 11511512// CommandPathPadding return padding for the command path.513func (c *Command) CommandPathPadding() int {514 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {515 return minCommandPathPadding516 }517 return c.parent.commandsMaxCommandPathLen518}519520var minNamePadding = 11521522// NamePadding returns padding for the name.523func (c *Command) NamePadding() int {524 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {525 return minNamePadding526 }527 return c.parent.commandsMaxNameLen528}529530// UsageTemplate returns usage template for the command.531func (c *Command) UsageTemplate() string {532 if c.usageTemplate != "" {533 return c.usageTemplate534 }535536 if c.HasParent() {537 return c.parent.UsageTemplate()538 }539 return `Usage:{{if .Runnable}}540 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}541 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}542543Aliases:544 {{.NameAndAliases}}{{end}}{{if .HasExample}}545546Examples:547{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}548549Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}550 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}551552{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}553 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}554555Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}556 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}557558Flags:559{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}560561Global Flags:562{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}563564Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}565 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}566567Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}568`569}570571// HelpTemplate return help template for the command.572func (c *Command) HelpTemplate() string {573 if c.helpTemplate != "" {574 return c.helpTemplate575 }576577 if c.HasParent() {578 return c.parent.HelpTemplate()579 }580 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}581582{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`583}584585// VersionTemplate return version template for the command.586func (c *Command) VersionTemplate() string {587 if c.versionTemplate != "" {588 return c.versionTemplate589 }590591 if c.HasParent() {592 return c.parent.VersionTemplate()593 }594 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}595`596}597598func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {599 flag := fs.Lookup(name)600 if flag == nil {601 return false602 }603 return flag.NoOptDefVal != ""604}605606func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {607 if len(name) == 0 {608 return false609 }610611 flag := fs.ShorthandLookup(name[:1])612 if flag == nil {613 return false614 }615 return flag.NoOptDefVal != ""616}617618func stripFlags(args []string, c *Command) []string {619 if len(args) == 0 {620 return args621 }622 c.mergePersistentFlags()623624 commands := []string{}625 flags := c.Flags()626627Loop:628 for len(args) > 0 {629 s := args[0]630 args = args[1:]631 switch {632 case s == "--":633 // "--" terminates the flags634 break Loop635 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):636 // If '--flag arg' then637 // delete arg from args.638 fallthrough // (do the same as below)639 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):640 // If '-f arg' then641 // delete 'arg' from args or break the loop if len(args) <= 1.642 if len(args) <= 1 {643 break Loop644 } else {645 args = args[1:]646 continue647 }648 case s != "" && !strings.HasPrefix(s, "-"):649 commands = append(commands, s)650 }651 }652653 return commands654}655656// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like657// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).658// Special care needs to be taken not to remove a flag value.659func (c *Command) argsMinusFirstX(args []string, x string) []string {660 if len(args) == 0 {661 return args662 }663 c.mergePersistentFlags()664 flags := c.Flags()665666Loop:667 for pos := 0; pos < len(args); pos++ {668 s := args[pos]669 switch {670 case s == "--":671 // -- means we have reached the end of the parseable args. Break out of the loop now.672 break Loop673 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):674 fallthrough675 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):676 // This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip677 // over the next arg, because that is the value of this flag.678 pos++679 continue680 case !strings.HasPrefix(s, "-"):681 // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,682 // return the args, excluding the one at this position.683 if s == x {684 ret := []string{}685 ret = append(ret, args[:pos]...)686 ret = append(ret, args[pos+1:]...)687 return ret688 }689 }690 }691 return args692}693694func isFlagArg(arg string) bool {695 return ((len(arg) >= 3 && arg[1] == '-') ||696 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))697}698699// Find the target command given the args and command tree700// Meant to be run on the highest node. Only searches down.701func (c *Command) Find(args []string) (*Command, []string, error) {702 var innerfind func(*Command, []string) (*Command, []string)703704 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {705 argsWOflags := stripFlags(innerArgs, c)706 if len(argsWOflags) == 0 {707 return c, innerArgs708 }709 nextSubCmd := argsWOflags[0]710711 cmd := c.findNext(nextSubCmd)712 if cmd != nil {713 return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd))714 }715 return c, innerArgs716 }717718 commandFound, a := innerfind(c, args)719 if commandFound.Args == nil {720 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))721 }722 return commandFound, a, nil723}724725func (c *Command) findSuggestions(arg string) string {726 if c.DisableSuggestions {727 return ""728 }729 if c.SuggestionsMinimumDistance <= 0 {730 c.SuggestionsMinimumDistance = 2731 }732 suggestionsString := ""733 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {734 suggestionsString += "\n\nDid you mean this?\n"735 for _, s := range suggestions {736 suggestionsString += fmt.Sprintf("\t%v\n", s)737 }738 }739 return suggestionsString740}741742func (c *Command) findNext(next string) *Command {743 matches := make([]*Command, 0)744 for _, cmd := range c.commands {745 if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {746 cmd.commandCalledAs.name = next747 return cmd748 }749 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {750 matches = append(matches, cmd)751 }752 }753754 if len(matches) == 1 {755 return matches[0]756 }757758 return nil759}760761// Traverse the command tree to find the command, and parse args for762// each parent.763func (c *Command) Traverse(args []string) (*Command, []string, error) {764 flags := []string{}765 inFlag := false766767 for i, arg := range args {768 switch {769 // A long flag with a space separated value770 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):771 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'772 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())773 flags = append(flags, arg)774 continue775 // A short flag with a space separated value776 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):777 inFlag = true778 flags = append(flags, arg)779 continue780 // The value for a flag781 case inFlag:782 inFlag = false783 flags = append(flags, arg)784 continue785 // A flag without a value, or with an `=` separated value786 case isFlagArg(arg):787 flags = append(flags, arg)788 continue789 }790791 cmd := c.findNext(arg)792 if cmd == nil {793 return c, args, nil794 }795796 if err := c.ParseFlags(flags); err != nil {797 return nil, args, err798 }799 return cmd.Traverse(args[i+1:])800 }801 return c, args, nil802}803804// SuggestionsFor provides suggestions for the typedName.805func (c *Command) SuggestionsFor(typedName string) []string {806 suggestions := []string{}807 for _, cmd := range c.commands {808 if cmd.IsAvailableCommand() {809 levenshteinDistance := ld(typedName, cmd.Name(), true)810 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance811 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))812 if suggestByLevenshtein || suggestByPrefix {813 suggestions = append(suggestions, cmd.Name())814 }815 for _, explicitSuggestion := range cmd.SuggestFor {816 if strings.EqualFold(typedName, explicitSuggestion) {817 suggestions = append(suggestions, cmd.Name())818 }819 }820 }821 }822 return suggestions823}824825// VisitParents visits all parents of the command and invokes fn on each parent.826func (c *Command) VisitParents(fn func(*Command)) {827 if c.HasParent() {828 fn(c.Parent())829 c.Parent().VisitParents(fn)830 }831}832833// Root finds root command.834func (c *Command) Root() *Command {835 if c.HasParent() {836 return c.Parent().Root()837 }838 return c839}840841// ArgsLenAtDash will return the length of c.Flags().Args at the moment842// when a -- was found during args parsing.843func (c *Command) ArgsLenAtDash() int {844 return c.Flags().ArgsLenAtDash()845}846847func (c *Command) execute(a []string) (err error) {848 if c == nil {849 return fmt.Errorf("Called Execute() on a nil Command")850 }851852 if len(c.Deprecated) > 0 {853 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)854 }855856 // initialize help and version flag at the last point possible to allow for user857 // overriding858 c.InitDefaultHelpFlag()859 c.InitDefaultVersionFlag()860861 err = c.ParseFlags(a)862 if err != nil {863 return c.FlagErrorFunc()(c, err)864 }865866 // If help is called, regardless of other flags, return we want help.867 // Also say we need help if the command isn't runnable.868 helpVal, err := c.Flags().GetBool("help")869 if err != nil {870 // should be impossible to get here as we always declare a help871 // flag in InitDefaultHelpFlag()872 c.Println("\"help\" flag declared as non-bool. Please correct your code")873 return err874 }875876 if helpVal {877 return flag.ErrHelp878 }879880 // for back-compat, only add version flag behavior if version is defined881 if c.Version != "" {882 versionVal, err := c.Flags().GetBool("version")883 if err != nil {884 c.Println("\"version\" flag declared as non-bool. Please correct your code")885 return err886 }887 if versionVal {888 err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)889 if err != nil {890 c.Println(err)891 }892 return err893 }894 }895896 if !c.Runnable() {897 return flag.ErrHelp898 }899900 c.preRun()901902 defer c.postRun()903904 argWoFlags := c.Flags().Args()905 if c.DisableFlagParsing {906 argWoFlags = a907 }908909 if err := c.ValidateArgs(argWoFlags); err != nil {910 return err911 }912913 for p := c; p != nil; p = p.Parent() {914 if p.PersistentPreRunE != nil {915 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {916 return err917 }918 break919 } else if p.PersistentPreRun != nil {920 p.PersistentPreRun(c, argWoFlags)921 break922 }923 }924 if c.PreRunE != nil {925 if err := c.PreRunE(c, argWoFlags); err != nil {926 return err927 }928 } else if c.PreRun != nil {929 c.PreRun(c, argWoFlags)930 }931932 if err := c.ValidateRequiredFlags(); err != nil {933 return err934 }935 if err := c.ValidateFlagGroups(); err != nil {936 return err937 }938939 if c.RunE != nil {940 if err := c.RunE(c, argWoFlags); err != nil {941 return err942 }943 } else {944 c.Run(c, argWoFlags)945 }946 if c.PostRunE != nil {947 if err := c.PostRunE(c, argWoFlags); err != nil {948 return err949 }950 } else if c.PostRun != nil {951 c.PostRun(c, argWoFlags)952 }953 for p := c; p != nil; p = p.Parent() {954 if p.PersistentPostRunE != nil {955 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {956 return err957 }958 break959 } else if p.PersistentPostRun != nil {960 p.PersistentPostRun(c, argWoFlags)961 break962 }963 }964965 return nil966}967968func (c *Command) preRun() {969 for _, x := range initializers {970 x()971 }972}973974func (c *Command) postRun() {975 for _, x := range finalizers {976 x()977 }978}979980// ExecuteContext is the same as Execute(), but sets the ctx on the command.981// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs982// functions.983func (c *Command) ExecuteContext(ctx context.Context) error {984 c.ctx = ctx985 return c.Execute()986}987988// Execute uses the args (os.Args[1:] by default)989// and run through the command tree finding appropriate matches990// for commands and then corresponding flags.991func (c *Command) Execute() error {992 _, err := c.ExecuteC()993 return err994}995996// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.997// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs998// functions.999func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {1000 c.ctx = ctx1001 return c.ExecuteC()1002}10031004// ExecuteC executes the command.1005func (c *Command) ExecuteC() (cmd *Command, err error) {1006 if c.ctx == nil {1007 c.ctx = context.Background()1008 }10091010 // Regardless of what command execute is called on, run on Root only1011 if c.HasParent() {1012 return c.Root().ExecuteC()1013 }10141015 // windows hook1016 if preExecHookFn != nil {1017 preExecHookFn(c)1018 }10191020 // initialize help at the last point to allow for user overriding1021 c.InitDefaultHelpCmd()1022 // initialize completion at the last point to allow for user overriding1023 c.InitDefaultCompletionCmd()10241025 // Now that all commands have been created, let's make sure all groups1026 // are properly created also1027 c.checkCommandGroups()10281029 args := c.args10301031 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #1551032 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {1033 args = os.Args[1:]1034 }10351036 // initialize the hidden command to be used for shell completion1037 c.initCompleteCmd(args)10381039 var flags []string1040 if c.TraverseChildren {1041 cmd, flags, err = c.Traverse(args)1042 } else {1043 cmd, flags, err = c.Find(args)1044 }1045 if err != nil {1046 // If found parse to a subcommand and then failed, talk about the subcommand1047 if cmd != nil {1048 c = cmd1049 }1050 if !c.SilenceErrors {1051 c.PrintErrln("Error:", err.Error())1052 c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())1053 }1054 return c, err1055 }10561057 cmd.commandCalledAs.called = true1058 if cmd.commandCalledAs.name == "" {1059 cmd.commandCalledAs.name = cmd.Name()1060 }10611062 // We have to pass global context to children command1063 // if context is present on the parent command.1064 if cmd.ctx == nil {1065 cmd.ctx = c.ctx1066 }10671068 err = cmd.execute(flags)1069 if err != nil {1070 // Always show help if requested, even if SilenceErrors is in1071 // effect1072 if errors.Is(err, flag.ErrHelp) {1073 cmd.HelpFunc()(cmd, args)1074 return cmd, nil1075 }10761077 // If root command has SilenceErrors flagged,1078 // all subcommands should respect it1079 if !cmd.SilenceErrors && !c.SilenceErrors {1080 c.PrintErrln("Error:", err.Error())1081 }10821083 // If root command has SilenceUsage flagged,1084 // all subcommands should respect it1085 if !cmd.SilenceUsage && !c.SilenceUsage {1086 c.Println(cmd.UsageString())1087 }1088 }1089 return cmd, err1090}10911092func (c *Command) ValidateArgs(args []string) error {1093 if c.Args == nil {1094 return ArbitraryArgs(c, args)1095 }1096 return c.Args(c, args)1097}10981099// ValidateRequiredFlags validates all required flags are present and returns an error otherwise1100func (c *Command) ValidateRequiredFlags() error {1101 if c.DisableFlagParsing {1102 return nil1103 }11041105 flags := c.Flags()1106 missingFlagNames := []string{}1107 flags.VisitAll(func(pflag *flag.Flag) {1108 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]1109 if !found {1110 return1111 }1112 if (requiredAnnotation[0] == "true") && !pflag.Changed {1113 missingFlagNames = append(missingFlagNames, pflag.Name)1114 }1115 })11161117 if len(missingFlagNames) > 0 {1118 return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))1119 }1120 return nil1121}11221123// checkCommandGroups checks if a command has been added to a group that does not exists.1124// If so, we panic because it indicates a coding error that should be corrected.1125func (c *Command) checkCommandGroups() {1126 for _, sub := range c.commands {1127 // if Group is not defined let the developer know right away1128 if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) {1129 panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath()))1130 }11311132 sub.checkCommandGroups()1133 }1134}11351136// InitDefaultHelpFlag adds default help flag to c.1137// It is called automatically by executing the c or by calling help and usage.1138// If c already has help flag, it will do nothing.1139func (c *Command) InitDefaultHelpFlag() {1140 c.mergePersistentFlags()1141 if c.Flags().Lookup("help") == nil {1142 usage := "help for "1143 if c.Name() == "" {1144 usage += "this command"1145 } else {1146 usage += c.Name()1147 }1148 c.Flags().BoolP("help", "h", false, usage)1149 _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})1150 }1151}11521153// InitDefaultVersionFlag adds default version flag to c.1154// It is called automatically by executing the c.1155// If c already has a version flag, it will do nothing.1156// If c.Version is empty, it will do nothing.1157func (c *Command) InitDefaultVersionFlag() {1158 if c.Version == "" {1159 return1160 }11611162 c.mergePersistentFlags()1163 if c.Flags().Lookup("version") == nil {1164 usage := "version for "1165 if c.Name() == "" {1166 usage += "this command"1167 } else {1168 usage += c.Name()1169 }1170 if c.Flags().ShorthandLookup("v") == nil {1171 c.Flags().BoolP("version", "v", false, usage)1172 } else {1173 c.Flags().Bool("version", false, usage)1174 }1175 _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"})1176 }1177}11781179// InitDefaultHelpCmd adds default help command to c.1180// It is called automatically by executing the c or by calling help and usage.1181// If c already has help command or c has no subcommands, it will do nothing.1182func (c *Command) InitDefaultHelpCmd() {1183 if !c.HasSubCommands() {1184 return1185 }11861187 if c.helpCommand == nil {1188 c.helpCommand = &Command{1189 Use: "help [command]",1190 Short: "Help about any command",1191 Long: `Help provides help for any command in the application.1192Simply type ` + c.Name() + ` help [path to command] for full details.`,1193 ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1194 var completions []string1195 cmd, _, e := c.Root().Find(args)1196 if e != nil {1197 return nil, ShellCompDirectiveNoFileComp1198 }1199 if cmd == nil {1200 // Root help command.1201 cmd = c.Root()1202 }1203 for _, subCmd := range cmd.Commands() {1204 if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {1205 if strings.HasPrefix(subCmd.Name(), toComplete) {1206 completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))1207 }1208 }1209 }1210 return completions, ShellCompDirectiveNoFileComp1211 },1212 Run: func(c *Command, args []string) {1213 cmd, _, e := c.Root().Find(args)1214 if cmd == nil || e != nil {1215 c.Printf("Unknown help topic %#q\n", args)1216 CheckErr(c.Root().Usage())1217 } else {1218 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1219 cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown1220 CheckErr(cmd.Help())1221 }1222 },1223 GroupID: c.helpCommandGroupID,1224 }1225 }1226 c.RemoveCommand(c.helpCommand)1227 c.AddCommand(c.helpCommand)1228}12291230// ResetCommands delete parent, subcommand and help command from c.1231func (c *Command) ResetCommands() {1232 c.parent = nil1233 c.commands = nil1234 c.helpCommand = nil1235 c.parentsPflags = nil1236}12371238// Sorts commands by their names.1239type commandSorterByName []*Command12401241func (c commandSorterByName) Len() int { return len(c) }1242func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }1243func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }12441245// Commands returns a sorted slice of child commands.1246func (c *Command) Commands() []*Command {1247 // do not sort commands if it already sorted or sorting was disabled1248 if EnableCommandSorting && !c.commandsAreSorted {1249 sort.Sort(commandSorterByName(c.commands))1250 c.commandsAreSorted = true1251 }1252 return c.commands1253}12541255// AddCommand adds one or more commands to this parent command.1256func (c *Command) AddCommand(cmds ...*Command) {1257 for i, x := range cmds {1258 if cmds[i] == c {1259 panic("Command can't be a child of itself")1260 }1261 cmds[i].parent = c1262 // update max lengths1263 usageLen := len(x.Use)1264 if usageLen > c.commandsMaxUseLen {1265 c.commandsMaxUseLen = usageLen1266 }1267 commandPathLen := len(x.CommandPath())1268 if commandPathLen > c.commandsMaxCommandPathLen {1269 c.commandsMaxCommandPathLen = commandPathLen1270 }1271 nameLen := len(x.Name())1272 if nameLen > c.commandsMaxNameLen {1273 c.commandsMaxNameLen = nameLen1274 }1275 // If global normalization function exists, update all children1276 if c.globNormFunc != nil {1277 x.SetGlobalNormalizationFunc(c.globNormFunc)1278 }1279 c.commands = append(c.commands, x)1280 c.commandsAreSorted = false1281 }1282}12831284// Groups returns a slice of child command groups.1285func (c *Command) Groups() []*Group {1286 return c.commandgroups1287}12881289// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group1290func (c *Command) AllChildCommandsHaveGroup() bool {1291 for _, sub := range c.commands {1292 if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {1293 return false1294 }1295 }1296 return true1297}12981299// ContainGroups return if groupID exists in the list of command groups.1300func (c *Command) ContainsGroup(groupID string) bool {1301 for _, x := range c.commandgroups {1302 if x.ID == groupID {1303 return true1304 }1305 }1306 return false1307}13081309// AddGroup adds one or more command groups to this parent command.1310func (c *Command) AddGroup(groups ...*Group) {1311 c.commandgroups = append(c.commandgroups, groups...)1312}13131314// RemoveCommand removes one or more commands from a parent command.1315func (c *Command) RemoveCommand(cmds ...*Command) {1316 commands := []*Command{}1317main:1318 for _, command := range c.commands {1319 for _, cmd := range cmds {1320 if command == cmd {1321 command.parent = nil1322 continue main1323 }1324 }1325 commands = append(commands, command)1326 }1327 c.commands = commands1328 // recompute all lengths1329 c.commandsMaxUseLen = 01330 c.commandsMaxCommandPathLen = 01331 c.commandsMaxNameLen = 01332 for _, command := range c.commands {1333 usageLen := len(command.Use)1334 if usageLen > c.commandsMaxUseLen {1335 c.commandsMaxUseLen = usageLen1336 }1337 commandPathLen := len(command.CommandPath())1338 if commandPathLen > c.commandsMaxCommandPathLen {1339 c.commandsMaxCommandPathLen = commandPathLen1340 }1341 nameLen := len(command.Name())1342 if nameLen > c.commandsMaxNameLen {1343 c.commandsMaxNameLen = nameLen1344 }1345 }1346}13471348// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1349func (c *Command) Print(i ...interface{}) {1350 fmt.Fprint(c.OutOrStderr(), i...)1351}13521353// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1354func (c *Command) Println(i ...interface{}) {1355 c.Print(fmt.Sprintln(i...))1356}13571358// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1359func (c *Command) Printf(format string, i ...interface{}) {1360 c.Print(fmt.Sprintf(format, i...))1361}13621363// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.1364func (c *Command) PrintErr(i ...interface{}) {1365 fmt.Fprint(c.ErrOrStderr(), i...)1366}13671368// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.1369func (c *Command) PrintErrln(i ...interface{}) {1370 c.PrintErr(fmt.Sprintln(i...))1371}13721373// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.1374func (c *Command) PrintErrf(format string, i ...interface{}) {1375 c.PrintErr(fmt.Sprintf(format, i...))1376}13771378// CommandPath returns the full path to this command.1379func (c *Command) CommandPath() string {1380 if c.HasParent() {1381 return c.Parent().CommandPath() + " " + c.Name()1382 }1383 return c.Name()1384}13851386// UseLine puts out the full usage for a given command (including parents).1387func (c *Command) UseLine() string {1388 var useline string1389 if c.HasParent() {1390 useline = c.parent.CommandPath() + " " + c.Use1391 } else {1392 useline = c.Use1393 }1394 if c.DisableFlagsInUseLine {1395 return useline1396 }1397 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1398 useline += " [flags]"1399 }1400 return useline1401}14021403// DebugFlags used to determine which flags have been assigned to which commands1404// and which persist.1405func (c *Command) DebugFlags() {1406 c.Println("DebugFlags called on", c.Name())1407 var debugflags func(*Command)14081409 debugflags = func(x *Command) {1410 if x.HasFlags() || x.HasPersistentFlags() {1411 c.Println(x.Name())1412 }1413 if x.HasFlags() {1414 x.flags.VisitAll(func(f *flag.Flag) {1415 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1416 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1417 } else {1418 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1419 }1420 })1421 }1422 if x.HasPersistentFlags() {1423 x.pflags.VisitAll(func(f *flag.Flag) {1424 if x.HasFlags() {1425 if x.flags.Lookup(f.Name) == nil {1426 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1427 }1428 } else {1429 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1430 }1431 })1432 }1433 c.Println(x.flagErrorBuf)1434 if x.HasSubCommands() {1435 for _, y := range x.commands {1436 debugflags(y)1437 }1438 }1439 }14401441 debugflags(c)1442}14431444// Name returns the command's name: the first word in the use line.1445func (c *Command) Name() string {1446 name := c.Use1447 i := strings.Index(name, " ")1448 if i >= 0 {1449 name = name[:i]1450 }1451 return name1452}14531454// HasAlias determines if a given string is an alias of the command.1455func (c *Command) HasAlias(s string) bool {1456 for _, a := range c.Aliases {1457 if commandNameMatches(a, s) {1458 return true1459 }1460 }1461 return false1462}14631464// CalledAs returns the command name or alias that was used to invoke1465// this command or an empty string if the command has not been called.1466func (c *Command) CalledAs() string {1467 if c.commandCalledAs.called {1468 return c.commandCalledAs.name1469 }1470 return ""1471}14721473// hasNameOrAliasPrefix returns true if the Name or any of aliases start1474// with prefix1475func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1476 if strings.HasPrefix(c.Name(), prefix) {1477 c.commandCalledAs.name = c.Name()1478 return true1479 }1480 for _, alias := range c.Aliases {1481 if strings.HasPrefix(alias, prefix) {1482 c.commandCalledAs.name = alias1483 return true1484 }1485 }1486 return false1487}14881489// NameAndAliases returns a list of the command name and all aliases1490func (c *Command) NameAndAliases() string {1491 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1492}14931494// HasExample determines if the command has example.1495func (c *Command) HasExample() bool {1496 return len(c.Example) > 01497}14981499// Runnable determines if the command is itself runnable.1500func (c *Command) Runnable() bool {1501 return c.Run != nil || c.RunE != nil1502}15031504// HasSubCommands determines if the command has children commands.1505func (c *Command) HasSubCommands() bool {1506 return len(c.commands) > 01507}15081509// IsAvailableCommand determines if a command is available as a non-help command1510// (this includes all non deprecated/hidden commands).1511func (c *Command) IsAvailableCommand() bool {1512 if len(c.Deprecated) != 0 || c.Hidden {1513 return false1514 }15151516 if c.HasParent() && c.Parent().helpCommand == c {1517 return false1518 }15191520 if c.Runnable() || c.HasAvailableSubCommands() {1521 return true1522 }15231524 return false1525}15261527// IsAdditionalHelpTopicCommand determines if a command is an additional1528// help topic command; additional help topic command is determined by the1529// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1530// are runnable/hidden/deprecated.1531// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1532func (c *Command) IsAdditionalHelpTopicCommand() bool {1533 // if a command is runnable, deprecated, or hidden it is not a 'help' command1534 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1535 return false1536 }15371538 // if any non-help sub commands are found, the command is not a 'help' command1539 for _, sub := range c.commands {1540 if !sub.IsAdditionalHelpTopicCommand() {1541 return false1542 }1543 }15441545 // the command either has no sub commands, or no non-help sub commands1546 return true1547}15481549// HasHelpSubCommands determines if a command has any available 'help' sub commands1550// that need to be shown in the usage/help default template under 'additional help1551// topics'.1552func (c *Command) HasHelpSubCommands() bool {1553 // return true on the first found available 'help' sub command1554 for _, sub := range c.commands {1555 if sub.IsAdditionalHelpTopicCommand() {1556 return true1557 }1558 }15591560 // the command either has no sub commands, or no available 'help' sub commands1561 return false1562}15631564// HasAvailableSubCommands determines if a command has available sub commands that1565// need to be shown in the usage/help default template under 'available commands'.1566func (c *Command) HasAvailableSubCommands() bool {1567 // return true on the first found available (non deprecated/help/hidden)1568 // sub command1569 for _, sub := range c.commands {1570 if sub.IsAvailableCommand() {1571 return true1572 }1573 }15741575 // the command either has no sub commands, or no available (non deprecated/help/hidden)1576 // sub commands1577 return false1578}15791580// HasParent determines if the command is a child command.1581func (c *Command) HasParent() bool {1582 return c.parent != nil1583}15841585// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.1586func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1587 return c.globNormFunc1588}15891590// Flags returns the complete FlagSet that applies1591// to this command (local and persistent declared here and by all parents).1592func (c *Command) Flags() *flag.FlagSet {1593 if c.flags == nil {1594 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1595 if c.flagErrorBuf == nil {1596 c.flagErrorBuf = new(bytes.Buffer)1597 }1598 c.flags.SetOutput(c.flagErrorBuf)1599 }16001601 return c.flags1602}16031604// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1605func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1606 persistentFlags := c.PersistentFlags()16071608 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1609 c.LocalFlags().VisitAll(func(f *flag.Flag) {1610 if persistentFlags.Lookup(f.Name) == nil {1611 out.AddFlag(f)1612 }1613 })1614 return out1615}16161617// LocalFlags returns the local FlagSet specifically set in the current command.1618func (c *Command) LocalFlags() *flag.FlagSet {1619 c.mergePersistentFlags()16201621 if c.lflags == nil {1622 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1623 if c.flagErrorBuf == nil {1624 c.flagErrorBuf = new(bytes.Buffer)1625 }1626 c.lflags.SetOutput(c.flagErrorBuf)1627 }1628 c.lflags.SortFlags = c.Flags().SortFlags1629 if c.globNormFunc != nil {1630 c.lflags.SetNormalizeFunc(c.globNormFunc)1631 }16321633 addToLocal := func(f *flag.Flag) {1634 // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag1635 if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {1636 c.lflags.AddFlag(f)1637 }1638 }1639 c.Flags().VisitAll(addToLocal)1640 c.PersistentFlags().VisitAll(addToLocal)1641 return c.lflags1642}16431644// InheritedFlags returns all flags which were inherited from parent commands.1645func (c *Command) InheritedFlags() *flag.FlagSet {1646 c.mergePersistentFlags()16471648 if c.iflags == nil {1649 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1650 if c.flagErrorBuf == nil {1651 c.flagErrorBuf = new(bytes.Buffer)1652 }1653 c.iflags.SetOutput(c.flagErrorBuf)1654 }16551656 local := c.LocalFlags()1657 if c.globNormFunc != nil {1658 c.iflags.SetNormalizeFunc(c.globNormFunc)1659 }16601661 c.parentsPflags.VisitAll(func(f *flag.Flag) {1662 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1663 c.iflags.AddFlag(f)1664 }1665 })1666 return c.iflags1667}16681669// NonInheritedFlags returns all flags which were not inherited from parent commands.1670func (c *Command) NonInheritedFlags() *flag.FlagSet {1671 return c.LocalFlags()1672}16731674// PersistentFlags returns the persistent FlagSet specifically set in the current command.1675func (c *Command) PersistentFlags() *flag.FlagSet {1676 if c.pflags == nil {1677 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1678 if c.flagErrorBuf == nil {1679 c.flagErrorBuf = new(bytes.Buffer)1680 }1681 c.pflags.SetOutput(c.flagErrorBuf)1682 }1683 return c.pflags1684}16851686// ResetFlags deletes all flags from command.1687func (c *Command) ResetFlags() {1688 c.flagErrorBuf = new(bytes.Buffer)1689 c.flagErrorBuf.Reset()1690 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1691 c.flags.SetOutput(c.flagErrorBuf)1692 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1693 c.pflags.SetOutput(c.flagErrorBuf)16941695 c.lflags = nil1696 c.iflags = nil1697 c.parentsPflags = nil1698}16991700// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1701func (c *Command) HasFlags() bool {1702 return c.Flags().HasFlags()1703}17041705// HasPersistentFlags checks if the command contains persistent flags.1706func (c *Command) HasPersistentFlags() bool {1707 return c.PersistentFlags().HasFlags()1708}17091710// HasLocalFlags checks if the command has flags specifically declared locally.1711func (c *Command) HasLocalFlags() bool {1712 return c.LocalFlags().HasFlags()1713}17141715// HasInheritedFlags checks if the command has flags inherited from its parent command.1716func (c *Command) HasInheritedFlags() bool {1717 return c.InheritedFlags().HasFlags()1718}17191720// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1721// structure) which are not hidden or deprecated.1722func (c *Command) HasAvailableFlags() bool {1723 return c.Flags().HasAvailableFlags()1724}17251726// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1727func (c *Command) HasAvailablePersistentFlags() bool {1728 return c.PersistentFlags().HasAvailableFlags()1729}17301731// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1732// or deprecated.1733func (c *Command) HasAvailableLocalFlags() bool {1734 return c.LocalFlags().HasAvailableFlags()1735}17361737// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1738// not hidden or deprecated.1739func (c *Command) HasAvailableInheritedFlags() bool {1740 return c.InheritedFlags().HasAvailableFlags()1741}17421743// Flag climbs up the command tree looking for matching flag.1744func (c *Command) Flag(name string) (flag *flag.Flag) {1745 flag = c.Flags().Lookup(name)17461747 if flag == nil {1748 flag = c.persistentFlag(name)1749 }17501751 return1752}17531754// Recursively find matching persistent flag.1755func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1756 if c.HasPersistentFlags() {1757 flag = c.PersistentFlags().Lookup(name)1758 }17591760 if flag == nil {1761 c.updateParentsPflags()1762 flag = c.parentsPflags.Lookup(name)1763 }1764 return1765}17661767// ParseFlags parses persistent flag tree and local flags.1768func (c *Command) ParseFlags(args []string) error {1769 if c.DisableFlagParsing {1770 return nil1771 }17721773 if c.flagErrorBuf == nil {1774 c.flagErrorBuf = new(bytes.Buffer)1775 }1776 beforeErrorBufLen := c.flagErrorBuf.Len()1777 c.mergePersistentFlags()17781779 // do it here after merging all flags and just before parse1780 c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)17811782 err := c.Flags().Parse(args)1783 // Print warnings if they occurred (e.g. deprecated flag messages).1784 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1785 c.Print(c.flagErrorBuf.String())1786 }17871788 return err1789}17901791// Parent returns a commands parent command.1792func (c *Command) Parent() *Command {1793 return c.parent1794}17951796// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1797// and adds missing persistent flags of all parents.1798func (c *Command) mergePersistentFlags() {1799 c.updateParentsPflags()1800 c.Flags().AddFlagSet(c.PersistentFlags())1801 c.Flags().AddFlagSet(c.parentsPflags)1802}18031804// updateParentsPflags updates c.parentsPflags by adding1805// new persistent flags of all parents.1806// If c.parentsPflags == nil, it makes new.1807func (c *Command) updateParentsPflags() {1808 if c.parentsPflags == nil {1809 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1810 c.parentsPflags.SetOutput(c.flagErrorBuf)1811 c.parentsPflags.SortFlags = false1812 }18131814 if c.globNormFunc != nil {1815 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1816 }18171818 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)18191820 c.VisitParents(func(parent *Command) {1821 c.parentsPflags.AddFlagSet(parent.PersistentFlags())1822 })1823}18241825// commandNameMatches checks if two command names are equal1826// taking into account case sensitivity according to1827// EnableCaseInsensitive global configuration.1828func commandNameMatches(s string, t string) bool {1829 if EnableCaseInsensitive {1830 return strings.EqualFold(s, t)1831 }18321833 return s == t1834}