command.go
This file
Path
command.go
2,072 lines · 59.7 KiB · Go
Last changed by
refactor: change minUsagePadding from var to const (#2325)SamareshSinghbefore adoptionfc81d20
History of this fileTake it
The walk stopped after 200 commits: lines older than 89d7b83 point at it.
update copyright year (#1927)Unai Martinez-Corralbefore adoption9e6b58a
line 1why, one step back1// Copyright 2013-2023 The Cobra AuthorsAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
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.0Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
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"Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 23–25why, one step back23 "fmt"24 "io"25 "os"Revert "Make detection for test-binary more universal (#2173)" (#2235)Marc Khouzambefore adoption40b5bc1
line 26why, one step back26 "path/filepath"Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 27–32why, one step back27 "sort"28 "strings"2930 flag "github.com/spf13/pflag"31)32Support usage as plugin for tools like kubectl (#2018)Nir Sofferbefore adoption890302a
lines 33–35why, one step back33const (34 FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"35 CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 36–38why, one step back3637 helpFlagName = "help"38 helpCommandName = "help"Support usage as plugin for tools like kubectl (#2018)Nir Sofferbefore adoption890302a
line 39why, one step back39)Include --help and --version flag in completion (#1813)Marc Khouzambefore adoption212ea40
line 40why, one step back40Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 41why, one step back41// FParseErrWhitelist configures Flag parse errors to be ignoredBump pflag to 1.0.8 (#2303)Tomas Aschanbefore adoption51d6751
line 42why, one step back42type FParseErrWhitelist flag.ParseErrorsAllowlistAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 43why, one step back43fix: func name in doc strings (#1885)Yash Ladhabefore adoptionbf11ab6
line 44why, one step back44// Group Structure to manage groups for commandsAdd groups for commands in help (#1003)aawsomebefore adoption2169adb
lines 45–49why, one step back45type Group struct {46 ID string47 Title string48}49Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 50–55why, one step back50// Command is just that, a command for your application.51// E.g. 'go run ...' - 'run' is the command. Cobra requires52// you to define the usage and description as part of your command53// definition to ensure usability.54type Command struct {55 // Use is the one-line usage message.fix: func name in doc strings (#1885)Yash Ladhabefore adoptionbf11ab6
line 56why, one step back56 // Recommended syntax is as follows:Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 57–75why, one step back57 // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.58 // ... indicates that you can specify multiple values for the previous argument.59 // | indicates mutually exclusive information. You can use the argument to the left of the separator or the60 // argument to the right of the separator. You cannot use both arguments in a single use of the command.61 // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are62 // optional, they are enclosed in brackets ([ ]).63 // Example: add [-F file | -D dir]... [-f format] profile64 Use string6566 // Aliases is an array of aliases that can be used instead of the first word in Use.67 Aliases []string6869 // SuggestFor is an array of command names for which this command will be suggested -70 // similar to aliases but only suggests.71 SuggestFor []string7273 // Short is the short description shown in the 'help' output.74 Short string75Add groups for commands in help (#1003)aawsomebefore adoption2169adb
lines 76–78why, one step back76 // The group id under which this subcommand is grouped in the 'help' output of its parent.77 GroupID string78Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 79–85why, one step back79 // Long is the long message shown in the 'help <this-command>' output.80 Long string8182 // Example is examples of how to use the command.83 Example string8485 // ValidArgs is list of all valid non-flag arguments that are accepted in shell completionsfeat: add CompletionWithDesc helper (#2231)ccoVeillebefore adoption8cb30f9
line 86why, one step back86 ValidArgs []CompletionAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 87–89why, one step back87 // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.88 // It is a dynamic version of using ValidArgs.89 // Only one of ValidArgs and ValidArgsFunction can be used for a command.feat: add CompletionFunc type to help with completions (#2220)ccoVeillebefore adoption6c3c116
line 90why, one step back90 ValidArgsFunction CompletionFuncAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 91–107why, one step back9192 // Expected arguments93 Args PositionalArgs9495 // ArgAliases is List of aliases for ValidArgs.96 // These are not suggested to the user in the shell completion,97 // but accepted if entered manually.98 ArgAliases []string99100 // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.101 // For portability with other shells, it is recommended to instead use ValidArgsFunction102 BashCompletionFunction string103104 // Deprecated defines, if this command is deprecated and should print this string when used.105 Deprecated string106107 // Annotations are key/value pairs that can be used by applications to identify orSupport usage as plugin for tools like kubectl (#2018)Nir Sofferbefore adoption890302a
line 108why, one step back108 // group commands or set special options.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 109–123why, one step back109 Annotations map[string]string110111 // Version defines the version for this command. If this value is non-empty and the command does not112 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,113 // will print content of the "Version" variable. A shorthand "v" flag will also be added if the114 // command does not define one.115 Version string116117 // The *Run functions are executed in the following order:118 // * PersistentPreRun()119 // * PreRun()120 // * Run()121 // * PostRun()122 // * PersistentPostRun()123 // All functions get the same args, the arguments after the command name.Add notes to doc on preRun and postRun condition (#2041)Haoming Mengbefore adoption95d8a1e
lines 124–125why, one step back124 // The *PreRun and *PostRun functions will only be executed if the Run function of the current125 // command has been declared.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 126–147why, one step back126 //127 // PersistentPreRun: children of this command will inherit and execute.128 PersistentPreRun func(cmd *Command, args []string)129 // PersistentPreRunE: PersistentPreRun but returns an error.130 PersistentPreRunE func(cmd *Command, args []string) error131 // PreRun: children of this command will not inherit.132 PreRun func(cmd *Command, args []string)133 // PreRunE: PreRun but returns an error.134 PreRunE func(cmd *Command, args []string) error135 // Run: Typically the actual work function. Most commands will only implement this.136 Run func(cmd *Command, args []string)137 // RunE: Run but returns an error.138 RunE func(cmd *Command, args []string) error139 // PostRun: run after the Run command.140 PostRun func(cmd *Command, args []string)141 // PostRunE: PostRun but returns an error.142 PostRunE func(cmd *Command, args []string) error143 // PersistentPostRun: children of this command will inherit and execute after PostRun.144 PersistentPostRun func(cmd *Command, args []string)145 // PersistentPostRunE: PersistentPostRun but returns an error.146 PersistentPostRunE func(cmd *Command, args []string) error147Add groups for commands in help (#1003)aawsomebefore adoption2169adb
lines 148–150why, one step back148 // groups for subcommands149 commandgroups []*Group150Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 151–159why, one step back151 // args is actual args parsed from flags.152 args []string153 // flagErrorBuf contains all error messages from pflag.154 flagErrorBuf *bytes.Buffer155 // flags is full set of flags.156 flags *flag.FlagSet157 // pflags contains persistent flags.158 pflags *flag.FlagSet159 // lflags contains local flags.flags: clarify documentation that LocalFlags related function do not modify the state (#2064)Dmytro Milinevskyibefore adoption4fb0a66
line 160why, one step back160 // This field does not represent internal state, it's used as a cache to optimise LocalFlags function callAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 161–162why, one step back161 lflags *flag.FlagSet162 // iflags contains inherited flags.flags: clarify documentation that LocalFlags related function do not modify the state (#2064)Dmytro Milinevskyibefore adoption4fb0a66
line 163why, one step back163 // This field does not represent internal state, it's used as a cache to optimise InheritedFlags function callAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 164–173why, one step back164 iflags *flag.FlagSet165 // parentsPflags is all persistent flags of cmd's parents.166 parentsPflags *flag.FlagSet167 // globNormFunc is the global normalization function168 // that we can use on every pflag set and children commands169 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName170171 // usageFunc is usage func defined by user.172 usageFunc func(*Command) error173 // usageTemplate is usage template defined by user.Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 174why, one step back174 usageTemplate *tmplFuncAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 175–178why, one step back175 // flagErrorFunc is func defined by user and it's called when the parsing of176 // flags returns an error.177 flagErrorFunc func(*Command, error) error178 // helpTemplate is help template defined by user.Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 179why, one step back179 helpTemplate *tmplFuncAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 180–184why, one step back180 // helpFunc is help func defined by user.181 helpFunc func(*Command, []string)182 // helpCommand is command with usage 'help'. If it's not defined by user,183 // cobra uses default help command.184 helpCommand *CommandAdd groups for commands in help (#1003)aawsomebefore adoption2169adb
lines 185–190why, one step back185 // helpCommandGroupID is the group id for the helpCommand186 helpCommandGroupID string187188 // completionCommandGroupID is the group id for the completion command189 completionCommandGroupID string190Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 191why, one step back191 // versionTemplate is the version template defined by user.Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 192why, one step back192 versionTemplate *tmplFuncAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 193why, one step back193Customizable error message prefix (#2023)Soumabefore adoption0c72800
lines 194–196why, one step back194 // errPrefix is the error message prefix defined by user.195 errPrefix string196Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 197–272why, one step back197 // inReader is a reader defined by the user that replaces stdin198 inReader io.Reader199 // outWriter is a writer defined by the user that replaces stdout200 outWriter io.Writer201 // errWriter is a writer defined by the user that replaces stderr202 errWriter io.Writer203204 // FParseErrWhitelist flag parse errors to be ignored205 FParseErrWhitelist FParseErrWhitelist206207 // CompletionOptions is a set of options to control the handling of shell completion208 CompletionOptions CompletionOptions209210 // commandsAreSorted defines, if command slice are sorted or not.211 commandsAreSorted bool212 // commandCalledAs is the name or alias value used to call this command.213 commandCalledAs struct {214 name string215 called bool216 }217218 ctx context.Context219220 // commands is the list of commands supported by this program.221 commands []*Command222 // parent is a parent command for this command.223 parent *Command224 // Max lengths of commands' string lengths for use in padding.225 commandsMaxUseLen int226 commandsMaxCommandPathLen int227 commandsMaxNameLen int228229 // TraverseChildren parses flags on all parents before executing child command.230 TraverseChildren bool231232 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.233 Hidden bool234235 // SilenceErrors is an option to quiet errors down stream.236 SilenceErrors bool237238 // SilenceUsage is an option to silence usage when an error occurs.239 SilenceUsage bool240241 // DisableFlagParsing disables the flag parsing.242 // If this is true all flags will be passed to the command as arguments.243 DisableFlagParsing bool244245 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")246 // will be printed by generating docs for this command.247 DisableAutoGenTag bool248249 // DisableFlagsInUseLine will disable the addition of [flags] to the usage250 // line of a command when printing help or generating docs251 DisableFlagsInUseLine bool252253 // DisableSuggestions disables the suggestions based on Levenshtein distance254 // that go along with 'unknown command' messages.255 DisableSuggestions bool256257 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.258 // Must be > 0.259 SuggestionsMinimumDistance int260}261262// Context returns underlying command context. If command was executed263// with ExecuteContext or the context was set with SetContext, the264// previously set context will be returned. Otherwise, nil is returned.265//266// Notice that a call to Execute and ExecuteC will replace a nil context of267// a command with a context.Background, so a background context will be268// returned by Context after one of these functions has been called.269func (c *Command) Context() context.Context {270 return c.ctx271}272Clarify SetContext documentation (#1748)Paul Meyerbefore adoption2a7647f
lines 273–274why, one step back273// SetContext sets context for the command. This context will be overwritten by274// Command.ExecuteContext or Command.ExecuteContextC.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 275–286why, one step back275func (c *Command) SetContext(ctx context.Context) {276 c.ctx = ctx277}278279// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden280// particularly useful when testing.281func (c *Command) SetArgs(a []string) {282 c.args = a283}284285// SetOutput sets the destination for usage and error messages.286// If output is nil, os.Stderr is used.Fix deprecation comment for Command.SetOutput (#2172)Sebastiaan van Stijnbefore adoption371ae25
line 287why, one step back287//Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 288–318why, one step back288// Deprecated: Use SetOut and/or SetErr instead289func (c *Command) SetOutput(output io.Writer) {290 c.outWriter = output291 c.errWriter = output292}293294// SetOut sets the destination for usage messages.295// If newOut is nil, os.Stdout is used.296func (c *Command) SetOut(newOut io.Writer) {297 c.outWriter = newOut298}299300// SetErr sets the destination for error messages.301// If newErr is nil, os.Stderr is used.302func (c *Command) SetErr(newErr io.Writer) {303 c.errWriter = newErr304}305306// SetIn sets the source for input data307// If newIn is nil, os.Stdin is used.308func (c *Command) SetIn(newIn io.Reader) {309 c.inReader = newIn310}311312// SetUsageFunc sets usage function. Usage can be defined by application.313func (c *Command) SetUsageFunc(f func(*Command) error) {314 c.usageFunc = f315}316317// SetUsageTemplate sets usage template. Can be defined by Application.318func (c *Command) SetUsageTemplate(s string) {Allow to reset the templates to the default (#2229)Marc Khouzambefore adoptionab5cadc
lines 319–322why, one step back319 if s == "" {320 c.usageTemplate = nil321 return322 }Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 323why, one step back323 c.usageTemplate = tmpl(s)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 324–341why, one step back324}325326// SetFlagErrorFunc sets a function to generate an error when flag parsing327// fails.328func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {329 c.flagErrorFunc = f330}331332// SetHelpFunc sets help function. Can be defined by Application.333func (c *Command) SetHelpFunc(f func(*Command, []string)) {334 c.helpFunc = f335}336337// SetHelpCommand sets help command.338func (c *Command) SetHelpCommand(cmd *Command) {339 c.helpCommand = cmd340}341fix: func name in doc strings (#1885)Yash Ladhabefore adoptionbf11ab6
line 342why, one step back342// SetHelpCommandGroupID sets the group id of the help command.Add groups for commands in help (#1003)aawsomebefore adoption2169adb
lines 343–350why, one step back343func (c *Command) SetHelpCommandGroupID(groupID string) {344 if c.helpCommand != nil {345 c.helpCommand.GroupID = groupID346 }347 // helpCommandGroupID is used if no helpCommand is defined by the user348 c.helpCommandGroupID = groupID349}350fix: func name in doc strings (#1885)Yash Ladhabefore adoptionbf11ab6
line 351why, one step back351// SetCompletionCommandGroupID sets the group id of the completion command.Add groups for commands in help (#1003)aawsomebefore adoption2169adb
lines 352–356why, one step back352func (c *Command) SetCompletionCommandGroupID(groupID string) {353 // completionCommandGroupID is used if no completion command is defined by the user354 c.Root().completionCommandGroupID = groupID355}356Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 357–358why, one step back357// SetHelpTemplate sets help template to be used. Application can use it to set custom template.358func (c *Command) SetHelpTemplate(s string) {Allow to reset the templates to the default (#2229)Marc Khouzambefore adoptionab5cadc
lines 359–362why, one step back359 if s == "" {360 c.helpTemplate = nil361 return362 }Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 363why, one step back363 c.helpTemplate = tmpl(s)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 364–367why, one step back364}365366// SetVersionTemplate sets version template to be used. Application can use it to set custom template.367func (c *Command) SetVersionTemplate(s string) {Allow to reset the templates to the default (#2229)Marc Khouzambefore adoptionab5cadc
lines 368–371why, one step back368 if s == "" {369 c.versionTemplate = nil370 return371 }Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 372why, one step back372 c.versionTemplate = tmpl(s)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 373–374why, one step back373}374Customizable error message prefix (#2023)Soumabefore adoption0c72800
lines 375–379why, one step back375// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.376func (c *Command) SetErrPrefix(s string) {377 c.errPrefix = s378}379Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 380–452why, one step back380// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.381// The user should not have a cyclic dependency on commands.382func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {383 c.Flags().SetNormalizeFunc(n)384 c.PersistentFlags().SetNormalizeFunc(n)385 c.globNormFunc = n386387 for _, command := range c.commands {388 command.SetGlobalNormalizationFunc(n)389 }390}391392// OutOrStdout returns output to stdout.393func (c *Command) OutOrStdout() io.Writer {394 return c.getOut(os.Stdout)395}396397// OutOrStderr returns output to stderr398func (c *Command) OutOrStderr() io.Writer {399 return c.getOut(os.Stderr)400}401402// ErrOrStderr returns output to stderr403func (c *Command) ErrOrStderr() io.Writer {404 return c.getErr(os.Stderr)405}406407// InOrStdin returns input to stdin408func (c *Command) InOrStdin() io.Reader {409 return c.getIn(os.Stdin)410}411412func (c *Command) getOut(def io.Writer) io.Writer {413 if c.outWriter != nil {414 return c.outWriter415 }416 if c.HasParent() {417 return c.parent.getOut(def)418 }419 return def420}421422func (c *Command) getErr(def io.Writer) io.Writer {423 if c.errWriter != nil {424 return c.errWriter425 }426 if c.HasParent() {427 return c.parent.getErr(def)428 }429 return def430}431432func (c *Command) getIn(def io.Reader) io.Reader {433 if c.inReader != nil {434 return c.inReader435 }436 if c.HasParent() {437 return c.parent.getIn(def)438 }439 return def440}441442// UsageFunc returns either the function set by SetUsageFunc for this command443// or a parent, or it returns a default usage function.444func (c *Command) UsageFunc() (f func(*Command) error) {445 if c.usageFunc != nil {446 return c.usageFunc447 }448 if c.HasParent() {449 return c.Parent().UsageFunc()450 }451 return func(c *Command) error {452 c.mergePersistentFlags()Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 453–454why, one step back453 fn := c.getUsageTemplateFunc()454 err := fn(c.OutOrStderr(), c)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 455–461why, one step back455 if err != nil {456 c.PrintErrln(err)457 }458 return err459 }460}461Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 462–474why, one step back462// getUsageTemplateFunc returns the usage template function for the command463// going up the command tree if necessary.464func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error {465 if c.usageTemplate != nil {466 return c.usageTemplate.fn467 }468469 if c.HasParent() {470 return c.parent.getUsageTemplateFunc()471 }472 return defaultUsageFunc473}474Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 475–492why, one step back475// Usage puts out the usage for the command.476// Used when a user provides invalid input.477// Can be defined by user by overriding UsageFunc.478func (c *Command) Usage() error {479 return c.UsageFunc()(c)480}481482// HelpFunc returns either the function set by SetHelpFunc for this command483// or a parent, or it returns a function with default help behavior.484func (c *Command) HelpFunc() func(*Command, []string) {485 if c.helpFunc != nil {486 return c.helpFunc487 }488 if c.HasParent() {489 return c.Parent().HelpFunc()490 }491 return func(c *Command, a []string) {492 c.mergePersistentFlags()Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 493why, one step back493 fn := c.getHelpTemplateFunc()Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 494–495why, one step back494 // The help should be sent to stdout495 // See https://github.com/spf13/cobra/issues/1002Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 496why, one step back496 err := fn(c.OutOrStdout(), c)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 497–502why, one step back497 if err != nil {498 c.PrintErrln(err)499 }500 }501}502Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 503–516why, one step back503// getHelpTemplateFunc returns the help template function for the command504// going up the command tree if necessary.505func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error {506 if c.helpTemplate != nil {507 return c.helpTemplate.fn508 }509510 if c.HasParent() {511 return c.parent.getHelpTemplateFunc()512 }513514 return defaultHelpFunc515}516Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 517–559why, one step back517// Help puts out the help for the command.518// Used when a user calls help [command].519// Can be defined by user by overriding HelpFunc.520func (c *Command) Help() error {521 c.HelpFunc()(c, []string{})522 return nil523}524525// UsageString returns usage string.526func (c *Command) UsageString() string {527 // Storing normal writers528 tmpOutput := c.outWriter529 tmpErr := c.errWriter530531 bb := new(bytes.Buffer)532 c.outWriter = bb533 c.errWriter = bb534535 CheckErr(c.Usage())536537 // Setting things back to normal538 c.outWriter = tmpOutput539 c.errWriter = tmpErr540541 return bb.String()542}543544// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this545// command or a parent, or it returns a function which returns the original546// error.547func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {548 if c.flagErrorFunc != nil {549 return c.flagErrorFunc550 }551552 if c.HasParent() {553 return c.parent.FlagErrorFunc()554 }555 return func(c *Command, err error) error {556 return err557 }558}559refactor: change minUsagePadding from var to const (#2325)SamareshSinghbefore adoptionfc81d20
line 560why, one step back560const minUsagePadding = 25Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 561–569why, one step back561562// UsagePadding return padding for the usage.563func (c *Command) UsagePadding() int {564 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {565 return minUsagePadding566 }567 return c.parent.commandsMaxUseLen568}569refactor: replace several vars with consts (#2328)htoyoda18before adoption117698a
line 570why, one step back570const minCommandPathPadding = 11Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 571–579why, one step back571572// CommandPathPadding return padding for the command path.573func (c *Command) CommandPathPadding() int {574 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {575 return minCommandPathPadding576 }577 return c.parent.commandsMaxCommandPathLen578}579refactor: replace several vars with consts (#2328)htoyoda18before adoption117698a
line 580why, one step back580const minNamePadding = 11Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 581–590why, one step back581582// NamePadding returns padding for the name.583func (c *Command) NamePadding() int {584 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {585 return minNamePadding586 }587 return c.parent.commandsMaxNameLen588}589590// UsageTemplate returns usage template for the command.Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 591why, one step back591// This function is kept for backwards-compatibility reasons.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 592why, one step back592func (c *Command) UsageTemplate() string {Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 593–594why, one step back593 if c.usageTemplate != nil {594 return c.usageTemplate.tmplAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 595–599why, one step back595 }596597 if c.HasParent() {598 return c.parent.UsageTemplate()599 }Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 600why, one step back600 return defaultUsageTemplateAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 601–603why, one step back601}602603// HelpTemplate return help template for the command.Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 604why, one step back604// This function is kept for backwards-compatibility reasons.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 605why, one step back605func (c *Command) HelpTemplate() string {Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 606–607why, one step back606 if c.helpTemplate != nil {607 return c.helpTemplate.tmplAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 608–612why, one step back608 }609610 if c.HasParent() {611 return c.parent.HelpTemplate()612 }Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 613why, one step back613 return defaultHelpTemplateAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 614–616why, one step back614}615616// VersionTemplate return version template for the command.Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 617why, one step back617// This function is kept for backwards-compatibility reasons.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 618why, one step back618func (c *Command) VersionTemplate() string {Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 619–620why, one step back619 if c.versionTemplate != nil {620 return c.versionTemplate.tmplAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 621–625why, one step back621 }622623 if c.HasParent() {624 return c.parent.VersionTemplate()625 }Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 626why, one step back626 return defaultVersionTemplateAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 627–628why, one step back627}628Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 629–641why, one step back629// getVersionTemplateFunc returns the version template function for the command630// going up the command tree if necessary.631func (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error {632 if c.versionTemplate != nil {633 return c.versionTemplate.fn634 }635636 if c.HasParent() {637 return c.parent.getVersionTemplateFunc()638 }639 return defaultVersionFunc640}641Customizable error message prefix (#2023)Soumabefore adoption0c72800
lines 642–653why, one step back642// ErrPrefix return error message prefix for the command643func (c *Command) ErrPrefix() string {644 if c.errPrefix != "" {645 return c.errPrefix646 }647648 if c.HasParent() {649 return c.parent.ErrPrefix()650 }651 return "Error:"652}653Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 654–713why, one step back654func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {655 flag := fs.Lookup(name)656 if flag == nil {657 return false658 }659 return flag.NoOptDefVal != ""660}661662func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {663 if len(name) == 0 {664 return false665 }666667 flag := fs.ShorthandLookup(name[:1])668 if flag == nil {669 return false670 }671 return flag.NoOptDefVal != ""672}673674func stripFlags(args []string, c *Command) []string {675 if len(args) == 0 {676 return args677 }678 c.mergePersistentFlags()679680 commands := []string{}681 flags := c.Flags()682683Loop:684 for len(args) > 0 {685 s := args[0]686 args = args[1:]687 switch {688 case s == "--":689 // "--" terminates the flags690 break Loop691 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):692 // If '--flag arg' then693 // delete arg from args.694 fallthrough // (do the same as below)695 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):696 // If '-f arg' then697 // delete 'arg' from args or break the loop if len(args) <= 1.698 if len(args) <= 1 {699 break Loop700 } else {701 args = args[1:]702 continue703 }704 case s != "" && !strings.HasPrefix(s, "-"):705 commands = append(commands, s)706 }707 }708709 return commands710}711712// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like713// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).fix: don't remove flag value that matches subcommand name (#1781)Brian Pursleybefore adoption6b0bd30
lines 714–739why, one step back714// Special care needs to be taken not to remove a flag value.715func (c *Command) argsMinusFirstX(args []string, x string) []string {716 if len(args) == 0 {717 return args718 }719 c.mergePersistentFlags()720 flags := c.Flags()721722Loop:723 for pos := 0; pos < len(args); pos++ {724 s := args[pos]725 switch {726 case s == "--":727 // -- means we have reached the end of the parseable args. Break out of the loop now.728 break Loop729 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):730 fallthrough731 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):732 // This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip733 // over the next arg, because that is the value of this flag.734 pos++735 continue736 case !strings.HasPrefix(s, "-"):737 // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,738 // return the args, excluding the one at this position.739 if s == x {Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43
line 740why, one step back740 ret := make([]string, 0, len(args)-1)fix: don't remove flag value that matches subcommand name (#1781)Brian Pursleybefore adoption6b0bd30
lines 741–744why, one step back741 ret = append(ret, args[:pos]...)742 ret = append(ret, args[pos+1:]...)743 return ret744 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 745–750why, one step back745 }746 }747 return args748}749750func isFlagArg(arg string) bool {completions: do not detect arguments with dash as 2nd char as flag (#1817)Dominik Roosbefore adoptionb4f979a
line 751why, one step back751 return ((len(arg) >= 3 && arg[0:2] == "--") ||Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 752–768why, one step back752 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))753}754755// Find the target command given the args and command tree756// Meant to be run on the highest node. Only searches down.757func (c *Command) Find(args []string) (*Command, []string, error) {758 var innerfind func(*Command, []string) (*Command, []string)759760 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {761 argsWOflags := stripFlags(innerArgs, c)762 if len(argsWOflags) == 0 {763 return c, innerArgs764 }765 nextSubCmd := argsWOflags[0]766767 cmd := c.findNext(nextSubCmd)768 if cmd != nil {fix: don't remove flag value that matches subcommand name (#1781)Brian Pursleybefore adoption6b0bd30
line 769why, one step back769 return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd))Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 770–787why, one step back770 }771 return c, innerArgs772 }773774 commandFound, a := innerfind(c, args)775 if commandFound.Args == nil {776 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))777 }778 return commandFound, a, nil779}780781func (c *Command) findSuggestions(arg string) string {782 if c.DisableSuggestions {783 return ""784 }785 if c.SuggestionsMinimumDistance <= 0 {786 c.SuggestionsMinimumDistance = 2787 }Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43
line 788why, one step back788 var sb strings.BuilderAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 789why, one step back789 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43
line 790why, one step back790 sb.WriteString("\n\nDid you mean this?\n")Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 791why, one step back791 for _, s := range suggestions {Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43
line 792why, one step back792 _, _ = fmt.Fprintf(&sb, "\t%v\n", s)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 793–794why, one step back793 }794 }Micro-optimizations (#1957)Ville Skyttäbefore adoption3d8ac43
line 795why, one step back795 return sb.String()Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 796–800why, one step back796}797798func (c *Command) findNext(next string) *Command {799 matches := make([]*Command, 0)800 for _, cmd := range c.commands {Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184
line 801why, one step back801 if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 802–810why, one step back802 cmd.commandCalledAs.name = next803 return cmd804 }805 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {806 matches = append(matches, cmd)807 }808 }809810 if len(matches) == 1 {command: temporarily disable G602 due to securego/gosec#1005 (#2022)Unai Martinez-Corralbefore adoption285460d
lines 811–813why, one step back811 // Temporarily disable gosec G602, which produces a false positive.812 // See https://github.com/securego/gosec/issues/1005.813 return matches[0] // #nosec G602Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 814–906why, one step back814 }815816 return nil817}818819// Traverse the command tree to find the command, and parse args for820// each parent.821func (c *Command) Traverse(args []string) (*Command, []string, error) {822 flags := []string{}823 inFlag := false824825 for i, arg := range args {826 switch {827 // A long flag with a space separated value828 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):829 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'830 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())831 flags = append(flags, arg)832 continue833 // A short flag with a space separated value834 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):835 inFlag = true836 flags = append(flags, arg)837 continue838 // The value for a flag839 case inFlag:840 inFlag = false841 flags = append(flags, arg)842 continue843 // A flag without a value, or with an `=` separated value844 case isFlagArg(arg):845 flags = append(flags, arg)846 continue847 }848849 cmd := c.findNext(arg)850 if cmd == nil {851 return c, args, nil852 }853854 if err := c.ParseFlags(flags); err != nil {855 return nil, args, err856 }857 return cmd.Traverse(args[i+1:])858 }859 return c, args, nil860}861862// SuggestionsFor provides suggestions for the typedName.863func (c *Command) SuggestionsFor(typedName string) []string {864 suggestions := []string{}865 for _, cmd := range c.commands {866 if cmd.IsAvailableCommand() {867 levenshteinDistance := ld(typedName, cmd.Name(), true)868 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance869 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))870 if suggestByLevenshtein || suggestByPrefix {871 suggestions = append(suggestions, cmd.Name())872 }873 for _, explicitSuggestion := range cmd.SuggestFor {874 if strings.EqualFold(typedName, explicitSuggestion) {875 suggestions = append(suggestions, cmd.Name())876 }877 }878 }879 }880 return suggestions881}882883// VisitParents visits all parents of the command and invokes fn on each parent.884func (c *Command) VisitParents(fn func(*Command)) {885 if c.HasParent() {886 fn(c.Parent())887 c.Parent().VisitParents(fn)888 }889}890891// Root finds root command.892func (c *Command) Root() *Command {893 if c.HasParent() {894 return c.Parent().Root()895 }896 return c897}898899// ArgsLenAtDash will return the length of c.Flags().Args at the moment900// when a -- was found during args parsing.901func (c *Command) ArgsLenAtDash() int {902 return c.Flags().ArgsLenAtDash()903}904905func (c *Command) execute(a []string) (err error) {906 if c == nil {Remove fully inactivated linters (#2148)Nir Sofferbefore adoption8003b74
line 907why, one step back907 return fmt.Errorf("called Execute() on a nil Command")Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 908–925why, one step back908 }909910 if len(c.Deprecated) > 0 {911 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)912 }913914 // initialize help and version flag at the last point possible to allow for user915 // overriding916 c.InitDefaultHelpFlag()917 c.InitDefaultVersionFlag()918919 err = c.ParseFlags(a)920 if err != nil {921 return c.FlagErrorFunc()(c, err)922 }923924 // If help is called, regardless of other flags, return we want help.925 // Also say we need help if the command isn't runnable.Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 926why, one step back926 helpVal, err := c.Flags().GetBool(helpFlagName)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 927–945why, one step back927 if err != nil {928 // should be impossible to get here as we always declare a help929 // flag in InitDefaultHelpFlag()930 c.Println("\"help\" flag declared as non-bool. Please correct your code")931 return err932 }933934 if helpVal {935 return flag.ErrHelp936 }937938 // for back-compat, only add version flag behavior if version is defined939 if c.Version != "" {940 versionVal, err := c.Flags().GetBool("version")941 if err != nil {942 c.Println("\"version\" flag declared as non-bool. Please correct your code")943 return err944 }945 if versionVal {Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 946–947why, one step back946 fn := c.getVersionTemplateFunc()947 err := fn(c.OutOrStdout(), c)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 948–960why, one step back948 if err != nil {949 c.Println(err)950 }951 return err952 }953 }954955 if !c.Runnable() {956 return flag.ErrHelp957 }958959 c.preRun()960Add OnFinalize method (#1788)Yann Soubeyrandbefore adoption93d1913
lines 961–962why, one step back961 defer c.postRun()962Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 963–971why, one step back963 argWoFlags := c.Flags().Args()964 if c.DisableFlagParsing {965 argWoFlags = a966 }967968 if err := c.ValidateArgs(argWoFlags); err != nil {969 return err970 }971Allow running persistent run hooks of all parents (#2044)vkhorozbefore adoption4cafa37
line 972why, one step back972 parents := make([]*Command, 0, 5)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 973why, one step back973 for p := c; p != nil; p = p.Parent() {Allow running persistent run hooks of all parents (#2044)vkhorozbefore adoption4cafa37
lines 974–984why, one step back974 if EnableTraverseRunHooks {975 // When EnableTraverseRunHooks is set:976 // - Execute all persistent pre-runs from the root parent till this command.977 // - Execute all persistent post-runs from this command till the root parent.978 parents = append([]*Command{p}, parents...)979 } else {980 // Otherwise, execute only the first found persistent hook.981 parents = append(parents, p)982 }983 }984 for _, p := range parents {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 985–988why, one step back985 if p.PersistentPreRunE != nil {986 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {987 return err988 }Allow running persistent run hooks of all parents (#2044)vkhorozbefore adoption4cafa37
lines 989–991why, one step back989 if !EnableTraverseRunHooks {990 break991 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 992–993why, one step back992 } else if p.PersistentPreRun != nil {993 p.PersistentPreRun(c, argWoFlags)Allow running persistent run hooks of all parents (#2044)vkhorozbefore adoption4cafa37
lines 994–996why, one step back994 if !EnableTraverseRunHooks {995 break996 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 997–1006why, one step back997 }998 }999 if c.PreRunE != nil {1000 if err := c.PreRunE(c, argWoFlags); err != nil {1001 return err1002 }1003 } else if c.PreRun != nil {1004 c.PreRun(c, argWoFlags)1005 }1006Expose ValidateRequiredFlags and ValidateFlagGroups (#1760)Skeet WUbefore adoptionfce8d8a
line 1007why, one step back1007 if err := c.ValidateRequiredFlags(); err != nil {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1008–1009why, one step back1008 return err1009 }Expose ValidateRequiredFlags and ValidateFlagGroups (#1760)Skeet WUbefore adoptionfce8d8a
line 1010why, one step back1010 if err := c.ValidateFlagGroups(); err != nil {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1011–1032why, one step back1011 return err1012 }10131014 if c.RunE != nil {1015 if err := c.RunE(c, argWoFlags); err != nil {1016 return err1017 }1018 } else {1019 c.Run(c, argWoFlags)1020 }1021 if c.PostRunE != nil {1022 if err := c.PostRunE(c, argWoFlags); err != nil {1023 return err1024 }1025 } else if c.PostRun != nil {1026 c.PostRun(c, argWoFlags)1027 }1028 for p := c; p != nil; p = p.Parent() {1029 if p.PersistentPostRunE != nil {1030 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {1031 return err1032 }Allow running persistent run hooks of all parents (#2044)vkhorozbefore adoption4cafa37
lines 1033–1035why, one step back1033 if !EnableTraverseRunHooks {1034 break1035 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1036–1037why, one step back1036 } else if p.PersistentPostRun != nil {1037 p.PersistentPostRun(c, argWoFlags)Allow running persistent run hooks of all parents (#2044)vkhorozbefore adoption4cafa37
lines 1038–1040why, one step back1038 if !EnableTraverseRunHooks {1039 break1040 }Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1041–1048why, one step back1041 }1042 }10431044 return nil1045}10461047func (c *Command) preRun() {1048 for _, x := range initializers {Add OnFinalize method (#1788)Yann Soubeyrandbefore adoption93d1913
lines 1049–1054why, one step back1049 x()1050 }1051}10521053func (c *Command) postRun() {1054 for _, x := range finalizers {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1055–1103why, one step back1055 x()1056 }1057}10581059// ExecuteContext is the same as Execute(), but sets the ctx on the command.1060// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs1061// functions.1062func (c *Command) ExecuteContext(ctx context.Context) error {1063 c.ctx = ctx1064 return c.Execute()1065}10661067// Execute uses the args (os.Args[1:] by default)1068// and run through the command tree finding appropriate matches1069// for commands and then corresponding flags.1070func (c *Command) Execute() error {1071 _, err := c.ExecuteC()1072 return err1073}10741075// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.1076// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs1077// functions.1078func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {1079 c.ctx = ctx1080 return c.ExecuteC()1081}10821083// ExecuteC executes the command.1084func (c *Command) ExecuteC() (cmd *Command, err error) {1085 if c.ctx == nil {1086 c.ctx = context.Background()1087 }10881089 // Regardless of what command execute is called on, run on Root only1090 if c.HasParent() {1091 return c.Root().ExecuteC()1092 }10931094 // windows hook1095 if preExecHookFn != nil {1096 preExecHookFn(c)1097 }10981099 // initialize help at the last point to allow for user overriding1100 c.InitDefaultHelpCmd()11011102 args := c.args1103Revert "Make detection for test-binary more universal (#2173)" (#2235)Marc Khouzambefore adoption40b5bc1
lines 1104–1105why, one step back1104 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #1551105 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1106–1108why, one step back1106 args = os.Args[1:]1107 }1108Remove the default "completion" cmd if it is alone (#1559)Marc Khouzambefore adoption24ada7f
line 1109why, one step back1109 // initialize the __complete command to be used for shell completionAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 1110why, one step back1110 c.initCompleteCmd(args)Remove the default "completion" cmd if it is alone (#1559)Marc Khouzambefore adoption24ada7f
lines 1111–1117why, one step back11111112 // initialize the default completion command1113 c.InitDefaultCompletionCmd(args...)11141115 // Now that all commands have been created, let's make sure all groups1116 // are properly created also1117 c.checkCommandGroups()Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1118–1130why, one step back11181119 var flags []string1120 if c.TraverseChildren {1121 cmd, flags, err = c.Traverse(args)1122 } else {1123 cmd, flags, err = c.Find(args)1124 }1125 if err != nil {1126 // If found parse to a subcommand and then failed, talk about the subcommand1127 if cmd != nil {1128 c = cmd1129 }1130 if !c.SilenceErrors {Customizable error message prefix (#2023)Soumabefore adoption0c72800
line 1131why, one step back1131 c.PrintErrln(c.ErrPrefix(), err.Error())Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1132–1151why, one step back1132 c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())1133 }1134 return c, err1135 }11361137 cmd.commandCalledAs.called = true1138 if cmd.commandCalledAs.name == "" {1139 cmd.commandCalledAs.name = cmd.Name()1140 }11411142 // We have to pass global context to children command1143 // if context is present on the parent command.1144 if cmd.ctx == nil {1145 cmd.ctx = c.ctx1146 }11471148 err = cmd.execute(flags)1149 if err != nil {1150 // Always show help if requested, even if SilenceErrors is in1151 // effectuse errors.Is() to check for errors (#1730)Paul Holzingerbefore adoptionb9ca594
line 1152why, one step back1152 if errors.Is(err, flag.ErrHelp) {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1153–1159why, one step back1153 cmd.HelpFunc()(cmd, args)1154 return cmd, nil1155 }11561157 // If root command has SilenceErrors flagged,1158 // all subcommands should respect it1159 if !cmd.SilenceErrors && !c.SilenceErrors {Customizable error message prefix (#2023)Soumabefore adoption0c72800
line 1160why, one step back1160 c.PrintErrln(cmd.ErrPrefix(), err.Error())Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1161–1173why, one step back1161 }11621163 // If root command has SilenceUsage flagged,1164 // all subcommands should respect it1165 if !cmd.SilenceUsage && !c.SilenceUsage {1166 c.Println(cmd.UsageString())1167 }1168 }1169 return cmd, err1170}11711172func (c *Command) ValidateArgs(args []string) error {1173 if c.Args == nil {undefined or nil Args default to ArbitraryArgs (#1612)Unai Martinez-Corralbefore adoptionea94a3d
line 1174why, one step back1174 return ArbitraryArgs(c, args)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1175–1178why, one step back1175 }1176 return c.Args(c, args)1177}1178Expose ValidateRequiredFlags and ValidateFlagGroups (#1760)Skeet WUbefore adoptionfce8d8a
lines 1179–1180why, one step back1179// ValidateRequiredFlags validates all required flags are present and returns an error otherwise1180func (c *Command) ValidateRequiredFlags() error {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1181–1202why, one step back1181 if c.DisableFlagParsing {1182 return nil1183 }11841185 flags := c.Flags()1186 missingFlagNames := []string{}1187 flags.VisitAll(func(pflag *flag.Flag) {1188 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]1189 if !found {1190 return1191 }1192 if (requiredAnnotation[0] == "true") && !pflag.Changed {1193 missingFlagNames = append(missingFlagNames, pflag.Name)1194 }1195 })11961197 if len(missingFlagNames) > 0 {1198 return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))1199 }1200 return nil1201}1202Check for group presence after full initialization (#1839)Marc Khouzambefore adoption10cf7be
lines 1203–1215why, one step back1203// checkCommandGroups checks if a command has been added to a group that does not exists.1204// If so, we panic because it indicates a coding error that should be corrected.1205func (c *Command) checkCommandGroups() {1206 for _, sub := range c.commands {1207 // if Group is not defined let the developer know right away1208 if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) {1209 panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath()))1210 }12111212 sub.checkCommandGroups()1213 }1214}1215Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1216–1220why, one step back1216// InitDefaultHelpFlag adds default help flag to c.1217// It is called automatically by executing the c or by calling help and usage.1218// If c already has help flag, it will do nothing.1219func (c *Command) InitDefaultHelpFlag() {1220 c.mergePersistentFlags()Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
line 1221why, one step back1221 if c.Flags().Lookup(helpFlagName) == nil {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 1222why, one step back1222 usage := "help for "Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1223why, one step back1223 name := c.DisplayName()Fix help text for pluginsNir Sofferbefore adoptiondf547f5
line 1224why, one step back1224 if name == "" {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1225–1226why, one step back1225 usage += "this command"1226 } else {Fix help text for pluginsNir Sofferbefore adoptiondf547f5
line 1227why, one step back1227 usage += nameAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 1228why, one step back1228 }Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 1229–1230why, one step back1229 c.Flags().BoolP(helpFlagName, "h", false, usage)1230 _ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"})Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1231–1248why, one step back1231 }1232}12331234// InitDefaultVersionFlag adds default version flag to c.1235// It is called automatically by executing the c.1236// If c already has a version flag, it will do nothing.1237// If c.Version is empty, it will do nothing.1238func (c *Command) InitDefaultVersionFlag() {1239 if c.Version == "" {1240 return1241 }12421243 c.mergePersistentFlags()1244 if c.Flags().Lookup("version") == nil {1245 usage := "version for "1246 if c.Name() == "" {1247 usage += "this command"1248 } else {Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1249why, one step back1249 usage += c.DisplayName()Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1250–1255why, one step back1250 }1251 if c.Flags().ShorthandLookup("v") == nil {1252 c.Flags().BoolP("version", "v", false, usage)1253 } else {1254 c.Flags().Bool("version", false, usage)1255 }Include --help and --version flag in completion (#1813)Marc Khouzambefore adoption212ea40
line 1256why, one step back1256 _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"})Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1257–1272why, one step back1257 }1258}12591260// InitDefaultHelpCmd adds default help command to c.1261// It is called automatically by executing the c or by calling help and usage.1262// If c already has help command or c has no subcommands, it will do nothing.1263func (c *Command) InitDefaultHelpCmd() {1264 if !c.HasSubCommands() {1265 return1266 }12671268 if c.helpCommand == nil {1269 c.helpCommand = &Command{1270 Use: "help [command]",1271 Short: "Help about any command",1272 Long: `Help provides help for any command in the application.Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1273why, one step back1273Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,feat: add CompletionWithDesc helper (#2231)ccoVeillebefore adoption8cb30f9
lines 1274–1275why, one step back1274 ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {1275 var completions []CompletionAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1276–1286why, one step back1276 cmd, _, e := c.Root().Find(args)1277 if e != nil {1278 return nil, ShellCompDirectiveNoFileComp1279 }1280 if cmd == nil {1281 // Root help command.1282 cmd = c.Root()1283 }1284 for _, subCmd := range cmd.Commands() {1285 if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {1286 if strings.HasPrefix(subCmd.Name(), toComplete) {feat: add CompletionWithDesc helper (#2231)ccoVeillebefore adoption8cb30f9
line 1287why, one step back1287 completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1288–1298why, one step back1288 }1289 }1290 }1291 return completions, ShellCompDirectiveNoFileComp1292 },1293 Run: func(c *Command, args []string) {1294 cmd, _, e := c.Root().Find(args)1295 if cmd == nil || e != nil {1296 c.Printf("Unknown help topic %#q\n", args)1297 CheckErr(c.Root().Usage())1298 } else {Flow context to command in SetHelpFunc (#2241)Fraser Watersbefore adoption1995054
lines 1299–1303why, one step back1299 // FLow the context down to be used in help text1300 if cmd.ctx == nil {1301 cmd.ctx = c.ctx1302 }1303Add '--version' flag to Help output (#1707)Francis Nickels IIIbefore adoption7039e1f
lines 1304–1305why, one step back1304 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1305 cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shownAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1306–1308why, one step back1306 CheckErr(cmd.Help())1307 }1308 },Add groups for commands in help (#1003)aawsomebefore adoption2169adb
line 1309why, one step back1309 GroupID: c.helpCommandGroupID,Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1310–1367why, one step back1310 }1311 }1312 c.RemoveCommand(c.helpCommand)1313 c.AddCommand(c.helpCommand)1314}13151316// ResetCommands delete parent, subcommand and help command from c.1317func (c *Command) ResetCommands() {1318 c.parent = nil1319 c.commands = nil1320 c.helpCommand = nil1321 c.parentsPflags = nil1322}13231324// Sorts commands by their names.1325type commandSorterByName []*Command13261327func (c commandSorterByName) Len() int { return len(c) }1328func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }1329func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }13301331// Commands returns a sorted slice of child commands.1332func (c *Command) Commands() []*Command {1333 // do not sort commands if it already sorted or sorting was disabled1334 if EnableCommandSorting && !c.commandsAreSorted {1335 sort.Sort(commandSorterByName(c.commands))1336 c.commandsAreSorted = true1337 }1338 return c.commands1339}13401341// AddCommand adds one or more commands to this parent command.1342func (c *Command) AddCommand(cmds ...*Command) {1343 for i, x := range cmds {1344 if cmds[i] == c {1345 panic("Command can't be a child of itself")1346 }1347 cmds[i].parent = c1348 // update max lengths1349 usageLen := len(x.Use)1350 if usageLen > c.commandsMaxUseLen {1351 c.commandsMaxUseLen = usageLen1352 }1353 commandPathLen := len(x.CommandPath())1354 if commandPathLen > c.commandsMaxCommandPathLen {1355 c.commandsMaxCommandPathLen = commandPathLen1356 }1357 nameLen := len(x.Name())1358 if nameLen > c.commandsMaxNameLen {1359 c.commandsMaxNameLen = nameLen1360 }1361 // If global normalization function exists, update all children1362 if c.globNormFunc != nil {1363 x.SetGlobalNormalizationFunc(c.globNormFunc)1364 }1365 c.commands = append(c.commands, x)1366 c.commandsAreSorted = false1367 }Add groups for commands in help (#1003)aawsomebefore adoption2169adb
lines 1368–1384why, one step back1368}13691370// Groups returns a slice of child command groups.1371func (c *Command) Groups() []*Group {1372 return c.commandgroups1373}13741375// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group1376func (c *Command) AllChildCommandsHaveGroup() bool {1377 for _, sub := range c.commands {1378 if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {1379 return false1380 }1381 }1382 return true1383}1384fix: func name in doc strings (#1885)Yash Ladhabefore adoptionbf11ab6
line 1385why, one step back1385// ContainsGroup return if groupID exists in the list of command groups.Add groups for commands in help (#1003)aawsomebefore adoption2169adb
lines 1386–1397why, one step back1386func (c *Command) ContainsGroup(groupID string) bool {1387 for _, x := range c.commandgroups {1388 if x.ID == groupID {1389 return true1390 }1391 }1392 return false1393}13941395// AddGroup adds one or more command groups to this parent command.1396func (c *Command) AddGroup(groups ...*Group) {1397 c.commandgroups = append(c.commandgroups, groups...)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1398–1467why, one step back1398}13991400// RemoveCommand removes one or more commands from a parent command.1401func (c *Command) RemoveCommand(cmds ...*Command) {1402 commands := []*Command{}1403main:1404 for _, command := range c.commands {1405 for _, cmd := range cmds {1406 if command == cmd {1407 command.parent = nil1408 continue main1409 }1410 }1411 commands = append(commands, command)1412 }1413 c.commands = commands1414 // recompute all lengths1415 c.commandsMaxUseLen = 01416 c.commandsMaxCommandPathLen = 01417 c.commandsMaxNameLen = 01418 for _, command := range c.commands {1419 usageLen := len(command.Use)1420 if usageLen > c.commandsMaxUseLen {1421 c.commandsMaxUseLen = usageLen1422 }1423 commandPathLen := len(command.CommandPath())1424 if commandPathLen > c.commandsMaxCommandPathLen {1425 c.commandsMaxCommandPathLen = commandPathLen1426 }1427 nameLen := len(command.Name())1428 if nameLen > c.commandsMaxNameLen {1429 c.commandsMaxNameLen = nameLen1430 }1431 }1432}14331434// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1435func (c *Command) Print(i ...interface{}) {1436 fmt.Fprint(c.OutOrStderr(), i...)1437}14381439// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1440func (c *Command) Println(i ...interface{}) {1441 c.Print(fmt.Sprintln(i...))1442}14431444// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1445func (c *Command) Printf(format string, i ...interface{}) {1446 c.Print(fmt.Sprintf(format, i...))1447}14481449// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.1450func (c *Command) PrintErr(i ...interface{}) {1451 fmt.Fprint(c.ErrOrStderr(), i...)1452}14531454// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.1455func (c *Command) PrintErrln(i ...interface{}) {1456 c.PrintErr(fmt.Sprintln(i...))1457}14581459// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.1460func (c *Command) PrintErrf(format string, i ...interface{}) {1461 c.PrintErr(fmt.Sprintf(format, i...))1462}14631464// CommandPath returns the full path to this command.1465func (c *Command) CommandPath() string {1466 if c.HasParent() {1467 return c.Parent().CommandPath() + " " + c.Name()Support usage as plugin for tools like kubectl (#2018)Nir Sofferbefore adoption890302a
line 1468why, one step back1468 }Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1469why, one step back1469 return c.DisplayName()Fix help text for pluginsNir Sofferbefore adoptiondf547f5
lines 1470–1471why, one step back1470}1471Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
lines 1472–1474why, one step back1472// DisplayName returns the name to display in help text. Returns command Name()1473// If CommandDisplayNameAnnoation is not set1474func (c *Command) DisplayName() string {Support usage as plugin for tools like kubectl (#2018)Nir Sofferbefore adoption890302a
lines 1475–1476why, one step back1475 if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {1476 return displayNameAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1477–1483why, one step back1477 }1478 return c.Name()1479}14801481// UseLine puts out the full usage for a given command (including parents).1482func (c *Command) UseLine() string {1483 var useline stringFix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1484why, one step back1484 use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 1485why, one step back1485 if c.HasParent() {Fix help text for runnable plugin commandNir Sofferbefore adoptiona73b9c3
line 1486why, one step back1486 useline = c.parent.CommandPath() + " " + useAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 1487why, one step back1487 } else {Fix help text for runnable plugin commandNir Sofferbefore adoptiona73b9c3
line 1488why, one step back1488 useline = useAdd Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1489–1552why, one step back1489 }1490 if c.DisableFlagsInUseLine {1491 return useline1492 }1493 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1494 useline += " [flags]"1495 }1496 return useline1497}14981499// DebugFlags used to determine which flags have been assigned to which commands1500// and which persist.1501func (c *Command) DebugFlags() {1502 c.Println("DebugFlags called on", c.Name())1503 var debugflags func(*Command)15041505 debugflags = func(x *Command) {1506 if x.HasFlags() || x.HasPersistentFlags() {1507 c.Println(x.Name())1508 }1509 if x.HasFlags() {1510 x.flags.VisitAll(func(f *flag.Flag) {1511 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1512 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1513 } else {1514 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1515 }1516 })1517 }1518 if x.HasPersistentFlags() {1519 x.pflags.VisitAll(func(f *flag.Flag) {1520 if x.HasFlags() {1521 if x.flags.Lookup(f.Name) == nil {1522 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1523 }1524 } else {1525 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1526 }1527 })1528 }1529 c.Println(x.flagErrorBuf)1530 if x.HasSubCommands() {1531 for _, y := range x.commands {1532 debugflags(y)1533 }1534 }1535 }15361537 debugflags(c)1538}15391540// Name returns the command's name: the first word in the use line.1541func (c *Command) Name() string {1542 name := c.Use1543 i := strings.Index(name, " ")1544 if i >= 0 {1545 name = name[:i]1546 }1547 return name1548}15491550// HasAlias determines if a given string is an alias of the command.1551func (c *Command) HasAlias(s string) bool {1552 for _, a := range c.Aliases {Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184
line 1553why, one step back1553 if commandNameMatches(a, s) {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1554–1689why, one step back1554 return true1555 }1556 }1557 return false1558}15591560// CalledAs returns the command name or alias that was used to invoke1561// this command or an empty string if the command has not been called.1562func (c *Command) CalledAs() string {1563 if c.commandCalledAs.called {1564 return c.commandCalledAs.name1565 }1566 return ""1567}15681569// hasNameOrAliasPrefix returns true if the Name or any of aliases start1570// with prefix1571func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1572 if strings.HasPrefix(c.Name(), prefix) {1573 c.commandCalledAs.name = c.Name()1574 return true1575 }1576 for _, alias := range c.Aliases {1577 if strings.HasPrefix(alias, prefix) {1578 c.commandCalledAs.name = alias1579 return true1580 }1581 }1582 return false1583}15841585// NameAndAliases returns a list of the command name and all aliases1586func (c *Command) NameAndAliases() string {1587 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1588}15891590// HasExample determines if the command has example.1591func (c *Command) HasExample() bool {1592 return len(c.Example) > 01593}15941595// Runnable determines if the command is itself runnable.1596func (c *Command) Runnable() bool {1597 return c.Run != nil || c.RunE != nil1598}15991600// HasSubCommands determines if the command has children commands.1601func (c *Command) HasSubCommands() bool {1602 return len(c.commands) > 01603}16041605// IsAvailableCommand determines if a command is available as a non-help command1606// (this includes all non deprecated/hidden commands).1607func (c *Command) IsAvailableCommand() bool {1608 if len(c.Deprecated) != 0 || c.Hidden {1609 return false1610 }16111612 if c.HasParent() && c.Parent().helpCommand == c {1613 return false1614 }16151616 if c.Runnable() || c.HasAvailableSubCommands() {1617 return true1618 }16191620 return false1621}16221623// IsAdditionalHelpTopicCommand determines if a command is an additional1624// help topic command; additional help topic command is determined by the1625// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1626// are runnable/hidden/deprecated.1627// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1628func (c *Command) IsAdditionalHelpTopicCommand() bool {1629 // if a command is runnable, deprecated, or hidden it is not a 'help' command1630 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1631 return false1632 }16331634 // if any non-help sub commands are found, the command is not a 'help' command1635 for _, sub := range c.commands {1636 if !sub.IsAdditionalHelpTopicCommand() {1637 return false1638 }1639 }16401641 // the command either has no sub commands, or no non-help sub commands1642 return true1643}16441645// HasHelpSubCommands determines if a command has any available 'help' sub commands1646// that need to be shown in the usage/help default template under 'additional help1647// topics'.1648func (c *Command) HasHelpSubCommands() bool {1649 // return true on the first found available 'help' sub command1650 for _, sub := range c.commands {1651 if sub.IsAdditionalHelpTopicCommand() {1652 return true1653 }1654 }16551656 // the command either has no sub commands, or no available 'help' sub commands1657 return false1658}16591660// HasAvailableSubCommands determines if a command has available sub commands that1661// need to be shown in the usage/help default template under 'available commands'.1662func (c *Command) HasAvailableSubCommands() bool {1663 // return true on the first found available (non deprecated/help/hidden)1664 // sub command1665 for _, sub := range c.commands {1666 if sub.IsAvailableCommand() {1667 return true1668 }1669 }16701671 // the command either has no sub commands, or no available (non deprecated/help/hidden)1672 // sub commands1673 return false1674}16751676// HasParent determines if the command is a child command.1677func (c *Command) HasParent() bool {1678 return c.parent != nil1679}16801681// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.1682func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1683 return c.globNormFunc1684}16851686// Flags returns the complete FlagSet that applies1687// to this command (local and persistent declared here and by all parents).1688func (c *Command) Flags() *flag.FlagSet {1689 if c.flags == nil {Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1690why, one step back1690 c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1691–1700why, one step back1691 if c.flagErrorBuf == nil {1692 c.flagErrorBuf = new(bytes.Buffer)1693 }1694 c.flags.SetOutput(c.flagErrorBuf)1695 }16961697 return c.flags1698}16991700// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.flags: clarify documentation that LocalFlags related function do not modify the state (#2064)Dmytro Milinevskyibefore adoption4fb0a66
line 1701why, one step back1701// This function does not modify the flags of the current command, it's purpose is to return the current state.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1702–1704why, one step back1702func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1703 persistentFlags := c.PersistentFlags()1704Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1705why, one step back1705 out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1706–1714why, one step back1706 c.LocalFlags().VisitAll(func(f *flag.Flag) {1707 if persistentFlags.Lookup(f.Name) == nil {1708 out.AddFlag(f)1709 }1710 })1711 return out1712}17131714// LocalFlags returns the local FlagSet specifically set in the current command.flags: clarify documentation that LocalFlags related function do not modify the state (#2064)Dmytro Milinevskyibefore adoption4fb0a66
line 1715why, one step back1715// This function does not modify the flags of the current command, it's purpose is to return the current state.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1716–1719why, one step back1716func (c *Command) LocalFlags() *flag.FlagSet {1717 c.mergePersistentFlags()17181719 if c.lflags == nil {Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1720why, one step back1720 c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1721–1731why, one step back1721 if c.flagErrorBuf == nil {1722 c.flagErrorBuf = new(bytes.Buffer)1723 }1724 c.lflags.SetOutput(c.flagErrorBuf)1725 }1726 c.lflags.SortFlags = c.Flags().SortFlags1727 if c.globNormFunc != nil {1728 c.lflags.SetNormalizeFunc(c.globNormFunc)1729 }17301731 addToLocal := func(f *flag.Flag) {fix: show flags that shadow parent persistent flag in child help (#1776)Brian Pursleybefore adoption22b6179
lines 1732–1733why, one step back1732 // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag1733 if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1734–1742why, one step back1734 c.lflags.AddFlag(f)1735 }1736 }1737 c.Flags().VisitAll(addToLocal)1738 c.PersistentFlags().VisitAll(addToLocal)1739 return c.lflags1740}17411742// InheritedFlags returns all flags which were inherited from parent commands.flags: clarify documentation that LocalFlags related function do not modify the state (#2064)Dmytro Milinevskyibefore adoption4fb0a66
line 1743why, one step back1743// This function does not modify the flags of the current command, it's purpose is to return the current state.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1744–1747why, one step back1744func (c *Command) InheritedFlags() *flag.FlagSet {1745 c.mergePersistentFlags()17461747 if c.iflags == nil {Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1748why, one step back1748 c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1749–1768why, one step back1749 if c.flagErrorBuf == nil {1750 c.flagErrorBuf = new(bytes.Buffer)1751 }1752 c.iflags.SetOutput(c.flagErrorBuf)1753 }17541755 local := c.LocalFlags()1756 if c.globNormFunc != nil {1757 c.iflags.SetNormalizeFunc(c.globNormFunc)1758 }17591760 c.parentsPflags.VisitAll(func(f *flag.Flag) {1761 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1762 c.iflags.AddFlag(f)1763 }1764 })1765 return c.iflags1766}17671768// NonInheritedFlags returns all flags which were not inherited from parent commands.flags: clarify documentation that LocalFlags related function do not modify the state (#2064)Dmytro Milinevskyibefore adoption4fb0a66
line 1769why, one step back1769// This function does not modify the flags of the current command, it's purpose is to return the current state.Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1770–1776why, one step back1770func (c *Command) NonInheritedFlags() *flag.FlagSet {1771 return c.LocalFlags()1772}17731774// PersistentFlags returns the persistent FlagSet specifically set in the current command.1775func (c *Command) PersistentFlags() *flag.FlagSet {1776 if c.pflags == nil {Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1777why, one step back1777 c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1778–1789why, one step back1778 if c.flagErrorBuf == nil {1779 c.flagErrorBuf = new(bytes.Buffer)1780 }1781 c.pflags.SetOutput(c.flagErrorBuf)1782 }1783 return c.pflags1784}17851786// ResetFlags deletes all flags from command.1787func (c *Command) ResetFlags() {1788 c.flagErrorBuf = new(bytes.Buffer)1789 c.flagErrorBuf.Reset()Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1790why, one step back1790 c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
line 1791why, one step back1791 c.flags.SetOutput(c.flagErrorBuf)Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1792why, one step back1792 c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1793–1879why, one step back1793 c.pflags.SetOutput(c.flagErrorBuf)17941795 c.lflags = nil1796 c.iflags = nil1797 c.parentsPflags = nil1798}17991800// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1801func (c *Command) HasFlags() bool {1802 return c.Flags().HasFlags()1803}18041805// HasPersistentFlags checks if the command contains persistent flags.1806func (c *Command) HasPersistentFlags() bool {1807 return c.PersistentFlags().HasFlags()1808}18091810// HasLocalFlags checks if the command has flags specifically declared locally.1811func (c *Command) HasLocalFlags() bool {1812 return c.LocalFlags().HasFlags()1813}18141815// HasInheritedFlags checks if the command has flags inherited from its parent command.1816func (c *Command) HasInheritedFlags() bool {1817 return c.InheritedFlags().HasFlags()1818}18191820// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1821// structure) which are not hidden or deprecated.1822func (c *Command) HasAvailableFlags() bool {1823 return c.Flags().HasAvailableFlags()1824}18251826// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1827func (c *Command) HasAvailablePersistentFlags() bool {1828 return c.PersistentFlags().HasAvailableFlags()1829}18301831// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1832// or deprecated.1833func (c *Command) HasAvailableLocalFlags() bool {1834 return c.LocalFlags().HasAvailableFlags()1835}18361837// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1838// not hidden or deprecated.1839func (c *Command) HasAvailableInheritedFlags() bool {1840 return c.InheritedFlags().HasAvailableFlags()1841}18421843// Flag climbs up the command tree looking for matching flag.1844func (c *Command) Flag(name string) (flag *flag.Flag) {1845 flag = c.Flags().Lookup(name)18461847 if flag == nil {1848 flag = c.persistentFlag(name)1849 }18501851 return1852}18531854// Recursively find matching persistent flag.1855func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1856 if c.HasPersistentFlags() {1857 flag = c.PersistentFlags().Lookup(name)1858 }18591860 if flag == nil {1861 c.updateParentsPflags()1862 flag = c.parentsPflags.Lookup(name)1863 }1864 return1865}18661867// ParseFlags parses persistent flag tree and local flags.1868func (c *Command) ParseFlags(args []string) error {1869 if c.DisableFlagParsing {1870 return nil1871 }18721873 if c.flagErrorBuf == nil {1874 c.flagErrorBuf = new(bytes.Buffer)1875 }1876 beforeErrorBufLen := c.flagErrorBuf.Len()1877 c.mergePersistentFlags()18781879 // do it here after merging all flags and just before parseBump pflag to 1.0.8 (#2303)Tomas Aschanbefore adoption51d6751
line 1880why, one step back1880 c.Flags().ParseErrorsAllowlist = flag.ParseErrorsAllowlist(c.FParseErrWhitelist)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1881–1908why, one step back18811882 err := c.Flags().Parse(args)1883 // Print warnings if they occurred (e.g. deprecated flag messages).1884 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1885 c.Print(c.flagErrorBuf.String())1886 }18871888 return err1889}18901891// Parent returns a commands parent command.1892func (c *Command) Parent() *Command {1893 return c.parent1894}18951896// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1897// and adds missing persistent flags of all parents.1898func (c *Command) mergePersistentFlags() {1899 c.updateParentsPflags()1900 c.Flags().AddFlagSet(c.PersistentFlags())1901 c.Flags().AddFlagSet(c.parentsPflags)1902}19031904// updateParentsPflags updates c.parentsPflags by adding1905// new persistent flags of all parents.1906// If c.parentsPflags == nil, it makes new.1907func (c *Command) updateParentsPflags() {1908 if c.parentsPflags == nil {Fix --version help and output for plugins (#2180)Nir Sofferbefore adoption5bef9d8
line 1909why, one step back1909 c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)Add Polygon Edge as a project using Cobra (#1672)Miloš Živkovićbefore adoption89d7b83
lines 1910–1922why, one step back1910 c.parentsPflags.SetOutput(c.flagErrorBuf)1911 c.parentsPflags.SortFlags = false1912 }19131914 if c.globNormFunc != nil {1915 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1916 }19171918 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)19191920 c.VisitParents(func(parent *Command) {1921 c.parentsPflags.AddFlagSet(parent.PersistentFlags())1922 })Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184
lines 1923–1933why, one step back1923}19241925// commandNameMatches checks if two command names are equal1926// taking into account case sensitivity according to1927// EnableCaseInsensitive global configuration.1928func commandNameMatches(s string, t string) bool {1929 if EnableCaseInsensitive {1930 return strings.EqualFold(s, t)1931 }19321933 return s == tAllow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 1934–1941why, one step back1934}19351936// tmplFunc holds a template and a function that will execute said template.1937type tmplFunc struct {1938 tmpl string1939 fn func(io.Writer, interface{}) error1940}1941refactor: replace several vars with consts (#2328)htoyoda18before adoption117698a
line 1942why, one step back1942const defaultUsageTemplate = `Usage:{{if .Runnable}}Allow linker to perform deadcode elimination for program using Cobra (#1956)Alessandro Arzillibefore adoption611e16c
lines 1943–2027why, one step back1943 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}1944 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}19451946Aliases:1947 {{.NameAndAliases}}{{end}}{{if .HasExample}}19481949Examples:1950{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}19511952Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}1953 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}19541955{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}1956 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}19571958Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}1959 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}19601961Flags:1962{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}19631964Global Flags:1965{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}19661967Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}1968 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}19691970Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}1971`19721973// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync.1974func defaultUsageFunc(w io.Writer, in interface{}) error {1975 c := in.(*Command)1976 fmt.Fprint(w, "Usage:")1977 if c.Runnable() {1978 fmt.Fprintf(w, "\n %s", c.UseLine())1979 }1980 if c.HasAvailableSubCommands() {1981 fmt.Fprintf(w, "\n %s [command]", c.CommandPath())1982 }1983 if len(c.Aliases) > 0 {1984 fmt.Fprintf(w, "\n\nAliases:\n")1985 fmt.Fprintf(w, " %s", c.NameAndAliases())1986 }1987 if c.HasExample() {1988 fmt.Fprintf(w, "\n\nExamples:\n")1989 fmt.Fprintf(w, "%s", c.Example)1990 }1991 if c.HasAvailableSubCommands() {1992 cmds := c.Commands()1993 if len(c.Groups()) == 0 {1994 fmt.Fprintf(w, "\n\nAvailable Commands:")1995 for _, subcmd := range cmds {1996 if subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName {1997 fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)1998 }1999 }2000 } else {The first 2,000 of 2,072 lines.