command.go
This file
Path
command.go
1,710 lines · 48.2 KiB · Go
Last changed by
Expose ValidateRequiredFlags and ValidateFlagGroups (#1760)Skeet WUbefore adoptionfce8d8a
History of this fileTake it
The walk stopped after 200 commits: lines older than 090d94f point at it.
add missing license headers (#1809)Unai Martinez-Corralbefore adoption6d978a9
line 1why, one step back1// Copyright 2013-2022 The Cobra AuthorsMove projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 2–5why, one step back2//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 atadd missing license headers (#1809)Unai Martinez-Corralbefore adoption6d978a9
lines 6–7why, one step back6//7// http://www.apache.org/licenses/LICENSE-2.0Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 8–21why, one step back8//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"use errors.Is() to check for errors (#1730)Paul Holzingerbefore adoptionb9ca594
line 22why, one step back22 "errors"Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 23–41why, one step back23 "fmt"24 "io"25 "os"26 "path/filepath"27 "sort"28 "strings"2930 flag "github.com/spf13/pflag"31)3233// FParseErrWhitelist configures Flag parse errors to be ignored34type FParseErrWhitelist flag.ParseErrorsWhitelist3536// Command is just that, a command for your application.37// E.g. 'go run ...' - 'run' is the command. Cobra requires38// you to define the usage and description as part of your command39// definition to ensure usability.40type Command struct {41 // Use is the one-line usage message.Add documentation for Use (#1188)Michael Murébefore adoption8cfa4b4
lines 42–49why, one step back42 // Recommended syntax is as follow:43 // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.44 // ... indicates that you can specify multiple values for the previous argument.45 // | indicates mutually exclusive information. You can use the argument to the left of the separator or the46 // argument to the right of the separator. You cannot use both arguments in a single use of the command.47 // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are48 // optional, they are enclosed in brackets ([ ]).49 // Example: add [-F file | -D dir]... [-f format] profileMove projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 50–67why, one step back50 Use string5152 // Aliases is an array of aliases that can be used instead of the first word in Use.53 Aliases []string5455 // SuggestFor is an array of command names for which this command will be suggested -56 // similar to aliases but only suggests.57 SuggestFor []string5859 // Short is the short description shown in the 'help' output.60 Short string6162 // Long is the long message shown in the 'help <this-command>' output.63 Long string6465 // Example is examples of how to use the command.66 Example string67Bash completion V2 with completion descriptions (#1146)Marc Khouzambefore adoptionb361960
line 68why, one step back68 // ValidArgs is list of all valid non-flag arguments that are accepted in shell completionsMove projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
line 69why, one step back69 ValidArgs []stringBash completion V2 with completion descriptions (#1146)Marc Khouzambefore adoptionb361960
line 70why, one step back70 // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 71–78why, one step back71 // It is a dynamic version of using ValidArgs.72 // Only one of ValidArgs and ValidArgsFunction can be used for a command.73 ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)7475 // Expected arguments76 Args PositionalArgs7778 // ArgAliases is List of aliases for ValidArgs.Bash completion V2 with completion descriptions (#1146)Marc Khouzambefore adoptionb361960
line 79why, one step back79 // These are not suggested to the user in the shell completion,Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 80–82why, one step back80 // but accepted if entered manually.81 ArgAliases []string82Bash completion V2 with completion descriptions (#1146)Marc Khouzambefore adoptionb361960
lines 83–84why, one step back83 // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.84 // For portability with other shells, it is recommended to instead use ValidArgsFunctionMove projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 85–169why, one step back85 BashCompletionFunction string8687 // Deprecated defines, if this command is deprecated and should print this string when used.88 Deprecated string8990 // Annotations are key/value pairs that can be used by applications to identify or91 // group commands.92 Annotations map[string]string9394 // Version defines the version for this command. If this value is non-empty and the command does not95 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,96 // will print content of the "Version" variable. A shorthand "v" flag will also be added if the97 // command does not define one.98 Version string99100 // The *Run functions are executed in the following order:101 // * PersistentPreRun()102 // * PreRun()103 // * Run()104 // * PostRun()105 // * PersistentPostRun()106 // All functions get the same args, the arguments after the command name.107 //108 // PersistentPreRun: children of this command will inherit and execute.109 PersistentPreRun func(cmd *Command, args []string)110 // PersistentPreRunE: PersistentPreRun but returns an error.111 PersistentPreRunE func(cmd *Command, args []string) error112 // PreRun: children of this command will not inherit.113 PreRun func(cmd *Command, args []string)114 // PreRunE: PreRun but returns an error.115 PreRunE func(cmd *Command, args []string) error116 // Run: Typically the actual work function. Most commands will only implement this.117 Run func(cmd *Command, args []string)118 // RunE: Run but returns an error.119 RunE func(cmd *Command, args []string) error120 // PostRun: run after the Run command.121 PostRun func(cmd *Command, args []string)122 // PostRunE: PostRun but returns an error.123 PostRunE func(cmd *Command, args []string) error124 // PersistentPostRun: children of this command will inherit and execute after PostRun.125 PersistentPostRun func(cmd *Command, args []string)126 // PersistentPostRunE: PersistentPostRun but returns an error.127 PersistentPostRunE func(cmd *Command, args []string) error128129 // args is actual args parsed from flags.130 args []string131 // flagErrorBuf contains all error messages from pflag.132 flagErrorBuf *bytes.Buffer133 // flags is full set of flags.134 flags *flag.FlagSet135 // pflags contains persistent flags.136 pflags *flag.FlagSet137 // lflags contains local flags.138 lflags *flag.FlagSet139 // iflags contains inherited flags.140 iflags *flag.FlagSet141 // parentsPflags is all persistent flags of cmd's parents.142 parentsPflags *flag.FlagSet143 // globNormFunc is the global normalization function144 // that we can use on every pflag set and children commands145 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName146147 // usageFunc is usage func defined by user.148 usageFunc func(*Command) error149 // usageTemplate is usage template defined by user.150 usageTemplate string151 // flagErrorFunc is func defined by user and it's called when the parsing of152 // flags returns an error.153 flagErrorFunc func(*Command, error) error154 // helpTemplate is help template defined by user.155 helpTemplate string156 // helpFunc is help func defined by user.157 helpFunc func(*Command, []string)158 // helpCommand is command with usage 'help'. If it's not defined by user,159 // cobra uses default help command.160 helpCommand *Command161 // versionTemplate is the version template defined by user.162 versionTemplate string163164 // inReader is a reader defined by the user that replaces stdin165 inReader io.Reader166 // outWriter is a writer defined by the user that replaces stdout167 outWriter io.Writer168 // errWriter is a writer defined by the user that replaces stderr169 errWriter io.WriterUse golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755
line 170why, one step back170Fix Command.Context comment (#1639)Paul Meyerbefore adoption3a1795b
line 171why, one step back171 // FParseErrWhitelist flag parse errors to be ignoredUse golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755
lines 172–173why, one step back172 FParseErrWhitelist FParseErrWhitelist173Create 'completion' command automatically (#1192)Marc Khouzambefore adoptionb312f0a
lines 174–176why, one step back174 // CompletionOptions is a set of options to control the handling of shell completion175 CompletionOptions CompletionOptions176Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755
lines 177–226why, one step back177 // commandsAreSorted defines, if command slice are sorted or not.178 commandsAreSorted bool179 // commandCalledAs is the name or alias value used to call this command.180 commandCalledAs struct {181 name string182 called bool183 }184185 ctx context.Context186187 // commands is the list of commands supported by this program.188 commands []*Command189 // parent is a parent command for this command.190 parent *Command191 // Max lengths of commands' string lengths for use in padding.192 commandsMaxUseLen int193 commandsMaxCommandPathLen int194 commandsMaxNameLen int195196 // TraverseChildren parses flags on all parents before executing child command.197 TraverseChildren bool198199 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.200 Hidden bool201202 // SilenceErrors is an option to quiet errors down stream.203 SilenceErrors bool204205 // SilenceUsage is an option to silence usage when an error occurs.206 SilenceUsage bool207208 // DisableFlagParsing disables the flag parsing.209 // If this is true all flags will be passed to the command as arguments.210 DisableFlagParsing bool211212 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")213 // will be printed by generating docs for this command.214 DisableAutoGenTag bool215216 // DisableFlagsInUseLine will disable the addition of [flags] to the usage217 // line of a command when printing help or generating docs218 DisableFlagsInUseLine bool219220 // DisableSuggestions disables the suggestions based on Levenshtein distance221 // that go along with 'unknown command' messages.222 DisableSuggestions bool223224 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.225 // Must be > 0.226 SuggestionsMinimumDistance intMove projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 227–228why, one step back227}228Fix Command.Context comment (#1639)Paul Meyerbefore adoption3a1795b
lines 229–235why, one step back229// Context returns underlying command context. If command was executed230// with ExecuteContext or the context was set with SetContext, the231// previously set context will be returned. Otherwise, nil is returned.232//233// Notice that a call to Execute and ExecuteC will replace a nil context of234// a command with a context.Background, so a background context will be235// returned by Context after one of these functions has been called.Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 236–239why, one step back236func (c *Command) Context() context.Context {237 return c.ctx238}239Clarify SetContext documentation (#1748)Paul Meyerbefore adoption2a7647f
lines 240–241why, one step back240// SetContext sets context for the command. This context will be overwritten by241// Command.ExecuteContext or Command.ExecuteContextC.Add Command.SetContext (#1551)Joshua Carpeggianibefore adoptionf848943
lines 242–245why, one step back242func (c *Command) SetContext(ctx context.Context) {243 c.ctx = ctx244}245Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 246–388why, one step back246// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden247// particularly useful when testing.248func (c *Command) SetArgs(a []string) {249 c.args = a250}251252// SetOutput sets the destination for usage and error messages.253// If output is nil, os.Stderr is used.254// Deprecated: Use SetOut and/or SetErr instead255func (c *Command) SetOutput(output io.Writer) {256 c.outWriter = output257 c.errWriter = output258}259260// SetOut sets the destination for usage messages.261// If newOut is nil, os.Stdout is used.262func (c *Command) SetOut(newOut io.Writer) {263 c.outWriter = newOut264}265266// SetErr sets the destination for error messages.267// If newErr is nil, os.Stderr is used.268func (c *Command) SetErr(newErr io.Writer) {269 c.errWriter = newErr270}271272// SetIn sets the source for input data273// If newIn is nil, os.Stdin is used.274func (c *Command) SetIn(newIn io.Reader) {275 c.inReader = newIn276}277278// SetUsageFunc sets usage function. Usage can be defined by application.279func (c *Command) SetUsageFunc(f func(*Command) error) {280 c.usageFunc = f281}282283// SetUsageTemplate sets usage template. Can be defined by Application.284func (c *Command) SetUsageTemplate(s string) {285 c.usageTemplate = s286}287288// SetFlagErrorFunc sets a function to generate an error when flag parsing289// fails.290func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {291 c.flagErrorFunc = f292}293294// SetHelpFunc sets help function. Can be defined by Application.295func (c *Command) SetHelpFunc(f func(*Command, []string)) {296 c.helpFunc = f297}298299// SetHelpCommand sets help command.300func (c *Command) SetHelpCommand(cmd *Command) {301 c.helpCommand = cmd302}303304// SetHelpTemplate sets help template to be used. Application can use it to set custom template.305func (c *Command) SetHelpTemplate(s string) {306 c.helpTemplate = s307}308309// SetVersionTemplate sets version template to be used. Application can use it to set custom template.310func (c *Command) SetVersionTemplate(s string) {311 c.versionTemplate = s312}313314// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.315// The user should not have a cyclic dependency on commands.316func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {317 c.Flags().SetNormalizeFunc(n)318 c.PersistentFlags().SetNormalizeFunc(n)319 c.globNormFunc = n320321 for _, command := range c.commands {322 command.SetGlobalNormalizationFunc(n)323 }324}325326// OutOrStdout returns output to stdout.327func (c *Command) OutOrStdout() io.Writer {328 return c.getOut(os.Stdout)329}330331// OutOrStderr returns output to stderr332func (c *Command) OutOrStderr() io.Writer {333 return c.getOut(os.Stderr)334}335336// ErrOrStderr returns output to stderr337func (c *Command) ErrOrStderr() io.Writer {338 return c.getErr(os.Stderr)339}340341// InOrStdin returns input to stdin342func (c *Command) InOrStdin() io.Reader {343 return c.getIn(os.Stdin)344}345346func (c *Command) getOut(def io.Writer) io.Writer {347 if c.outWriter != nil {348 return c.outWriter349 }350 if c.HasParent() {351 return c.parent.getOut(def)352 }353 return def354}355356func (c *Command) getErr(def io.Writer) io.Writer {357 if c.errWriter != nil {358 return c.errWriter359 }360 if c.HasParent() {361 return c.parent.getErr(def)362 }363 return def364}365366func (c *Command) getIn(def io.Reader) io.Reader {367 if c.inReader != nil {368 return c.inReader369 }370 if c.HasParent() {371 return c.parent.getIn(def)372 }373 return def374}375376// UsageFunc returns either the function set by SetUsageFunc for this command377// or a parent, or it returns a default usage function.378func (c *Command) UsageFunc() (f func(*Command) error) {379 if c.usageFunc != nil {380 return c.usageFunc381 }382 if c.HasParent() {383 return c.Parent().UsageFunc()384 }385 return func(c *Command) error {386 c.mergePersistentFlags()387 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)388 if err != nil {Fix stderr printing functions (#894)Alessio Tregliabefore adoption40d34bc
line 389why, one step back389 c.PrintErrln(err)Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 390–416why, one step back390 }391 return err392 }393}394395// Usage puts out the usage for the command.396// Used when a user provides invalid input.397// Can be defined by user by overriding UsageFunc.398func (c *Command) Usage() error {399 return c.UsageFunc()(c)400}401402// HelpFunc returns either the function set by SetHelpFunc for this command403// or a parent, or it returns a function with default help behavior.404func (c *Command) HelpFunc() func(*Command, []string) {405 if c.helpFunc != nil {406 return c.helpFunc407 }408 if c.HasParent() {409 return c.Parent().HelpFunc()410 }411 return func(c *Command, a []string) {412 c.mergePersistentFlags()413 // The help should be sent to stdout414 // See https://github.com/spf13/cobra/issues/1002415 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)416 if err != nil {Fix stderr printing functions (#894)Alessio Tregliabefore adoption40d34bc
line 417why, one step back417 c.PrintErrln(err)Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 418–439why, one step back418 }419 }420}421422// Help puts out the help for the command.423// Used when a user calls help [command].424// Can be defined by user by overriding HelpFunc.425func (c *Command) Help() error {426 c.HelpFunc()(c, []string{})427 return nil428}429430// UsageString returns usage string.431func (c *Command) UsageString() string {432 // Storing normal writers433 tmpOutput := c.outWriter434 tmpErr := c.errWriter435436 bb := new(bytes.Buffer)437 c.outWriter = bb438 c.errWriter = bb439Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755
line 440why, one step back440 CheckErr(c.Usage())Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 441–679why, one step back441442 // Setting things back to normal443 c.outWriter = tmpOutput444 c.errWriter = tmpErr445446 return bb.String()447}448449// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this450// command or a parent, or it returns a function which returns the original451// error.452func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {453 if c.flagErrorFunc != nil {454 return c.flagErrorFunc455 }456457 if c.HasParent() {458 return c.parent.FlagErrorFunc()459 }460 return func(c *Command, err error) error {461 return err462 }463}464465var minUsagePadding = 25466467// UsagePadding return padding for the usage.468func (c *Command) UsagePadding() int {469 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {470 return minUsagePadding471 }472 return c.parent.commandsMaxUseLen473}474475var minCommandPathPadding = 11476477// CommandPathPadding return padding for the command path.478func (c *Command) CommandPathPadding() int {479 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {480 return minCommandPathPadding481 }482 return c.parent.commandsMaxCommandPathLen483}484485var minNamePadding = 11486487// NamePadding returns padding for the name.488func (c *Command) NamePadding() int {489 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {490 return minNamePadding491 }492 return c.parent.commandsMaxNameLen493}494495// UsageTemplate returns usage template for the command.496func (c *Command) UsageTemplate() string {497 if c.usageTemplate != "" {498 return c.usageTemplate499 }500501 if c.HasParent() {502 return c.parent.UsageTemplate()503 }504 return `Usage:{{if .Runnable}}505 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}506 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}507508Aliases:509 {{.NameAndAliases}}{{end}}{{if .HasExample}}510511Examples:512{{.Example}}{{end}}{{if .HasAvailableSubCommands}}513514Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}515 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}516517Flags:518{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}519520Global Flags:521{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}522523Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}524 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}525526Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}527`528}529530// HelpTemplate return help template for the command.531func (c *Command) HelpTemplate() string {532 if c.helpTemplate != "" {533 return c.helpTemplate534 }535536 if c.HasParent() {537 return c.parent.HelpTemplate()538 }539 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}540541{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`542}543544// VersionTemplate return version template for the command.545func (c *Command) VersionTemplate() string {546 if c.versionTemplate != "" {547 return c.versionTemplate548 }549550 if c.HasParent() {551 return c.parent.VersionTemplate()552 }553 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}554`555}556557func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {558 flag := fs.Lookup(name)559 if flag == nil {560 return false561 }562 return flag.NoOptDefVal != ""563}564565func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {566 if len(name) == 0 {567 return false568 }569570 flag := fs.ShorthandLookup(name[:1])571 if flag == nil {572 return false573 }574 return flag.NoOptDefVal != ""575}576577func stripFlags(args []string, c *Command) []string {578 if len(args) == 0 {579 return args580 }581 c.mergePersistentFlags()582583 commands := []string{}584 flags := c.Flags()585586Loop:587 for len(args) > 0 {588 s := args[0]589 args = args[1:]590 switch {591 case s == "--":592 // "--" terminates the flags593 break Loop594 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):595 // If '--flag arg' then596 // delete arg from args.597 fallthrough // (do the same as below)598 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):599 // If '-f arg' then600 // delete 'arg' from args or break the loop if len(args) <= 1.601 if len(args) <= 1 {602 break Loop603 } else {604 args = args[1:]605 continue606 }607 case s != "" && !strings.HasPrefix(s, "-"):608 commands = append(commands, s)609 }610 }611612 return commands613}614615// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like616// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).617func argsMinusFirstX(args []string, x string) []string {618 for i, y := range args {619 if x == y {620 ret := []string{}621 ret = append(ret, args[:i]...)622 ret = append(ret, args[i+1:]...)623 return ret624 }625 }626 return args627}628629func isFlagArg(arg string) bool {630 return ((len(arg) >= 3 && arg[1] == '-') ||631 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))632}633634// Find the target command given the args and command tree635// Meant to be run on the highest node. Only searches down.636func (c *Command) Find(args []string) (*Command, []string, error) {637 var innerfind func(*Command, []string) (*Command, []string)638639 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {640 argsWOflags := stripFlags(innerArgs, c)641 if len(argsWOflags) == 0 {642 return c, innerArgs643 }644 nextSubCmd := argsWOflags[0]645646 cmd := c.findNext(nextSubCmd)647 if cmd != nil {648 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))649 }650 return c, innerArgs651 }652653 commandFound, a := innerfind(c, args)654 if commandFound.Args == nil {655 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))656 }657 return commandFound, a, nil658}659660func (c *Command) findSuggestions(arg string) string {661 if c.DisableSuggestions {662 return ""663 }664 if c.SuggestionsMinimumDistance <= 0 {665 c.SuggestionsMinimumDistance = 2666 }667 suggestionsString := ""668 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {669 suggestionsString += "\n\nDid you mean this?\n"670 for _, s := range suggestions {671 suggestionsString += fmt.Sprintf("\t%v\n", s)672 }673 }674 return suggestionsString675}676677func (c *Command) findNext(next string) *Command {678 matches := make([]*Command, 0)679 for _, cmd := range c.commands {Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184
line 680why, one step back680 if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 681–864why, one step back681 cmd.commandCalledAs.name = next682 return cmd683 }684 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {685 matches = append(matches, cmd)686 }687 }688689 if len(matches) == 1 {690 return matches[0]691 }692693 return nil694}695696// Traverse the command tree to find the command, and parse args for697// each parent.698func (c *Command) Traverse(args []string) (*Command, []string, error) {699 flags := []string{}700 inFlag := false701702 for i, arg := range args {703 switch {704 // A long flag with a space separated value705 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):706 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'707 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())708 flags = append(flags, arg)709 continue710 // A short flag with a space separated value711 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):712 inFlag = true713 flags = append(flags, arg)714 continue715 // The value for a flag716 case inFlag:717 inFlag = false718 flags = append(flags, arg)719 continue720 // A flag without a value, or with an `=` separated value721 case isFlagArg(arg):722 flags = append(flags, arg)723 continue724 }725726 cmd := c.findNext(arg)727 if cmd == nil {728 return c, args, nil729 }730731 if err := c.ParseFlags(flags); err != nil {732 return nil, args, err733 }734 return cmd.Traverse(args[i+1:])735 }736 return c, args, nil737}738739// SuggestionsFor provides suggestions for the typedName.740func (c *Command) SuggestionsFor(typedName string) []string {741 suggestions := []string{}742 for _, cmd := range c.commands {743 if cmd.IsAvailableCommand() {744 levenshteinDistance := ld(typedName, cmd.Name(), true)745 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance746 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))747 if suggestByLevenshtein || suggestByPrefix {748 suggestions = append(suggestions, cmd.Name())749 }750 for _, explicitSuggestion := range cmd.SuggestFor {751 if strings.EqualFold(typedName, explicitSuggestion) {752 suggestions = append(suggestions, cmd.Name())753 }754 }755 }756 }757 return suggestions758}759760// VisitParents visits all parents of the command and invokes fn on each parent.761func (c *Command) VisitParents(fn func(*Command)) {762 if c.HasParent() {763 fn(c.Parent())764 c.Parent().VisitParents(fn)765 }766}767768// Root finds root command.769func (c *Command) Root() *Command {770 if c.HasParent() {771 return c.Parent().Root()772 }773 return c774}775776// ArgsLenAtDash will return the length of c.Flags().Args at the moment777// when a -- was found during args parsing.778func (c *Command) ArgsLenAtDash() int {779 return c.Flags().ArgsLenAtDash()780}781782func (c *Command) execute(a []string) (err error) {783 if c == nil {784 return fmt.Errorf("Called Execute() on a nil Command")785 }786787 if len(c.Deprecated) > 0 {788 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)789 }790791 // initialize help and version flag at the last point possible to allow for user792 // overriding793 c.InitDefaultHelpFlag()794 c.InitDefaultVersionFlag()795796 err = c.ParseFlags(a)797 if err != nil {798 return c.FlagErrorFunc()(c, err)799 }800801 // If help is called, regardless of other flags, return we want help.802 // Also say we need help if the command isn't runnable.803 helpVal, err := c.Flags().GetBool("help")804 if err != nil {805 // should be impossible to get here as we always declare a help806 // flag in InitDefaultHelpFlag()807 c.Println("\"help\" flag declared as non-bool. Please correct your code")808 return err809 }810811 if helpVal {812 return flag.ErrHelp813 }814815 // for back-compat, only add version flag behavior if version is defined816 if c.Version != "" {817 versionVal, err := c.Flags().GetBool("version")818 if err != nil {819 c.Println("\"version\" flag declared as non-bool. Please correct your code")820 return err821 }822 if versionVal {823 err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)824 if err != nil {825 c.Println(err)826 }827 return err828 }829 }830831 if !c.Runnable() {832 return flag.ErrHelp833 }834835 c.preRun()836837 argWoFlags := c.Flags().Args()838 if c.DisableFlagParsing {839 argWoFlags = a840 }841842 if err := c.ValidateArgs(argWoFlags); err != nil {843 return err844 }845846 for p := c; p != nil; p = p.Parent() {847 if p.PersistentPreRunE != nil {848 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {849 return err850 }851 break852 } else if p.PersistentPreRun != nil {853 p.PersistentPreRun(c, argWoFlags)854 break855 }856 }857 if c.PreRunE != nil {858 if err := c.PreRunE(c, argWoFlags); err != nil {859 return err860 }861 } else if c.PreRun != nil {862 c.PreRun(c, argWoFlags)863 }864Expose ValidateRequiredFlags and ValidateFlagGroups (#1760)Skeet WUbefore adoptionfce8d8a
line 865why, one step back865 if err := c.ValidateRequiredFlags(); err != nil {Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 866–867why, one step back866 return err867 }Expose ValidateRequiredFlags and ValidateFlagGroups (#1760)Skeet WUbefore adoptionfce8d8a
line 868why, one step back868 if err := c.ValidateFlagGroups(); err != nil {Add ability to mark flags as required or exclusive as a group (#1654)John Schnakebefore adoption68b6b24
lines 869–871why, one step back869 return err870 }871Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 872–907why, one step back872 if c.RunE != nil {873 if err := c.RunE(c, argWoFlags); err != nil {874 return err875 }876 } else {877 c.Run(c, argWoFlags)878 }879 if c.PostRunE != nil {880 if err := c.PostRunE(c, argWoFlags); err != nil {881 return err882 }883 } else if c.PostRun != nil {884 c.PostRun(c, argWoFlags)885 }886 for p := c; p != nil; p = p.Parent() {887 if p.PersistentPostRunE != nil {888 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {889 return err890 }891 break892 } else if p.PersistentPostRun != nil {893 p.PersistentPostRun(c, argWoFlags)894 break895 }896 }897898 return nil899}900901func (c *Command) preRun() {902 for _, x := range initializers {903 x()904 }905}906907// ExecuteContext is the same as Execute(), but sets the ctx on the command.Pass context to completion (#1265)Lukas Malkmusbefore adoption6d00909
lines 908–909why, one step back908// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs909// functions.Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 910–920why, one step back910func (c *Command) ExecuteContext(ctx context.Context) error {911 c.ctx = ctx912 return c.Execute()913}914915// Execute uses the args (os.Args[1:] by default)916// and run through the command tree finding appropriate matches917// for commands and then corresponding flags.918func (c *Command) Execute() error {919 _, err := c.ExecuteC()920 return errPass context to completion (#1265)Lukas Malkmusbefore adoption6d00909
lines 921–928why, one step back921}922923// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.924// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs925// functions.926func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {927 c.ctx = ctx928 return c.ExecuteC()Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 929–946why, one step back929}930931// ExecuteC executes the command.932func (c *Command) ExecuteC() (cmd *Command, err error) {933 if c.ctx == nil {934 c.ctx = context.Background()935 }936937 // Regardless of what command execute is called on, run on Root only938 if c.HasParent() {939 return c.Root().ExecuteC()940 }941942 // windows hook943 if preExecHookFn != nil {944 preExecHookFn(c)945 }946Create 'completion' command automatically (#1192)Marc Khouzambefore adoptionb312f0a
line 947why, one step back947 // initialize help at the last point to allow for user overridingMove projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
line 948why, one step back948 c.InitDefaultHelpCmd()Create 'completion' command automatically (#1192)Marc Khouzambefore adoptionb312f0a
lines 949–950why, one step back949 // initialize completion at the last point to allow for user overriding950 c.initDefaultCompletionCmd()Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 951–958why, one step back951952 args := c.args953954 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155955 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {956 args = os.Args[1:]957 }958Bash completion V2 with completion descriptions (#1146)Marc Khouzambefore adoptionb361960
line 959why, one step back959 // initialize the hidden command to be used for shell completionMove projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 960–973why, one step back960 c.initCompleteCmd(args)961962 var flags []string963 if c.TraverseChildren {964 cmd, flags, err = c.Traverse(args)965 } else {966 cmd, flags, err = c.Find(args)967 }968 if err != nil {969 // If found parse to a subcommand and then failed, talk about the subcommand970 if cmd != nil {971 c = cmd972 }973 if !c.SilenceErrors {Fix stderr printing functions (#894)Alessio Tregliabefore adoption40d34bc
lines 974–975why, one step back974 c.PrintErrln("Error:", err.Error())975 c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 976–994why, one step back976 }977 return c, err978 }979980 cmd.commandCalledAs.called = true981 if cmd.commandCalledAs.name == "" {982 cmd.commandCalledAs.name = cmd.Name()983 }984985 // We have to pass global context to children command986 // if context is present on the parent command.987 if cmd.ctx == nil {988 cmd.ctx = c.ctx989 }990991 err = cmd.execute(flags)992 if err != nil {993 // Always show help if requested, even if SilenceErrors is in994 // effectuse errors.Is() to check for errors (#1730)Paul Holzingerbefore adoptionb9ca594
line 995why, one step back995 if errors.Is(err, flag.ErrHelp) {Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 996–999why, one step back996 cmd.HelpFunc()(cmd, args)997 return cmd, nil998 }999fix typos (#1274)namusyakabefore adoption7df62f7
line 1000why, one step back1000 // If root command has SilenceErrors flagged,Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1001–1002why, one step back1001 // all subcommands should respect it1002 if !cmd.SilenceErrors && !c.SilenceErrors {Fix stderr printing functions (#894)Alessio Tregliabefore adoption40d34bc
line 1003why, one step back1003 c.PrintErrln("Error:", err.Error())Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1004–1005why, one step back1004 }1005fix typos (#1274)namusyakabefore adoption7df62f7
line 1006why, one step back1006 // If root command has SilenceUsage flagged,Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1007–1016why, one step back1007 // all subcommands should respect it1008 if !cmd.SilenceUsage && !c.SilenceUsage {1009 c.Println(cmd.UsageString())1010 }1011 }1012 return cmd, err1013}10141015func (c *Command) ValidateArgs(args []string) error {1016 if c.Args == nil {undefined or nil Args default to ArbitraryArgs (#1612)Unai Martinez-Corralbefore adoptionea94a3d
line 1017why, one step back1017 return ArbitraryArgs(c, args)Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1018–1021why, one step back1018 }1019 return c.Args(c, args)1020}1021Expose ValidateRequiredFlags and ValidateFlagGroups (#1760)Skeet WUbefore adoptionfce8d8a
lines 1022–1023why, one step back1022// ValidateRequiredFlags validates all required flags are present and returns an error otherwise1023func (c *Command) ValidateRequiredFlags() error {Ignore required flags when DisableFlagParsing (#1095)Marc Khouzambefore adoption5155946
lines 1024–1027why, one step back1024 if c.DisableFlagParsing {1025 return nil1026 }1027Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1028–1100why, one step back1028 flags := c.Flags()1029 missingFlagNames := []string{}1030 flags.VisitAll(func(pflag *flag.Flag) {1031 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]1032 if !found {1033 return1034 }1035 if (requiredAnnotation[0] == "true") && !pflag.Changed {1036 missingFlagNames = append(missingFlagNames, pflag.Name)1037 }1038 })10391040 if len(missingFlagNames) > 0 {1041 return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))1042 }1043 return nil1044}10451046// InitDefaultHelpFlag adds default help flag to c.1047// It is called automatically by executing the c or by calling help and usage.1048// If c already has help flag, it will do nothing.1049func (c *Command) InitDefaultHelpFlag() {1050 c.mergePersistentFlags()1051 if c.Flags().Lookup("help") == nil {1052 usage := "help for "1053 if c.Name() == "" {1054 usage += "this command"1055 } else {1056 usage += c.Name()1057 }1058 c.Flags().BoolP("help", "h", false, usage)1059 }1060}10611062// InitDefaultVersionFlag adds default version flag to c.1063// It is called automatically by executing the c.1064// If c already has a version flag, it will do nothing.1065// If c.Version is empty, it will do nothing.1066func (c *Command) InitDefaultVersionFlag() {1067 if c.Version == "" {1068 return1069 }10701071 c.mergePersistentFlags()1072 if c.Flags().Lookup("version") == nil {1073 usage := "version for "1074 if c.Name() == "" {1075 usage += "this command"1076 } else {1077 usage += c.Name()1078 }1079 if c.Flags().ShorthandLookup("v") == nil {1080 c.Flags().BoolP("version", "v", false, usage)1081 } else {1082 c.Flags().Bool("version", false, usage)1083 }1084 }1085}10861087// InitDefaultHelpCmd adds default help command to c.1088// It is called automatically by executing the c or by calling help and usage.1089// If c already has help command or c has no subcommands, it will do nothing.1090func (c *Command) InitDefaultHelpCmd() {1091 if !c.HasSubCommands() {1092 return1093 }10941095 if c.helpCommand == nil {1096 c.helpCommand = &Command{1097 Use: "help [command]",1098 Short: "Help about any command",1099 Long: `Help provides help for any command in the application.1100Simply type ` + c.Name() + ` help [path to command] for full details.`,Add completion for help command (#1136)Marc Khouzambefore adoption0431872
lines 1101–1119why, one step back1101 ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1102 var completions []string1103 cmd, _, e := c.Root().Find(args)1104 if e != nil {1105 return nil, ShellCompDirectiveNoFileComp1106 }1107 if cmd == nil {1108 // Root help command.1109 cmd = c.Root()1110 }1111 for _, subCmd := range cmd.Commands() {1112 if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {1113 if strings.HasPrefix(subCmd.Name(), toComplete) {1114 completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))1115 }1116 }1117 }1118 return completions, ShellCompDirectiveNoFileComp1119 },Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1120–1123why, one step back1120 Run: func(c *Command, args []string) {1121 cmd, _, e := c.Root().Find(args)1122 if cmd == nil || e != nil {1123 c.Printf("Unknown help topic %#q\n", args)Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755
line 1124why, one step back1124 CheckErr(c.Root().Usage())Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1125–1126why, one step back1125 } else {1126 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shownUse golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755
line 1127why, one step back1127 CheckErr(cmd.Help())Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1128–1245why, one step back1128 }1129 },1130 }1131 }1132 c.RemoveCommand(c.helpCommand)1133 c.AddCommand(c.helpCommand)1134}11351136// ResetCommands delete parent, subcommand and help command from c.1137func (c *Command) ResetCommands() {1138 c.parent = nil1139 c.commands = nil1140 c.helpCommand = nil1141 c.parentsPflags = nil1142}11431144// Sorts commands by their names.1145type commandSorterByName []*Command11461147func (c commandSorterByName) Len() int { return len(c) }1148func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }1149func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }11501151// Commands returns a sorted slice of child commands.1152func (c *Command) Commands() []*Command {1153 // do not sort commands if it already sorted or sorting was disabled1154 if EnableCommandSorting && !c.commandsAreSorted {1155 sort.Sort(commandSorterByName(c.commands))1156 c.commandsAreSorted = true1157 }1158 return c.commands1159}11601161// AddCommand adds one or more commands to this parent command.1162func (c *Command) AddCommand(cmds ...*Command) {1163 for i, x := range cmds {1164 if cmds[i] == c {1165 panic("Command can't be a child of itself")1166 }1167 cmds[i].parent = c1168 // update max lengths1169 usageLen := len(x.Use)1170 if usageLen > c.commandsMaxUseLen {1171 c.commandsMaxUseLen = usageLen1172 }1173 commandPathLen := len(x.CommandPath())1174 if commandPathLen > c.commandsMaxCommandPathLen {1175 c.commandsMaxCommandPathLen = commandPathLen1176 }1177 nameLen := len(x.Name())1178 if nameLen > c.commandsMaxNameLen {1179 c.commandsMaxNameLen = nameLen1180 }1181 // If global normalization function exists, update all children1182 if c.globNormFunc != nil {1183 x.SetGlobalNormalizationFunc(c.globNormFunc)1184 }1185 c.commands = append(c.commands, x)1186 c.commandsAreSorted = false1187 }1188}11891190// RemoveCommand removes one or more commands from a parent command.1191func (c *Command) RemoveCommand(cmds ...*Command) {1192 commands := []*Command{}1193main:1194 for _, command := range c.commands {1195 for _, cmd := range cmds {1196 if command == cmd {1197 command.parent = nil1198 continue main1199 }1200 }1201 commands = append(commands, command)1202 }1203 c.commands = commands1204 // recompute all lengths1205 c.commandsMaxUseLen = 01206 c.commandsMaxCommandPathLen = 01207 c.commandsMaxNameLen = 01208 for _, command := range c.commands {1209 usageLen := len(command.Use)1210 if usageLen > c.commandsMaxUseLen {1211 c.commandsMaxUseLen = usageLen1212 }1213 commandPathLen := len(command.CommandPath())1214 if commandPathLen > c.commandsMaxCommandPathLen {1215 c.commandsMaxCommandPathLen = commandPathLen1216 }1217 nameLen := len(command.Name())1218 if nameLen > c.commandsMaxNameLen {1219 c.commandsMaxNameLen = nameLen1220 }1221 }1222}12231224// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1225func (c *Command) Print(i ...interface{}) {1226 fmt.Fprint(c.OutOrStderr(), i...)1227}12281229// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1230func (c *Command) Println(i ...interface{}) {1231 c.Print(fmt.Sprintln(i...))1232}12331234// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1235func (c *Command) Printf(format string, i ...interface{}) {1236 c.Print(fmt.Sprintf(format, i...))1237}12381239// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.1240func (c *Command) PrintErr(i ...interface{}) {1241 fmt.Fprint(c.ErrOrStderr(), i...)1242}12431244// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.1245func (c *Command) PrintErrln(i ...interface{}) {Fix stderr printing functions (#894)Alessio Tregliabefore adoption40d34bc
line 1246why, one step back1246 c.PrintErr(fmt.Sprintln(i...))Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1247–1250why, one step back1247}12481249// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.1250func (c *Command) PrintErrf(format string, i ...interface{}) {Fix stderr printing functions (#894)Alessio Tregliabefore adoption40d34bc
line 1251why, one step back1251 c.PrintErr(fmt.Sprintf(format, i...))Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1252–1332why, one step back1252}12531254// CommandPath returns the full path to this command.1255func (c *Command) CommandPath() string {1256 if c.HasParent() {1257 return c.Parent().CommandPath() + " " + c.Name()1258 }1259 return c.Name()1260}12611262// UseLine puts out the full usage for a given command (including parents).1263func (c *Command) UseLine() string {1264 var useline string1265 if c.HasParent() {1266 useline = c.parent.CommandPath() + " " + c.Use1267 } else {1268 useline = c.Use1269 }1270 if c.DisableFlagsInUseLine {1271 return useline1272 }1273 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1274 useline += " [flags]"1275 }1276 return useline1277}12781279// DebugFlags used to determine which flags have been assigned to which commands1280// and which persist.1281func (c *Command) DebugFlags() {1282 c.Println("DebugFlags called on", c.Name())1283 var debugflags func(*Command)12841285 debugflags = func(x *Command) {1286 if x.HasFlags() || x.HasPersistentFlags() {1287 c.Println(x.Name())1288 }1289 if x.HasFlags() {1290 x.flags.VisitAll(func(f *flag.Flag) {1291 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1292 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1293 } else {1294 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1295 }1296 })1297 }1298 if x.HasPersistentFlags() {1299 x.pflags.VisitAll(func(f *flag.Flag) {1300 if x.HasFlags() {1301 if x.flags.Lookup(f.Name) == nil {1302 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1303 }1304 } else {1305 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1306 }1307 })1308 }1309 c.Println(x.flagErrorBuf)1310 if x.HasSubCommands() {1311 for _, y := range x.commands {1312 debugflags(y)1313 }1314 }1315 }13161317 debugflags(c)1318}13191320// Name returns the command's name: the first word in the use line.1321func (c *Command) Name() string {1322 name := c.Use1323 i := strings.Index(name, " ")1324 if i >= 0 {1325 name = name[:i]1326 }1327 return name1328}13291330// HasAlias determines if a given string is an alias of the command.1331func (c *Command) HasAlias(s string) bool {1332 for _, a := range c.Aliases {Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184
line 1333why, one step back1333 if commandNameMatches(a, s) {Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1334–1509why, one step back1334 return true1335 }1336 }1337 return false1338}13391340// CalledAs returns the command name or alias that was used to invoke1341// this command or an empty string if the command has not been called.1342func (c *Command) CalledAs() string {1343 if c.commandCalledAs.called {1344 return c.commandCalledAs.name1345 }1346 return ""1347}13481349// hasNameOrAliasPrefix returns true if the Name or any of aliases start1350// with prefix1351func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1352 if strings.HasPrefix(c.Name(), prefix) {1353 c.commandCalledAs.name = c.Name()1354 return true1355 }1356 for _, alias := range c.Aliases {1357 if strings.HasPrefix(alias, prefix) {1358 c.commandCalledAs.name = alias1359 return true1360 }1361 }1362 return false1363}13641365// NameAndAliases returns a list of the command name and all aliases1366func (c *Command) NameAndAliases() string {1367 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1368}13691370// HasExample determines if the command has example.1371func (c *Command) HasExample() bool {1372 return len(c.Example) > 01373}13741375// Runnable determines if the command is itself runnable.1376func (c *Command) Runnable() bool {1377 return c.Run != nil || c.RunE != nil1378}13791380// HasSubCommands determines if the command has children commands.1381func (c *Command) HasSubCommands() bool {1382 return len(c.commands) > 01383}13841385// IsAvailableCommand determines if a command is available as a non-help command1386// (this includes all non deprecated/hidden commands).1387func (c *Command) IsAvailableCommand() bool {1388 if len(c.Deprecated) != 0 || c.Hidden {1389 return false1390 }13911392 if c.HasParent() && c.Parent().helpCommand == c {1393 return false1394 }13951396 if c.Runnable() || c.HasAvailableSubCommands() {1397 return true1398 }13991400 return false1401}14021403// IsAdditionalHelpTopicCommand determines if a command is an additional1404// help topic command; additional help topic command is determined by the1405// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1406// are runnable/hidden/deprecated.1407// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1408func (c *Command) IsAdditionalHelpTopicCommand() bool {1409 // if a command is runnable, deprecated, or hidden it is not a 'help' command1410 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1411 return false1412 }14131414 // if any non-help sub commands are found, the command is not a 'help' command1415 for _, sub := range c.commands {1416 if !sub.IsAdditionalHelpTopicCommand() {1417 return false1418 }1419 }14201421 // the command either has no sub commands, or no non-help sub commands1422 return true1423}14241425// HasHelpSubCommands determines if a command has any available 'help' sub commands1426// that need to be shown in the usage/help default template under 'additional help1427// topics'.1428func (c *Command) HasHelpSubCommands() bool {1429 // return true on the first found available 'help' sub command1430 for _, sub := range c.commands {1431 if sub.IsAdditionalHelpTopicCommand() {1432 return true1433 }1434 }14351436 // the command either has no sub commands, or no available 'help' sub commands1437 return false1438}14391440// HasAvailableSubCommands determines if a command has available sub commands that1441// need to be shown in the usage/help default template under 'available commands'.1442func (c *Command) HasAvailableSubCommands() bool {1443 // return true on the first found available (non deprecated/help/hidden)1444 // sub command1445 for _, sub := range c.commands {1446 if sub.IsAvailableCommand() {1447 return true1448 }1449 }14501451 // the command either has no sub commands, or no available (non deprecated/help/hidden)1452 // sub commands1453 return false1454}14551456// HasParent determines if the command is a child command.1457func (c *Command) HasParent() bool {1458 return c.parent != nil1459}14601461// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.1462func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1463 return c.globNormFunc1464}14651466// Flags returns the complete FlagSet that applies1467// to this command (local and persistent declared here and by all parents).1468func (c *Command) Flags() *flag.FlagSet {1469 if c.flags == nil {1470 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1471 if c.flagErrorBuf == nil {1472 c.flagErrorBuf = new(bytes.Buffer)1473 }1474 c.flags.SetOutput(c.flagErrorBuf)1475 }14761477 return c.flags1478}14791480// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1481func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1482 persistentFlags := c.PersistentFlags()14831484 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1485 c.LocalFlags().VisitAll(func(f *flag.Flag) {1486 if persistentFlags.Lookup(f.Name) == nil {1487 out.AddFlag(f)1488 }1489 })1490 return out1491}14921493// LocalFlags returns the local FlagSet specifically set in the current command.1494func (c *Command) LocalFlags() *flag.FlagSet {1495 c.mergePersistentFlags()14961497 if c.lflags == nil {1498 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1499 if c.flagErrorBuf == nil {1500 c.flagErrorBuf = new(bytes.Buffer)1501 }1502 c.lflags.SetOutput(c.flagErrorBuf)1503 }1504 c.lflags.SortFlags = c.Flags().SortFlags1505 if c.globNormFunc != nil {1506 c.lflags.SetNormalizeFunc(c.globNormFunc)1507 }15081509 addToLocal := func(f *flag.Flag) {fix: show flags that shadow parent persistent flag in child help (#1776)Brian Pursleybefore adoption22b6179
lines 1510–1511why, one step back1510 // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag1511 if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
lines 1512–1698why, one step back1512 c.lflags.AddFlag(f)1513 }1514 }1515 c.Flags().VisitAll(addToLocal)1516 c.PersistentFlags().VisitAll(addToLocal)1517 return c.lflags1518}15191520// InheritedFlags returns all flags which were inherited from parent commands.1521func (c *Command) InheritedFlags() *flag.FlagSet {1522 c.mergePersistentFlags()15231524 if c.iflags == nil {1525 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1526 if c.flagErrorBuf == nil {1527 c.flagErrorBuf = new(bytes.Buffer)1528 }1529 c.iflags.SetOutput(c.flagErrorBuf)1530 }15311532 local := c.LocalFlags()1533 if c.globNormFunc != nil {1534 c.iflags.SetNormalizeFunc(c.globNormFunc)1535 }15361537 c.parentsPflags.VisitAll(func(f *flag.Flag) {1538 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1539 c.iflags.AddFlag(f)1540 }1541 })1542 return c.iflags1543}15441545// NonInheritedFlags returns all flags which were not inherited from parent commands.1546func (c *Command) NonInheritedFlags() *flag.FlagSet {1547 return c.LocalFlags()1548}15491550// PersistentFlags returns the persistent FlagSet specifically set in the current command.1551func (c *Command) PersistentFlags() *flag.FlagSet {1552 if c.pflags == nil {1553 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1554 if c.flagErrorBuf == nil {1555 c.flagErrorBuf = new(bytes.Buffer)1556 }1557 c.pflags.SetOutput(c.flagErrorBuf)1558 }1559 return c.pflags1560}15611562// ResetFlags deletes all flags from command.1563func (c *Command) ResetFlags() {1564 c.flagErrorBuf = new(bytes.Buffer)1565 c.flagErrorBuf.Reset()1566 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1567 c.flags.SetOutput(c.flagErrorBuf)1568 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1569 c.pflags.SetOutput(c.flagErrorBuf)15701571 c.lflags = nil1572 c.iflags = nil1573 c.parentsPflags = nil1574}15751576// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1577func (c *Command) HasFlags() bool {1578 return c.Flags().HasFlags()1579}15801581// HasPersistentFlags checks if the command contains persistent flags.1582func (c *Command) HasPersistentFlags() bool {1583 return c.PersistentFlags().HasFlags()1584}15851586// HasLocalFlags checks if the command has flags specifically declared locally.1587func (c *Command) HasLocalFlags() bool {1588 return c.LocalFlags().HasFlags()1589}15901591// HasInheritedFlags checks if the command has flags inherited from its parent command.1592func (c *Command) HasInheritedFlags() bool {1593 return c.InheritedFlags().HasFlags()1594}15951596// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1597// structure) which are not hidden or deprecated.1598func (c *Command) HasAvailableFlags() bool {1599 return c.Flags().HasAvailableFlags()1600}16011602// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1603func (c *Command) HasAvailablePersistentFlags() bool {1604 return c.PersistentFlags().HasAvailableFlags()1605}16061607// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1608// or deprecated.1609func (c *Command) HasAvailableLocalFlags() bool {1610 return c.LocalFlags().HasAvailableFlags()1611}16121613// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1614// not hidden or deprecated.1615func (c *Command) HasAvailableInheritedFlags() bool {1616 return c.InheritedFlags().HasAvailableFlags()1617}16181619// Flag climbs up the command tree looking for matching flag.1620func (c *Command) Flag(name string) (flag *flag.Flag) {1621 flag = c.Flags().Lookup(name)16221623 if flag == nil {1624 flag = c.persistentFlag(name)1625 }16261627 return1628}16291630// Recursively find matching persistent flag.1631func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1632 if c.HasPersistentFlags() {1633 flag = c.PersistentFlags().Lookup(name)1634 }16351636 if flag == nil {1637 c.updateParentsPflags()1638 flag = c.parentsPflags.Lookup(name)1639 }1640 return1641}16421643// ParseFlags parses persistent flag tree and local flags.1644func (c *Command) ParseFlags(args []string) error {1645 if c.DisableFlagParsing {1646 return nil1647 }16481649 if c.flagErrorBuf == nil {1650 c.flagErrorBuf = new(bytes.Buffer)1651 }1652 beforeErrorBufLen := c.flagErrorBuf.Len()1653 c.mergePersistentFlags()16541655 // do it here after merging all flags and just before parse1656 c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)16571658 err := c.Flags().Parse(args)1659 // Print warnings if they occurred (e.g. deprecated flag messages).1660 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1661 c.Print(c.flagErrorBuf.String())1662 }16631664 return err1665}16661667// Parent returns a commands parent command.1668func (c *Command) Parent() *Command {1669 return c.parent1670}16711672// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1673// and adds missing persistent flags of all parents.1674func (c *Command) mergePersistentFlags() {1675 c.updateParentsPflags()1676 c.Flags().AddFlagSet(c.PersistentFlags())1677 c.Flags().AddFlagSet(c.parentsPflags)1678}16791680// updateParentsPflags updates c.parentsPflags by adding1681// new persistent flags of all parents.1682// If c.parentsPflags == nil, it makes new.1683func (c *Command) updateParentsPflags() {1684 if c.parentsPflags == nil {1685 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1686 c.parentsPflags.SetOutput(c.flagErrorBuf)1687 c.parentsPflags.SortFlags = false1688 }16891690 if c.globNormFunc != nil {1691 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1692 }16931694 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)16951696 c.VisitParents(func(parent *Command) {1697 c.parentsPflags.AddFlagSet(parent.PersistentFlags())1698 })Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184
lines 1699–1709why, one step back1699}17001701// commandNameMatches checks if two command names are equal1702// taking into account case sensitivity according to1703// EnableCaseInsensitive global configuration.1704func commandNameMatches(s string, t string) bool {1705 if EnableCaseInsensitive {1706 return strings.EqualFold(s, t)1707 }17081709 return s == tMove projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f
line 1710why, one step back1710}