Path: blob/main/vendor/github.com/spf13/cobra/command.go
2875 views
// Copyright 2013-2023 The Cobra Authors1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// 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"errors"22"fmt"23"io"24"os"25"path/filepath"26"sort"27"strings"2829flag "github.com/spf13/pflag"30)3132const (33FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"34CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"3536helpFlagName = "help"37helpCommandName = "help"38)3940// FParseErrWhitelist configures Flag parse errors to be ignored41type FParseErrWhitelist flag.ParseErrorsAllowlist4243// Group Structure to manage groups for commands44type Group struct {45ID string46Title string47}4849// Command is just that, a command for your application.50// E.g. 'go run ...' - 'run' is the command. Cobra requires51// you to define the usage and description as part of your command52// definition to ensure usability.53type Command struct {54// Use is the one-line usage message.55// Recommended syntax is as follows:56// [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.57// ... indicates that you can specify multiple values for the previous argument.58// | indicates mutually exclusive information. You can use the argument to the left of the separator or the59// argument to the right of the separator. You cannot use both arguments in a single use of the command.60// { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are61// optional, they are enclosed in brackets ([ ]).62// Example: add [-F file | -D dir]... [-f format] profile63Use string6465// Aliases is an array of aliases that can be used instead of the first word in Use.66Aliases []string6768// SuggestFor is an array of command names for which this command will be suggested -69// similar to aliases but only suggests.70SuggestFor []string7172// Short is the short description shown in the 'help' output.73Short string7475// The group id under which this subcommand is grouped in the 'help' output of its parent.76GroupID string7778// Long is the long message shown in the 'help <this-command>' output.79Long string8081// Example is examples of how to use the command.82Example string8384// ValidArgs is list of all valid non-flag arguments that are accepted in shell completions85ValidArgs []Completion86// ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.87// It is a dynamic version of using ValidArgs.88// Only one of ValidArgs and ValidArgsFunction can be used for a command.89ValidArgsFunction CompletionFunc9091// Expected arguments92Args PositionalArgs9394// ArgAliases is List of aliases for ValidArgs.95// These are not suggested to the user in the shell completion,96// but accepted if entered manually.97ArgAliases []string9899// BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.100// For portability with other shells, it is recommended to instead use ValidArgsFunction101BashCompletionFunction string102103// Deprecated defines, if this command is deprecated and should print this string when used.104Deprecated string105106// Annotations are key/value pairs that can be used by applications to identify or107// group commands or set special options.108Annotations map[string]string109110// Version defines the version for this command. If this value is non-empty and the command does not111// define a "version" flag, a "version" boolean flag will be added to the command and, if specified,112// will print content of the "Version" variable. A shorthand "v" flag will also be added if the113// command does not define one.114Version string115116// The *Run functions are executed in the following order:117// * PersistentPreRun()118// * PreRun()119// * Run()120// * PostRun()121// * PersistentPostRun()122// All functions get the same args, the arguments after the command name.123// The *PreRun and *PostRun functions will only be executed if the Run function of the current124// command has been declared.125//126// PersistentPreRun: children of this command will inherit and execute.127PersistentPreRun func(cmd *Command, args []string)128// PersistentPreRunE: PersistentPreRun but returns an error.129PersistentPreRunE func(cmd *Command, args []string) error130// PreRun: children of this command will not inherit.131PreRun func(cmd *Command, args []string)132// PreRunE: PreRun but returns an error.133PreRunE func(cmd *Command, args []string) error134// Run: Typically the actual work function. Most commands will only implement this.135Run func(cmd *Command, args []string)136// RunE: Run but returns an error.137RunE func(cmd *Command, args []string) error138// PostRun: run after the Run command.139PostRun func(cmd *Command, args []string)140// PostRunE: PostRun but returns an error.141PostRunE func(cmd *Command, args []string) error142// PersistentPostRun: children of this command will inherit and execute after PostRun.143PersistentPostRun func(cmd *Command, args []string)144// PersistentPostRunE: PersistentPostRun but returns an error.145PersistentPostRunE func(cmd *Command, args []string) error146147// groups for subcommands148commandgroups []*Group149150// args is actual args parsed from flags.151args []string152// flagErrorBuf contains all error messages from pflag.153flagErrorBuf *bytes.Buffer154// flags is full set of flags.155flags *flag.FlagSet156// pflags contains persistent flags.157pflags *flag.FlagSet158// lflags contains local flags.159// This field does not represent internal state, it's used as a cache to optimise LocalFlags function call160lflags *flag.FlagSet161// iflags contains inherited flags.162// This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call163iflags *flag.FlagSet164// parentsPflags is all persistent flags of cmd's parents.165parentsPflags *flag.FlagSet166// globNormFunc is the global normalization function167// that we can use on every pflag set and children commands168globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName169170// usageFunc is usage func defined by user.171usageFunc func(*Command) error172// usageTemplate is usage template defined by user.173usageTemplate *tmplFunc174// flagErrorFunc is func defined by user and it's called when the parsing of175// flags returns an error.176flagErrorFunc func(*Command, error) error177// helpTemplate is help template defined by user.178helpTemplate *tmplFunc179// helpFunc is help func defined by user.180helpFunc func(*Command, []string)181// helpCommand is command with usage 'help'. If it's not defined by user,182// cobra uses default help command.183helpCommand *Command184// helpCommandGroupID is the group id for the helpCommand185helpCommandGroupID string186187// completionCommandGroupID is the group id for the completion command188completionCommandGroupID string189190// versionTemplate is the version template defined by user.191versionTemplate *tmplFunc192193// errPrefix is the error message prefix defined by user.194errPrefix string195196// inReader is a reader defined by the user that replaces stdin197inReader io.Reader198// outWriter is a writer defined by the user that replaces stdout199outWriter io.Writer200// errWriter is a writer defined by the user that replaces stderr201errWriter io.Writer202203// FParseErrWhitelist flag parse errors to be ignored204FParseErrWhitelist FParseErrWhitelist205206// CompletionOptions is a set of options to control the handling of shell completion207CompletionOptions CompletionOptions208209// commandsAreSorted defines, if command slice are sorted or not.210commandsAreSorted bool211// commandCalledAs is the name or alias value used to call this command.212commandCalledAs struct {213name string214called bool215}216217ctx context.Context218219// commands is the list of commands supported by this program.220commands []*Command221// parent is a parent command for this command.222parent *Command223// Max lengths of commands' string lengths for use in padding.224commandsMaxUseLen int225commandsMaxCommandPathLen int226commandsMaxNameLen int227228// TraverseChildren parses flags on all parents before executing child command.229TraverseChildren bool230231// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.232Hidden bool233234// SilenceErrors is an option to quiet errors down stream.235SilenceErrors bool236237// SilenceUsage is an option to silence usage when an error occurs.238SilenceUsage bool239240// DisableFlagParsing disables the flag parsing.241// If this is true all flags will be passed to the command as arguments.242DisableFlagParsing bool243244// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")245// will be printed by generating docs for this command.246DisableAutoGenTag bool247248// DisableFlagsInUseLine will disable the addition of [flags] to the usage249// line of a command when printing help or generating docs250DisableFlagsInUseLine bool251252// DisableSuggestions disables the suggestions based on Levenshtein distance253// that go along with 'unknown command' messages.254DisableSuggestions bool255256// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.257// Must be > 0.258SuggestionsMinimumDistance int259}260261// Context returns underlying command context. If command was executed262// with ExecuteContext or the context was set with SetContext, the263// previously set context will be returned. Otherwise, nil is returned.264//265// Notice that a call to Execute and ExecuteC will replace a nil context of266// a command with a context.Background, so a background context will be267// returned by Context after one of these functions has been called.268func (c *Command) Context() context.Context {269return c.ctx270}271272// SetContext sets context for the command. This context will be overwritten by273// Command.ExecuteContext or Command.ExecuteContextC.274func (c *Command) SetContext(ctx context.Context) {275c.ctx = ctx276}277278// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden279// particularly useful when testing.280func (c *Command) SetArgs(a []string) {281c.args = a282}283284// SetOutput sets the destination for usage and error messages.285// If output is nil, os.Stderr is used.286//287// Deprecated: Use SetOut and/or SetErr instead288func (c *Command) SetOutput(output io.Writer) {289c.outWriter = output290c.errWriter = output291}292293// SetOut sets the destination for usage messages.294// If newOut is nil, os.Stdout is used.295func (c *Command) SetOut(newOut io.Writer) {296c.outWriter = newOut297}298299// SetErr sets the destination for error messages.300// If newErr is nil, os.Stderr is used.301func (c *Command) SetErr(newErr io.Writer) {302c.errWriter = newErr303}304305// SetIn sets the source for input data306// If newIn is nil, os.Stdin is used.307func (c *Command) SetIn(newIn io.Reader) {308c.inReader = newIn309}310311// SetUsageFunc sets usage function. Usage can be defined by application.312func (c *Command) SetUsageFunc(f func(*Command) error) {313c.usageFunc = f314}315316// SetUsageTemplate sets usage template. Can be defined by Application.317func (c *Command) SetUsageTemplate(s string) {318if s == "" {319c.usageTemplate = nil320return321}322c.usageTemplate = tmpl(s)323}324325// SetFlagErrorFunc sets a function to generate an error when flag parsing326// fails.327func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {328c.flagErrorFunc = f329}330331// SetHelpFunc sets help function. Can be defined by Application.332func (c *Command) SetHelpFunc(f func(*Command, []string)) {333c.helpFunc = f334}335336// SetHelpCommand sets help command.337func (c *Command) SetHelpCommand(cmd *Command) {338c.helpCommand = cmd339}340341// SetHelpCommandGroupID sets the group id of the help command.342func (c *Command) SetHelpCommandGroupID(groupID string) {343if c.helpCommand != nil {344c.helpCommand.GroupID = groupID345}346// helpCommandGroupID is used if no helpCommand is defined by the user347c.helpCommandGroupID = groupID348}349350// SetCompletionCommandGroupID sets the group id of the completion command.351func (c *Command) SetCompletionCommandGroupID(groupID string) {352// completionCommandGroupID is used if no completion command is defined by the user353c.Root().completionCommandGroupID = groupID354}355356// SetHelpTemplate sets help template to be used. Application can use it to set custom template.357func (c *Command) SetHelpTemplate(s string) {358if s == "" {359c.helpTemplate = nil360return361}362c.helpTemplate = tmpl(s)363}364365// SetVersionTemplate sets version template to be used. Application can use it to set custom template.366func (c *Command) SetVersionTemplate(s string) {367if s == "" {368c.versionTemplate = nil369return370}371c.versionTemplate = tmpl(s)372}373374// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.375func (c *Command) SetErrPrefix(s string) {376c.errPrefix = s377}378379// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.380// The user should not have a cyclic dependency on commands.381func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {382c.Flags().SetNormalizeFunc(n)383c.PersistentFlags().SetNormalizeFunc(n)384c.globNormFunc = n385386for _, command := range c.commands {387command.SetGlobalNormalizationFunc(n)388}389}390391// OutOrStdout returns output to stdout.392func (c *Command) OutOrStdout() io.Writer {393return c.getOut(os.Stdout)394}395396// OutOrStderr returns output to stderr397func (c *Command) OutOrStderr() io.Writer {398return c.getOut(os.Stderr)399}400401// ErrOrStderr returns output to stderr402func (c *Command) ErrOrStderr() io.Writer {403return c.getErr(os.Stderr)404}405406// InOrStdin returns input to stdin407func (c *Command) InOrStdin() io.Reader {408return c.getIn(os.Stdin)409}410411func (c *Command) getOut(def io.Writer) io.Writer {412if c.outWriter != nil {413return c.outWriter414}415if c.HasParent() {416return c.parent.getOut(def)417}418return def419}420421func (c *Command) getErr(def io.Writer) io.Writer {422if c.errWriter != nil {423return c.errWriter424}425if c.HasParent() {426return c.parent.getErr(def)427}428return def429}430431func (c *Command) getIn(def io.Reader) io.Reader {432if c.inReader != nil {433return c.inReader434}435if c.HasParent() {436return c.parent.getIn(def)437}438return def439}440441// UsageFunc returns either the function set by SetUsageFunc for this command442// or a parent, or it returns a default usage function.443func (c *Command) UsageFunc() (f func(*Command) error) {444if c.usageFunc != nil {445return c.usageFunc446}447if c.HasParent() {448return c.Parent().UsageFunc()449}450return func(c *Command) error {451c.mergePersistentFlags()452fn := c.getUsageTemplateFunc()453err := fn(c.OutOrStderr(), c)454if err != nil {455c.PrintErrln(err)456}457return err458}459}460461// getUsageTemplateFunc returns the usage template function for the command462// going up the command tree if necessary.463func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error {464if c.usageTemplate != nil {465return c.usageTemplate.fn466}467468if c.HasParent() {469return c.parent.getUsageTemplateFunc()470}471return defaultUsageFunc472}473474// Usage puts out the usage for the command.475// Used when a user provides invalid input.476// Can be defined by user by overriding UsageFunc.477func (c *Command) Usage() error {478return c.UsageFunc()(c)479}480481// HelpFunc returns either the function set by SetHelpFunc for this command482// or a parent, or it returns a function with default help behavior.483func (c *Command) HelpFunc() func(*Command, []string) {484if c.helpFunc != nil {485return c.helpFunc486}487if c.HasParent() {488return c.Parent().HelpFunc()489}490return func(c *Command, a []string) {491c.mergePersistentFlags()492fn := c.getHelpTemplateFunc()493// The help should be sent to stdout494// See https://github.com/spf13/cobra/issues/1002495err := fn(c.OutOrStdout(), c)496if err != nil {497c.PrintErrln(err)498}499}500}501502// getHelpTemplateFunc returns the help template function for the command503// going up the command tree if necessary.504func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error {505if c.helpTemplate != nil {506return c.helpTemplate.fn507}508509if c.HasParent() {510return c.parent.getHelpTemplateFunc()511}512513return defaultHelpFunc514}515516// Help puts out the help for the command.517// Used when a user calls help [command].518// Can be defined by user by overriding HelpFunc.519func (c *Command) Help() error {520c.HelpFunc()(c, []string{})521return nil522}523524// UsageString returns usage string.525func (c *Command) UsageString() string {526// Storing normal writers527tmpOutput := c.outWriter528tmpErr := c.errWriter529530bb := new(bytes.Buffer)531c.outWriter = bb532c.errWriter = bb533534CheckErr(c.Usage())535536// Setting things back to normal537c.outWriter = tmpOutput538c.errWriter = tmpErr539540return bb.String()541}542543// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this544// command or a parent, or it returns a function which returns the original545// error.546func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {547if c.flagErrorFunc != nil {548return c.flagErrorFunc549}550551if c.HasParent() {552return c.parent.FlagErrorFunc()553}554return func(c *Command, err error) error {555return err556}557}558559var minUsagePadding = 25560561// UsagePadding return padding for the usage.562func (c *Command) UsagePadding() int {563if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {564return minUsagePadding565}566return c.parent.commandsMaxUseLen567}568569var minCommandPathPadding = 11570571// CommandPathPadding return padding for the command path.572func (c *Command) CommandPathPadding() int {573if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {574return minCommandPathPadding575}576return c.parent.commandsMaxCommandPathLen577}578579var minNamePadding = 11580581// NamePadding returns padding for the name.582func (c *Command) NamePadding() int {583if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {584return minNamePadding585}586return c.parent.commandsMaxNameLen587}588589// UsageTemplate returns usage template for the command.590// This function is kept for backwards-compatibility reasons.591func (c *Command) UsageTemplate() string {592if c.usageTemplate != nil {593return c.usageTemplate.tmpl594}595596if c.HasParent() {597return c.parent.UsageTemplate()598}599return defaultUsageTemplate600}601602// HelpTemplate return help template for the command.603// This function is kept for backwards-compatibility reasons.604func (c *Command) HelpTemplate() string {605if c.helpTemplate != nil {606return c.helpTemplate.tmpl607}608609if c.HasParent() {610return c.parent.HelpTemplate()611}612return defaultHelpTemplate613}614615// VersionTemplate return version template for the command.616// This function is kept for backwards-compatibility reasons.617func (c *Command) VersionTemplate() string {618if c.versionTemplate != nil {619return c.versionTemplate.tmpl620}621622if c.HasParent() {623return c.parent.VersionTemplate()624}625return defaultVersionTemplate626}627628// getVersionTemplateFunc returns the version template function for the command629// going up the command tree if necessary.630func (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error {631if c.versionTemplate != nil {632return c.versionTemplate.fn633}634635if c.HasParent() {636return c.parent.getVersionTemplateFunc()637}638return defaultVersionFunc639}640641// ErrPrefix return error message prefix for the command642func (c *Command) ErrPrefix() string {643if c.errPrefix != "" {644return c.errPrefix645}646647if c.HasParent() {648return c.parent.ErrPrefix()649}650return "Error:"651}652653func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {654flag := fs.Lookup(name)655if flag == nil {656return false657}658return flag.NoOptDefVal != ""659}660661func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {662if len(name) == 0 {663return false664}665666flag := fs.ShorthandLookup(name[:1])667if flag == nil {668return false669}670return flag.NoOptDefVal != ""671}672673func stripFlags(args []string, c *Command) []string {674if len(args) == 0 {675return args676}677c.mergePersistentFlags()678679commands := []string{}680flags := c.Flags()681682Loop:683for len(args) > 0 {684s := args[0]685args = args[1:]686switch {687case s == "--":688// "--" terminates the flags689break Loop690case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):691// If '--flag arg' then692// delete arg from args.693fallthrough // (do the same as below)694case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):695// If '-f arg' then696// delete 'arg' from args or break the loop if len(args) <= 1.697if len(args) <= 1 {698break Loop699} else {700args = args[1:]701continue702}703case s != "" && !strings.HasPrefix(s, "-"):704commands = append(commands, s)705}706}707708return commands709}710711// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like712// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).713// Special care needs to be taken not to remove a flag value.714func (c *Command) argsMinusFirstX(args []string, x string) []string {715if len(args) == 0 {716return args717}718c.mergePersistentFlags()719flags := c.Flags()720721Loop:722for pos := 0; pos < len(args); pos++ {723s := args[pos]724switch {725case s == "--":726// -- means we have reached the end of the parseable args. Break out of the loop now.727break Loop728case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):729fallthrough730case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):731// This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip732// over the next arg, because that is the value of this flag.733pos++734continue735case !strings.HasPrefix(s, "-"):736// This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,737// return the args, excluding the one at this position.738if s == x {739ret := make([]string, 0, len(args)-1)740ret = append(ret, args[:pos]...)741ret = append(ret, args[pos+1:]...)742return ret743}744}745}746return args747}748749func isFlagArg(arg string) bool {750return ((len(arg) >= 3 && arg[0:2] == "--") ||751(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))752}753754// Find the target command given the args and command tree755// Meant to be run on the highest node. Only searches down.756func (c *Command) Find(args []string) (*Command, []string, error) {757var innerfind func(*Command, []string) (*Command, []string)758759innerfind = func(c *Command, innerArgs []string) (*Command, []string) {760argsWOflags := stripFlags(innerArgs, c)761if len(argsWOflags) == 0 {762return c, innerArgs763}764nextSubCmd := argsWOflags[0]765766cmd := c.findNext(nextSubCmd)767if cmd != nil {768return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd))769}770return c, innerArgs771}772773commandFound, a := innerfind(c, args)774if commandFound.Args == nil {775return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))776}777return commandFound, a, nil778}779780func (c *Command) findSuggestions(arg string) string {781if c.DisableSuggestions {782return ""783}784if c.SuggestionsMinimumDistance <= 0 {785c.SuggestionsMinimumDistance = 2786}787var sb strings.Builder788if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {789sb.WriteString("\n\nDid you mean this?\n")790for _, s := range suggestions {791_, _ = fmt.Fprintf(&sb, "\t%v\n", s)792}793}794return sb.String()795}796797func (c *Command) findNext(next string) *Command {798matches := make([]*Command, 0)799for _, cmd := range c.commands {800if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {801cmd.commandCalledAs.name = next802return cmd803}804if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {805matches = append(matches, cmd)806}807}808809if len(matches) == 1 {810// Temporarily disable gosec G602, which produces a false positive.811// See https://github.com/securego/gosec/issues/1005.812return matches[0] // #nosec G602813}814815return nil816}817818// Traverse the command tree to find the command, and parse args for819// each parent.820func (c *Command) Traverse(args []string) (*Command, []string, error) {821flags := []string{}822inFlag := false823824for i, arg := range args {825switch {826// A long flag with a space separated value827case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):828// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'829inFlag = !hasNoOptDefVal(arg[2:], c.Flags())830flags = append(flags, arg)831continue832// A short flag with a space separated value833case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):834inFlag = true835flags = append(flags, arg)836continue837// The value for a flag838case inFlag:839inFlag = false840flags = append(flags, arg)841continue842// A flag without a value, or with an `=` separated value843case isFlagArg(arg):844flags = append(flags, arg)845continue846}847848cmd := c.findNext(arg)849if cmd == nil {850return c, args, nil851}852853if err := c.ParseFlags(flags); err != nil {854return nil, args, err855}856return cmd.Traverse(args[i+1:])857}858return c, args, nil859}860861// SuggestionsFor provides suggestions for the typedName.862func (c *Command) SuggestionsFor(typedName string) []string {863suggestions := []string{}864for _, cmd := range c.commands {865if cmd.IsAvailableCommand() {866levenshteinDistance := ld(typedName, cmd.Name(), true)867suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance868suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))869if suggestByLevenshtein || suggestByPrefix {870suggestions = append(suggestions, cmd.Name())871}872for _, explicitSuggestion := range cmd.SuggestFor {873if strings.EqualFold(typedName, explicitSuggestion) {874suggestions = append(suggestions, cmd.Name())875}876}877}878}879return suggestions880}881882// VisitParents visits all parents of the command and invokes fn on each parent.883func (c *Command) VisitParents(fn func(*Command)) {884if c.HasParent() {885fn(c.Parent())886c.Parent().VisitParents(fn)887}888}889890// Root finds root command.891func (c *Command) Root() *Command {892if c.HasParent() {893return c.Parent().Root()894}895return c896}897898// ArgsLenAtDash will return the length of c.Flags().Args at the moment899// when a -- was found during args parsing.900func (c *Command) ArgsLenAtDash() int {901return c.Flags().ArgsLenAtDash()902}903904func (c *Command) execute(a []string) (err error) {905if c == nil {906return fmt.Errorf("called Execute() on a nil Command")907}908909if len(c.Deprecated) > 0 {910c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)911}912913// initialize help and version flag at the last point possible to allow for user914// overriding915c.InitDefaultHelpFlag()916c.InitDefaultVersionFlag()917918err = c.ParseFlags(a)919if err != nil {920return c.FlagErrorFunc()(c, err)921}922923// If help is called, regardless of other flags, return we want help.924// Also say we need help if the command isn't runnable.925helpVal, err := c.Flags().GetBool(helpFlagName)926if err != nil {927// should be impossible to get here as we always declare a help928// flag in InitDefaultHelpFlag()929c.Println("\"help\" flag declared as non-bool. Please correct your code")930return err931}932933if helpVal {934return flag.ErrHelp935}936937// for back-compat, only add version flag behavior if version is defined938if c.Version != "" {939versionVal, err := c.Flags().GetBool("version")940if err != nil {941c.Println("\"version\" flag declared as non-bool. Please correct your code")942return err943}944if versionVal {945fn := c.getVersionTemplateFunc()946err := fn(c.OutOrStdout(), c)947if err != nil {948c.Println(err)949}950return err951}952}953954if !c.Runnable() {955return flag.ErrHelp956}957958c.preRun()959960defer c.postRun()961962argWoFlags := c.Flags().Args()963if c.DisableFlagParsing {964argWoFlags = a965}966967if err := c.ValidateArgs(argWoFlags); err != nil {968return err969}970971parents := make([]*Command, 0, 5)972for p := c; p != nil; p = p.Parent() {973if EnableTraverseRunHooks {974// When EnableTraverseRunHooks is set:975// - Execute all persistent pre-runs from the root parent till this command.976// - Execute all persistent post-runs from this command till the root parent.977parents = append([]*Command{p}, parents...)978} else {979// Otherwise, execute only the first found persistent hook.980parents = append(parents, p)981}982}983for _, p := range parents {984if p.PersistentPreRunE != nil {985if err := p.PersistentPreRunE(c, argWoFlags); err != nil {986return err987}988if !EnableTraverseRunHooks {989break990}991} else if p.PersistentPreRun != nil {992p.PersistentPreRun(c, argWoFlags)993if !EnableTraverseRunHooks {994break995}996}997}998if c.PreRunE != nil {999if err := c.PreRunE(c, argWoFlags); err != nil {1000return err1001}1002} else if c.PreRun != nil {1003c.PreRun(c, argWoFlags)1004}10051006if err := c.ValidateRequiredFlags(); err != nil {1007return err1008}1009if err := c.ValidateFlagGroups(); err != nil {1010return err1011}10121013if c.RunE != nil {1014if err := c.RunE(c, argWoFlags); err != nil {1015return err1016}1017} else {1018c.Run(c, argWoFlags)1019}1020if c.PostRunE != nil {1021if err := c.PostRunE(c, argWoFlags); err != nil {1022return err1023}1024} else if c.PostRun != nil {1025c.PostRun(c, argWoFlags)1026}1027for p := c; p != nil; p = p.Parent() {1028if p.PersistentPostRunE != nil {1029if err := p.PersistentPostRunE(c, argWoFlags); err != nil {1030return err1031}1032if !EnableTraverseRunHooks {1033break1034}1035} else if p.PersistentPostRun != nil {1036p.PersistentPostRun(c, argWoFlags)1037if !EnableTraverseRunHooks {1038break1039}1040}1041}10421043return nil1044}10451046func (c *Command) preRun() {1047for _, x := range initializers {1048x()1049}1050}10511052func (c *Command) postRun() {1053for _, x := range finalizers {1054x()1055}1056}10571058// ExecuteContext is the same as Execute(), but sets the ctx on the command.1059// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs1060// functions.1061func (c *Command) ExecuteContext(ctx context.Context) error {1062c.ctx = ctx1063return c.Execute()1064}10651066// Execute uses the args (os.Args[1:] by default)1067// and run through the command tree finding appropriate matches1068// for commands and then corresponding flags.1069func (c *Command) Execute() error {1070_, err := c.ExecuteC()1071return err1072}10731074// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.1075// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs1076// functions.1077func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {1078c.ctx = ctx1079return c.ExecuteC()1080}10811082// ExecuteC executes the command.1083func (c *Command) ExecuteC() (cmd *Command, err error) {1084if c.ctx == nil {1085c.ctx = context.Background()1086}10871088// Regardless of what command execute is called on, run on Root only1089if c.HasParent() {1090return c.Root().ExecuteC()1091}10921093// windows hook1094if preExecHookFn != nil {1095preExecHookFn(c)1096}10971098// initialize help at the last point to allow for user overriding1099c.InitDefaultHelpCmd()11001101args := c.args11021103// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #1551104if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {1105args = os.Args[1:]1106}11071108// initialize the __complete command to be used for shell completion1109c.initCompleteCmd(args)11101111// initialize the default completion command1112c.InitDefaultCompletionCmd(args...)11131114// Now that all commands have been created, let's make sure all groups1115// are properly created also1116c.checkCommandGroups()11171118var flags []string1119if c.TraverseChildren {1120cmd, flags, err = c.Traverse(args)1121} else {1122cmd, flags, err = c.Find(args)1123}1124if err != nil {1125// If found parse to a subcommand and then failed, talk about the subcommand1126if cmd != nil {1127c = cmd1128}1129if !c.SilenceErrors {1130c.PrintErrln(c.ErrPrefix(), err.Error())1131c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())1132}1133return c, err1134}11351136cmd.commandCalledAs.called = true1137if cmd.commandCalledAs.name == "" {1138cmd.commandCalledAs.name = cmd.Name()1139}11401141// We have to pass global context to children command1142// if context is present on the parent command.1143if cmd.ctx == nil {1144cmd.ctx = c.ctx1145}11461147err = cmd.execute(flags)1148if err != nil {1149// Always show help if requested, even if SilenceErrors is in1150// effect1151if errors.Is(err, flag.ErrHelp) {1152cmd.HelpFunc()(cmd, args)1153return cmd, nil1154}11551156// If root command has SilenceErrors flagged,1157// all subcommands should respect it1158if !cmd.SilenceErrors && !c.SilenceErrors {1159c.PrintErrln(cmd.ErrPrefix(), err.Error())1160}11611162// If root command has SilenceUsage flagged,1163// all subcommands should respect it1164if !cmd.SilenceUsage && !c.SilenceUsage {1165c.Println(cmd.UsageString())1166}1167}1168return cmd, err1169}11701171func (c *Command) ValidateArgs(args []string) error {1172if c.Args == nil {1173return ArbitraryArgs(c, args)1174}1175return c.Args(c, args)1176}11771178// ValidateRequiredFlags validates all required flags are present and returns an error otherwise1179func (c *Command) ValidateRequiredFlags() error {1180if c.DisableFlagParsing {1181return nil1182}11831184flags := c.Flags()1185missingFlagNames := []string{}1186flags.VisitAll(func(pflag *flag.Flag) {1187requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]1188if !found {1189return1190}1191if (requiredAnnotation[0] == "true") && !pflag.Changed {1192missingFlagNames = append(missingFlagNames, pflag.Name)1193}1194})11951196if len(missingFlagNames) > 0 {1197return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))1198}1199return nil1200}12011202// checkCommandGroups checks if a command has been added to a group that does not exists.1203// If so, we panic because it indicates a coding error that should be corrected.1204func (c *Command) checkCommandGroups() {1205for _, sub := range c.commands {1206// if Group is not defined let the developer know right away1207if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) {1208panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath()))1209}12101211sub.checkCommandGroups()1212}1213}12141215// InitDefaultHelpFlag adds default help flag to c.1216// It is called automatically by executing the c or by calling help and usage.1217// If c already has help flag, it will do nothing.1218func (c *Command) InitDefaultHelpFlag() {1219c.mergePersistentFlags()1220if c.Flags().Lookup(helpFlagName) == nil {1221usage := "help for "1222name := c.DisplayName()1223if name == "" {1224usage += "this command"1225} else {1226usage += name1227}1228c.Flags().BoolP(helpFlagName, "h", false, usage)1229_ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"})1230}1231}12321233// InitDefaultVersionFlag adds default version flag to c.1234// It is called automatically by executing the c.1235// If c already has a version flag, it will do nothing.1236// If c.Version is empty, it will do nothing.1237func (c *Command) InitDefaultVersionFlag() {1238if c.Version == "" {1239return1240}12411242c.mergePersistentFlags()1243if c.Flags().Lookup("version") == nil {1244usage := "version for "1245if c.Name() == "" {1246usage += "this command"1247} else {1248usage += c.DisplayName()1249}1250if c.Flags().ShorthandLookup("v") == nil {1251c.Flags().BoolP("version", "v", false, usage)1252} else {1253c.Flags().Bool("version", false, usage)1254}1255_ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"})1256}1257}12581259// InitDefaultHelpCmd adds default help command to c.1260// It is called automatically by executing the c or by calling help and usage.1261// If c already has help command or c has no subcommands, it will do nothing.1262func (c *Command) InitDefaultHelpCmd() {1263if !c.HasSubCommands() {1264return1265}12661267if c.helpCommand == nil {1268c.helpCommand = &Command{1269Use: "help [command]",1270Short: "Help about any command",1271Long: `Help provides help for any command in the application.1272Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,1273ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {1274var completions []Completion1275cmd, _, e := c.Root().Find(args)1276if e != nil {1277return nil, ShellCompDirectiveNoFileComp1278}1279if cmd == nil {1280// Root help command.1281cmd = c.Root()1282}1283for _, subCmd := range cmd.Commands() {1284if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {1285if strings.HasPrefix(subCmd.Name(), toComplete) {1286completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))1287}1288}1289}1290return completions, ShellCompDirectiveNoFileComp1291},1292Run: func(c *Command, args []string) {1293cmd, _, e := c.Root().Find(args)1294if cmd == nil || e != nil {1295c.Printf("Unknown help topic %#q\n", args)1296CheckErr(c.Root().Usage())1297} else {1298// FLow the context down to be used in help text1299if cmd.ctx == nil {1300cmd.ctx = c.ctx1301}13021303cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1304cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown1305CheckErr(cmd.Help())1306}1307},1308GroupID: c.helpCommandGroupID,1309}1310}1311c.RemoveCommand(c.helpCommand)1312c.AddCommand(c.helpCommand)1313}13141315// ResetCommands delete parent, subcommand and help command from c.1316func (c *Command) ResetCommands() {1317c.parent = nil1318c.commands = nil1319c.helpCommand = nil1320c.parentsPflags = nil1321}13221323// Sorts commands by their names.1324type commandSorterByName []*Command13251326func (c commandSorterByName) Len() int { return len(c) }1327func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }1328func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }13291330// Commands returns a sorted slice of child commands.1331func (c *Command) Commands() []*Command {1332// do not sort commands if it already sorted or sorting was disabled1333if EnableCommandSorting && !c.commandsAreSorted {1334sort.Sort(commandSorterByName(c.commands))1335c.commandsAreSorted = true1336}1337return c.commands1338}13391340// AddCommand adds one or more commands to this parent command.1341func (c *Command) AddCommand(cmds ...*Command) {1342for i, x := range cmds {1343if cmds[i] == c {1344panic("Command can't be a child of itself")1345}1346cmds[i].parent = c1347// update max lengths1348usageLen := len(x.Use)1349if usageLen > c.commandsMaxUseLen {1350c.commandsMaxUseLen = usageLen1351}1352commandPathLen := len(x.CommandPath())1353if commandPathLen > c.commandsMaxCommandPathLen {1354c.commandsMaxCommandPathLen = commandPathLen1355}1356nameLen := len(x.Name())1357if nameLen > c.commandsMaxNameLen {1358c.commandsMaxNameLen = nameLen1359}1360// If global normalization function exists, update all children1361if c.globNormFunc != nil {1362x.SetGlobalNormalizationFunc(c.globNormFunc)1363}1364c.commands = append(c.commands, x)1365c.commandsAreSorted = false1366}1367}13681369// Groups returns a slice of child command groups.1370func (c *Command) Groups() []*Group {1371return c.commandgroups1372}13731374// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group1375func (c *Command) AllChildCommandsHaveGroup() bool {1376for _, sub := range c.commands {1377if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {1378return false1379}1380}1381return true1382}13831384// ContainsGroup return if groupID exists in the list of command groups.1385func (c *Command) ContainsGroup(groupID string) bool {1386for _, x := range c.commandgroups {1387if x.ID == groupID {1388return true1389}1390}1391return false1392}13931394// AddGroup adds one or more command groups to this parent command.1395func (c *Command) AddGroup(groups ...*Group) {1396c.commandgroups = append(c.commandgroups, groups...)1397}13981399// RemoveCommand removes one or more commands from a parent command.1400func (c *Command) RemoveCommand(cmds ...*Command) {1401commands := []*Command{}1402main:1403for _, command := range c.commands {1404for _, cmd := range cmds {1405if command == cmd {1406command.parent = nil1407continue main1408}1409}1410commands = append(commands, command)1411}1412c.commands = commands1413// recompute all lengths1414c.commandsMaxUseLen = 01415c.commandsMaxCommandPathLen = 01416c.commandsMaxNameLen = 01417for _, command := range c.commands {1418usageLen := len(command.Use)1419if usageLen > c.commandsMaxUseLen {1420c.commandsMaxUseLen = usageLen1421}1422commandPathLen := len(command.CommandPath())1423if commandPathLen > c.commandsMaxCommandPathLen {1424c.commandsMaxCommandPathLen = commandPathLen1425}1426nameLen := len(command.Name())1427if nameLen > c.commandsMaxNameLen {1428c.commandsMaxNameLen = nameLen1429}1430}1431}14321433// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1434func (c *Command) Print(i ...interface{}) {1435fmt.Fprint(c.OutOrStderr(), i...)1436}14371438// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1439func (c *Command) Println(i ...interface{}) {1440c.Print(fmt.Sprintln(i...))1441}14421443// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1444func (c *Command) Printf(format string, i ...interface{}) {1445c.Print(fmt.Sprintf(format, i...))1446}14471448// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.1449func (c *Command) PrintErr(i ...interface{}) {1450fmt.Fprint(c.ErrOrStderr(), i...)1451}14521453// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.1454func (c *Command) PrintErrln(i ...interface{}) {1455c.PrintErr(fmt.Sprintln(i...))1456}14571458// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.1459func (c *Command) PrintErrf(format string, i ...interface{}) {1460c.PrintErr(fmt.Sprintf(format, i...))1461}14621463// CommandPath returns the full path to this command.1464func (c *Command) CommandPath() string {1465if c.HasParent() {1466return c.Parent().CommandPath() + " " + c.Name()1467}1468return c.DisplayName()1469}14701471// DisplayName returns the name to display in help text. Returns command Name()1472// If CommandDisplayNameAnnoation is not set1473func (c *Command) DisplayName() string {1474if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {1475return displayName1476}1477return c.Name()1478}14791480// UseLine puts out the full usage for a given command (including parents).1481func (c *Command) UseLine() string {1482var useline string1483use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1)1484if c.HasParent() {1485useline = c.parent.CommandPath() + " " + use1486} else {1487useline = use1488}1489if c.DisableFlagsInUseLine {1490return useline1491}1492if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1493useline += " [flags]"1494}1495return useline1496}14971498// DebugFlags used to determine which flags have been assigned to which commands1499// and which persist.1500func (c *Command) DebugFlags() {1501c.Println("DebugFlags called on", c.Name())1502var debugflags func(*Command)15031504debugflags = func(x *Command) {1505if x.HasFlags() || x.HasPersistentFlags() {1506c.Println(x.Name())1507}1508if x.HasFlags() {1509x.flags.VisitAll(func(f *flag.Flag) {1510if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1511c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1512} else {1513c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1514}1515})1516}1517if x.HasPersistentFlags() {1518x.pflags.VisitAll(func(f *flag.Flag) {1519if x.HasFlags() {1520if x.flags.Lookup(f.Name) == nil {1521c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1522}1523} else {1524c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1525}1526})1527}1528c.Println(x.flagErrorBuf)1529if x.HasSubCommands() {1530for _, y := range x.commands {1531debugflags(y)1532}1533}1534}15351536debugflags(c)1537}15381539// Name returns the command's name: the first word in the use line.1540func (c *Command) Name() string {1541name := c.Use1542i := strings.Index(name, " ")1543if i >= 0 {1544name = name[:i]1545}1546return name1547}15481549// HasAlias determines if a given string is an alias of the command.1550func (c *Command) HasAlias(s string) bool {1551for _, a := range c.Aliases {1552if commandNameMatches(a, s) {1553return true1554}1555}1556return false1557}15581559// CalledAs returns the command name or alias that was used to invoke1560// this command or an empty string if the command has not been called.1561func (c *Command) CalledAs() string {1562if c.commandCalledAs.called {1563return c.commandCalledAs.name1564}1565return ""1566}15671568// hasNameOrAliasPrefix returns true if the Name or any of aliases start1569// with prefix1570func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1571if strings.HasPrefix(c.Name(), prefix) {1572c.commandCalledAs.name = c.Name()1573return true1574}1575for _, alias := range c.Aliases {1576if strings.HasPrefix(alias, prefix) {1577c.commandCalledAs.name = alias1578return true1579}1580}1581return false1582}15831584// NameAndAliases returns a list of the command name and all aliases1585func (c *Command) NameAndAliases() string {1586return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1587}15881589// HasExample determines if the command has example.1590func (c *Command) HasExample() bool {1591return len(c.Example) > 01592}15931594// Runnable determines if the command is itself runnable.1595func (c *Command) Runnable() bool {1596return c.Run != nil || c.RunE != nil1597}15981599// HasSubCommands determines if the command has children commands.1600func (c *Command) HasSubCommands() bool {1601return len(c.commands) > 01602}16031604// IsAvailableCommand determines if a command is available as a non-help command1605// (this includes all non deprecated/hidden commands).1606func (c *Command) IsAvailableCommand() bool {1607if len(c.Deprecated) != 0 || c.Hidden {1608return false1609}16101611if c.HasParent() && c.Parent().helpCommand == c {1612return false1613}16141615if c.Runnable() || c.HasAvailableSubCommands() {1616return true1617}16181619return false1620}16211622// IsAdditionalHelpTopicCommand determines if a command is an additional1623// help topic command; additional help topic command is determined by the1624// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1625// are runnable/hidden/deprecated.1626// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1627func (c *Command) IsAdditionalHelpTopicCommand() bool {1628// if a command is runnable, deprecated, or hidden it is not a 'help' command1629if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1630return false1631}16321633// if any non-help sub commands are found, the command is not a 'help' command1634for _, sub := range c.commands {1635if !sub.IsAdditionalHelpTopicCommand() {1636return false1637}1638}16391640// the command either has no sub commands, or no non-help sub commands1641return true1642}16431644// HasHelpSubCommands determines if a command has any available 'help' sub commands1645// that need to be shown in the usage/help default template under 'additional help1646// topics'.1647func (c *Command) HasHelpSubCommands() bool {1648// return true on the first found available 'help' sub command1649for _, sub := range c.commands {1650if sub.IsAdditionalHelpTopicCommand() {1651return true1652}1653}16541655// the command either has no sub commands, or no available 'help' sub commands1656return false1657}16581659// HasAvailableSubCommands determines if a command has available sub commands that1660// need to be shown in the usage/help default template under 'available commands'.1661func (c *Command) HasAvailableSubCommands() bool {1662// return true on the first found available (non deprecated/help/hidden)1663// sub command1664for _, sub := range c.commands {1665if sub.IsAvailableCommand() {1666return true1667}1668}16691670// the command either has no sub commands, or no available (non deprecated/help/hidden)1671// sub commands1672return false1673}16741675// HasParent determines if the command is a child command.1676func (c *Command) HasParent() bool {1677return c.parent != nil1678}16791680// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.1681func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1682return c.globNormFunc1683}16841685// Flags returns the complete FlagSet that applies1686// to this command (local and persistent declared here and by all parents).1687func (c *Command) Flags() *flag.FlagSet {1688if c.flags == nil {1689c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)1690if c.flagErrorBuf == nil {1691c.flagErrorBuf = new(bytes.Buffer)1692}1693c.flags.SetOutput(c.flagErrorBuf)1694}16951696return c.flags1697}16981699// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1700// This function does not modify the flags of the current command, it's purpose is to return the current state.1701func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1702persistentFlags := c.PersistentFlags()17031704out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)1705c.LocalFlags().VisitAll(func(f *flag.Flag) {1706if persistentFlags.Lookup(f.Name) == nil {1707out.AddFlag(f)1708}1709})1710return out1711}17121713// LocalFlags returns the local FlagSet specifically set in the current command.1714// This function does not modify the flags of the current command, it's purpose is to return the current state.1715func (c *Command) LocalFlags() *flag.FlagSet {1716c.mergePersistentFlags()17171718if c.lflags == nil {1719c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)1720if c.flagErrorBuf == nil {1721c.flagErrorBuf = new(bytes.Buffer)1722}1723c.lflags.SetOutput(c.flagErrorBuf)1724}1725c.lflags.SortFlags = c.Flags().SortFlags1726if c.globNormFunc != nil {1727c.lflags.SetNormalizeFunc(c.globNormFunc)1728}17291730addToLocal := func(f *flag.Flag) {1731// Add the flag if it is not a parent PFlag, or it shadows a parent PFlag1732if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {1733c.lflags.AddFlag(f)1734}1735}1736c.Flags().VisitAll(addToLocal)1737c.PersistentFlags().VisitAll(addToLocal)1738return c.lflags1739}17401741// InheritedFlags returns all flags which were inherited from parent commands.1742// This function does not modify the flags of the current command, it's purpose is to return the current state.1743func (c *Command) InheritedFlags() *flag.FlagSet {1744c.mergePersistentFlags()17451746if c.iflags == nil {1747c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)1748if c.flagErrorBuf == nil {1749c.flagErrorBuf = new(bytes.Buffer)1750}1751c.iflags.SetOutput(c.flagErrorBuf)1752}17531754local := c.LocalFlags()1755if c.globNormFunc != nil {1756c.iflags.SetNormalizeFunc(c.globNormFunc)1757}17581759c.parentsPflags.VisitAll(func(f *flag.Flag) {1760if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1761c.iflags.AddFlag(f)1762}1763})1764return c.iflags1765}17661767// NonInheritedFlags returns all flags which were not inherited from parent commands.1768// This function does not modify the flags of the current command, it's purpose is to return the current state.1769func (c *Command) NonInheritedFlags() *flag.FlagSet {1770return c.LocalFlags()1771}17721773// PersistentFlags returns the persistent FlagSet specifically set in the current command.1774func (c *Command) PersistentFlags() *flag.FlagSet {1775if c.pflags == nil {1776c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)1777if c.flagErrorBuf == nil {1778c.flagErrorBuf = new(bytes.Buffer)1779}1780c.pflags.SetOutput(c.flagErrorBuf)1781}1782return c.pflags1783}17841785// ResetFlags deletes all flags from command.1786func (c *Command) ResetFlags() {1787c.flagErrorBuf = new(bytes.Buffer)1788c.flagErrorBuf.Reset()1789c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)1790c.flags.SetOutput(c.flagErrorBuf)1791c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)1792c.pflags.SetOutput(c.flagErrorBuf)17931794c.lflags = nil1795c.iflags = nil1796c.parentsPflags = nil1797}17981799// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1800func (c *Command) HasFlags() bool {1801return c.Flags().HasFlags()1802}18031804// HasPersistentFlags checks if the command contains persistent flags.1805func (c *Command) HasPersistentFlags() bool {1806return c.PersistentFlags().HasFlags()1807}18081809// HasLocalFlags checks if the command has flags specifically declared locally.1810func (c *Command) HasLocalFlags() bool {1811return c.LocalFlags().HasFlags()1812}18131814// HasInheritedFlags checks if the command has flags inherited from its parent command.1815func (c *Command) HasInheritedFlags() bool {1816return c.InheritedFlags().HasFlags()1817}18181819// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1820// structure) which are not hidden or deprecated.1821func (c *Command) HasAvailableFlags() bool {1822return c.Flags().HasAvailableFlags()1823}18241825// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1826func (c *Command) HasAvailablePersistentFlags() bool {1827return c.PersistentFlags().HasAvailableFlags()1828}18291830// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1831// or deprecated.1832func (c *Command) HasAvailableLocalFlags() bool {1833return c.LocalFlags().HasAvailableFlags()1834}18351836// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1837// not hidden or deprecated.1838func (c *Command) HasAvailableInheritedFlags() bool {1839return c.InheritedFlags().HasAvailableFlags()1840}18411842// Flag climbs up the command tree looking for matching flag.1843func (c *Command) Flag(name string) (flag *flag.Flag) {1844flag = c.Flags().Lookup(name)18451846if flag == nil {1847flag = c.persistentFlag(name)1848}18491850return1851}18521853// Recursively find matching persistent flag.1854func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1855if c.HasPersistentFlags() {1856flag = c.PersistentFlags().Lookup(name)1857}18581859if flag == nil {1860c.updateParentsPflags()1861flag = c.parentsPflags.Lookup(name)1862}1863return1864}18651866// ParseFlags parses persistent flag tree and local flags.1867func (c *Command) ParseFlags(args []string) error {1868if c.DisableFlagParsing {1869return nil1870}18711872if c.flagErrorBuf == nil {1873c.flagErrorBuf = new(bytes.Buffer)1874}1875beforeErrorBufLen := c.flagErrorBuf.Len()1876c.mergePersistentFlags()18771878// do it here after merging all flags and just before parse1879c.Flags().ParseErrorsAllowlist = flag.ParseErrorsAllowlist(c.FParseErrWhitelist)18801881err := c.Flags().Parse(args)1882// Print warnings if they occurred (e.g. deprecated flag messages).1883if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1884c.Print(c.flagErrorBuf.String())1885}18861887return err1888}18891890// Parent returns a commands parent command.1891func (c *Command) Parent() *Command {1892return c.parent1893}18941895// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1896// and adds missing persistent flags of all parents.1897func (c *Command) mergePersistentFlags() {1898c.updateParentsPflags()1899c.Flags().AddFlagSet(c.PersistentFlags())1900c.Flags().AddFlagSet(c.parentsPflags)1901}19021903// updateParentsPflags updates c.parentsPflags by adding1904// new persistent flags of all parents.1905// If c.parentsPflags == nil, it makes new.1906func (c *Command) updateParentsPflags() {1907if c.parentsPflags == nil {1908c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)1909c.parentsPflags.SetOutput(c.flagErrorBuf)1910c.parentsPflags.SortFlags = false1911}19121913if c.globNormFunc != nil {1914c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1915}19161917c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)19181919c.VisitParents(func(parent *Command) {1920c.parentsPflags.AddFlagSet(parent.PersistentFlags())1921})1922}19231924// commandNameMatches checks if two command names are equal1925// taking into account case sensitivity according to1926// EnableCaseInsensitive global configuration.1927func commandNameMatches(s string, t string) bool {1928if EnableCaseInsensitive {1929return strings.EqualFold(s, t)1930}19311932return s == t1933}19341935// tmplFunc holds a template and a function that will execute said template.1936type tmplFunc struct {1937tmpl string1938fn func(io.Writer, interface{}) error1939}19401941var defaultUsageTemplate = `Usage:{{if .Runnable}}1942{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}1943{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}19441945Aliases:1946{{.NameAndAliases}}{{end}}{{if .HasExample}}19471948Examples:1949{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}19501951Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}1952{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}19531954{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}1955{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}19561957Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}1958{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}19591960Flags:1961{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}19621963Global Flags:1964{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}19651966Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}1967{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}19681969Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}1970`19711972// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync.1973func defaultUsageFunc(w io.Writer, in interface{}) error {1974c := in.(*Command)1975fmt.Fprint(w, "Usage:")1976if c.Runnable() {1977fmt.Fprintf(w, "\n %s", c.UseLine())1978}1979if c.HasAvailableSubCommands() {1980fmt.Fprintf(w, "\n %s [command]", c.CommandPath())1981}1982if len(c.Aliases) > 0 {1983fmt.Fprintf(w, "\n\nAliases:\n")1984fmt.Fprintf(w, " %s", c.NameAndAliases())1985}1986if c.HasExample() {1987fmt.Fprintf(w, "\n\nExamples:\n")1988fmt.Fprintf(w, "%s", c.Example)1989}1990if c.HasAvailableSubCommands() {1991cmds := c.Commands()1992if len(c.Groups()) == 0 {1993fmt.Fprintf(w, "\n\nAvailable Commands:")1994for _, subcmd := range cmds {1995if subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName {1996fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)1997}1998}1999} else {2000for _, group := range c.Groups() {2001fmt.Fprintf(w, "\n\n%s", group.Title)2002for _, subcmd := range cmds {2003if subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {2004fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)2005}2006}2007}2008if !c.AllChildCommandsHaveGroup() {2009fmt.Fprintf(w, "\n\nAdditional Commands:")2010for _, subcmd := range cmds {2011if subcmd.GroupID == "" && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {2012fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)2013}2014}2015}2016}2017}2018if c.HasAvailableLocalFlags() {2019fmt.Fprintf(w, "\n\nFlags:\n")2020fmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages()))2021}2022if c.HasAvailableInheritedFlags() {2023fmt.Fprintf(w, "\n\nGlobal Flags:\n")2024fmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages()))2025}2026if c.HasHelpSubCommands() {2027fmt.Fprintf(w, "\n\nAdditional help topics:")2028for _, subcmd := range c.Commands() {2029if subcmd.IsAdditionalHelpTopicCommand() {2030fmt.Fprintf(w, "\n %s %s", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short)2031}2032}2033}2034if c.HasAvailableSubCommands() {2035fmt.Fprintf(w, "\n\nUse \"%s [command] --help\" for more information about a command.", c.CommandPath())2036}2037fmt.Fprintln(w)2038return nil2039}20402041var defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}20422043{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`20442045// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync.2046func defaultHelpFunc(w io.Writer, in interface{}) error {2047c := in.(*Command)2048usage := c.Long2049if usage == "" {2050usage = c.Short2051}2052usage = trimRightSpace(usage)2053if usage != "" {2054fmt.Fprintln(w, usage)2055fmt.Fprintln(w)2056}2057if c.Runnable() || c.HasSubCommands() {2058fmt.Fprint(w, c.UsageString())2059}2060return nil2061}20622063var defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}2064`20652066// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync.2067func defaultVersionFunc(w io.Writer, in interface{}) error {2068c := in.(*Command)2069_, err := fmt.Fprintf(w, "%s version %s\n", c.DisplayName(), c.Version)2070return err2071}207220732074