Skip to content
Myr

command.go

This file

Path

command.go

1,517 lines · 41.8 KiB · Go

Last changed by

Add support for ignoring parse errors (#662)Rajat Jindalbefore adoption4dab30c

History of this file

Take it

The walk stopped after 200 commits: lines older than 9495bc0 point at it.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1–13why, one step back
1// Copyright © 2013 Steve Francia <spf@spf13.com>.
2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.13

Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41

lines 14–15why, one step back
14// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
15// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 16–29why, one step back
16package cobra
1718import (19 "bytes"20 "fmt"21 "io"22 "os"23 "path/filepath"24 "sort"25 "strings"2627 flag "github.com/spf13/pflag"28)29

Add support for ignoring parse errors (#662)Rajat Jindalbefore adoption4dab30c

lines 30–32why, one step back
30// FParseErrWhitelist configures Flag parse errors to be ignored
31type FParseErrWhitelist flag.ParseErrorsWhitelist32

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 33why, one step back
33// Command is just that, a command for your application.

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 34why, one step back
34// E.g. 'go run ...' - 'run' is the command. Cobra requires

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 35–37why, one step back
35// you to define the usage and description as part of your command
36// definition to ensure usability.37type Command struct {

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 38why, one step back
38 // Use is the one-line usage message.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 39why, one step back
39 Use string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 40why, one step back
40

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 41why, one step back
41 // Aliases is an array of aliases that can be used instead of the first word in Use.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 42why, one step back
42 Aliases []string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 43why, one step back
43

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 44–45why, one step back
44 // SuggestFor is an array of command names for which this command will be suggested -
45 // similar to aliases but only suggests.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 46why, one step back
46 SuggestFor []string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 47why, one step back
47

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 48why, one step back
48 // Short is the short description shown in the 'help' output.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 49why, one step back
49 Short string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 50why, one step back
50

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 51why, one step back
51 // Long is the long message shown in the 'help <this-command>' output.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 52why, one step back
52 Long string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 53why, one step back
53

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 54why, one step back
54 // Example is examples of how to use the command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 55why, one step back
55 Example string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 56why, one step back
56

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 57why, one step back
57 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 58why, one step back
58 ValidArgs []string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 59why, one step back
59

Update documentationAlbert Nigmatzianovbefore adoption1723331

lines 60–62why, one step back
60 // Expected arguments
61 Args PositionalArgs62

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 63–65why, one step back
63 // ArgAliases is List of aliases for ValidArgs.
64 // These are not suggested to the user in the bash completion,65 // but accepted if entered manually.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 66why, one step back
66 ArgAliases []string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 67why, one step back
67

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 68why, one step back
68 // BashCompletionFunction is custom functions used by the bash autocompletion generator.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 69why, one step back
69 BashCompletionFunction string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 70why, one step back
70

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

line 71why, one step back
71 // Deprecated defines, if this command is deprecated and should print this string when used.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 72why, one step back
72 Deprecated string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 73why, one step back
73

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

line 74why, one step back
74 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 75why, one step back
75 Hidden bool

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 76why, one step back
76

Add a tags field for user defined tags on a Command. (#359)Daniel Nephinbefore adoption99600f6

line 77why, one step back
77 // Annotations are key/value pairs that can be used by applications to identify or

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 78why, one step back
78 // group commands.

Add a tags field for user defined tags on a Command. (#359)Daniel Nephinbefore adoption99600f6

line 79why, one step back
79 Annotations map[string]string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 80why, one step back
80

Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce

lines 81–85why, one step back
81 // Version defines the version for this command. If this value is non-empty and the command does not
82 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,83 // will print content of the "Version" variable.84 Version string85

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 86–91why, one step back
86 // The *Run functions are executed in the following order:
87 // * PersistentPreRun()88 // * PreRun()89 // * Run()90 // * PostRun()91 // * PersistentPostRun()

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 92why, one step back
92 // All functions get the same args, the arguments after the command name.

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 93why, one step back
93 //

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 94why, one step back
94 // PersistentPreRun: children of this command will inherit and execute.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 95why, one step back
95 PersistentPreRun func(cmd *Command, args []string)

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 96why, one step back
96 // PersistentPreRunE: PersistentPreRun but returns an error.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 97–99why, one step back
97 PersistentPreRunE func(cmd *Command, args []string) error
98 // PreRun: children of this command will not inherit.99 PreRun func(cmd *Command, args []string)

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 100why, one step back
100 // PreRunE: PreRun but returns an error.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 101why, one step back
101 PreRunE func(cmd *Command, args []string) error

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 102why, one step back
102 // Run: Typically the actual work function. Most commands will only implement this.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 103why, one step back
103 Run func(cmd *Command, args []string)

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 104why, one step back
104 // RunE: Run but returns an error.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 105–107why, one step back
105 RunE func(cmd *Command, args []string) error
106 // PostRun: run after the Run command.107 PostRun func(cmd *Command, args []string)

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 108why, one step back
108 // PostRunE: PostRun but returns an error.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 109why, one step back
109 PostRunE func(cmd *Command, args []string) error

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 110why, one step back
110 // PersistentPostRun: children of this command will inherit and execute after PostRun.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 111why, one step back
111 PersistentPostRun func(cmd *Command, args []string)

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 112why, one step back
112 // PersistentPostRunE: PersistentPostRun but returns an error.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 113why, one step back
113 PersistentPostRunE func(cmd *Command, args []string) error

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

lines 114–120why, one step back
114
115 // SilenceErrors is an option to quiet errors down stream.116 SilenceErrors bool117118 // SilenceUsage is an option to silence usage when an error occurs.119 SilenceUsage bool120

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 121–123why, one step back
121 // DisableFlagParsing disables the flag parsing.
122 // If this is true all flags will be passed to the command as arguments.123 DisableFlagParsing bool

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 124why, one step back
124

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 125–126why, one step back
125 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
126 // will be printed by generating docs for this command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 127why, one step back
127 DisableAutoGenTag bool

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 128why, one step back
128

Disable flags in UseLine (#552)Daniel Nephinbefore adoption34ceca5

lines 129–132why, one step back
129 // DisableFlagsInUseLine will disable the addition of [flags] to the usage
130 // line of a command when printing help or generating docs131 DisableFlagsInUseLine bool132

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 133–139why, one step back
133 // DisableSuggestions disables the suggestions based on Levenshtein distance
134 // that go along with 'unknown command' messages.135 DisableSuggestions bool136 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.137 // Must be > 0.138 SuggestionsMinimumDistance int139

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 140–142why, one step back
140 // TraverseChildren parses flags on all parents before executing child command.
141 TraverseChildren bool142

Add support for ignoring parse errors (#662)Rajat Jindalbefore adoption4dab30c

lines 143–145why, one step back
143 //FParseErrWhitelist flag parse errors to be ignored
144 FParseErrWhitelist FParseErrWhitelist145

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 146why, one step back
146 // commands is the list of commands supported by this program.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 147why, one step back
147 commands []*Command

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

line 148why, one step back
148 // parent is a parent command for this command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 149why, one step back
149 parent *Command

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 150why, one step back
150 // Max lengths of commands' string lengths for use in padding.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 151–153why, one step back
151 commandsMaxUseLen int
152 commandsMaxCommandPathLen int153 commandsMaxNameLen int

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

line 154why, one step back
154 // commandsAreSorted defines, if command slice are sorted or not.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 155why, one step back
155 commandsAreSorted bool

Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983

lines 156–160why, one step back
156 // commandCalledAs is the name or alias value used to call this command.
157 commandCalledAs struct {158 name string159 called bool160 }

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

line 161why, one step back
161

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 162–163why, one step back
162 // args is actual args parsed from flags.
163 args []string

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

lines 164–179why, one step back
164 // flagErrorBuf contains all error messages from pflag.
165 flagErrorBuf *bytes.Buffer166 // flags is full set of flags.167 flags *flag.FlagSet168 // pflags contains persistent flags.169 pflags *flag.FlagSet170 // lflags contains local flags.171 lflags *flag.FlagSet172 // iflags contains inherited flags.173 iflags *flag.FlagSet174 // parentsPflags is all persistent flags of cmd's parents.175 parentsPflags *flag.FlagSet176 // globNormFunc is the global normalization function177 // that we can use on every pflag set and children commands178 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName179

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 180–187why, one step back
180 // output is an output writer defined by user.
181 output io.Writer182 // usageFunc is usage func defined by user.183 usageFunc func(*Command) error184 // usageTemplate is usage template defined by user.185 usageTemplate string186 // flagErrorFunc is func defined by user and it's called when the parsing of187 // flags returns an error.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 188why, one step back
188 flagErrorFunc func(*Command, error) error

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 189–192why, one step back
189 // helpTemplate is help template defined by user.
190 helpTemplate string191 // helpFunc is help func defined by user.192 helpFunc func(*Command, []string)

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

line 193why, one step back
193 // helpCommand is command with usage 'help'. If it's not defined by user,

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 194–195why, one step back
194 // cobra uses default help command.
195 helpCommand *Command

Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce

lines 196–197why, one step back
196 // versionTemplate is the version template defined by user.
197 versionTemplate string

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 198–199why, one step back
198}
199

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 200why, one step back
200// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 201–208why, one step back
201// particularly useful when testing.
202func (c *Command) SetArgs(a []string) {203 c.args = a204}205206// SetOutput sets the destination for usage and error messages.207// If output is nil, os.Stderr is used.208func (c *Command) SetOutput(output io.Writer) {

Avoid storing pointer to nil (#411)Tamir Dubersteinbefore adoption7aeaa2c

line 209why, one step back
209 c.output = output

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 210–211why, one step back
210}
211

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 212why, one step back
212// SetUsageFunc sets usage function. Usage can be defined by application.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 213–216why, one step back
213func (c *Command) SetUsageFunc(f func(*Command) error) {
214 c.usageFunc = f215}216

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 217why, one step back
217// SetUsageTemplate sets usage template. Can be defined by Application.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 218–222why, one step back
218func (c *Command) SetUsageTemplate(s string) {
219 c.usageTemplate = s220}221222// SetFlagErrorFunc sets a function to generate an error when flag parsing

Some fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a

line 223why, one step back
223// fails.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 224–227why, one step back
224func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
225 c.flagErrorFunc = f226}227

Some fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a

line 228why, one step back
228// SetHelpFunc sets help function. Can be defined by Application.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 229–232why, one step back
229func (c *Command) SetHelpFunc(f func(*Command, []string)) {
230 c.helpFunc = f231}232

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 233why, one step back
233// SetHelpCommand sets help command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 234–237why, one step back
234func (c *Command) SetHelpCommand(cmd *Command) {
235 c.helpCommand = cmd236}237

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 238why, one step back
238// SetHelpTemplate sets help template to be used. Application can use it to set custom template.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 239–242why, one step back
239func (c *Command) SetHelpTemplate(s string) {
240 c.helpTemplate = s241}242

Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce

lines 243–247why, one step back
243// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
244func (c *Command) SetVersionTemplate(s string) {245 c.versionTemplate = s246}247

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 248–259why, one step back
248// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
249// The user should not have a cyclic dependency on commands.250func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {251 c.Flags().SetNormalizeFunc(n)252 c.PersistentFlags().SetNormalizeFunc(n)253 c.globNormFunc = n254255 for _, command := range c.commands {256 command.SetGlobalNormalizationFunc(n)257 }258}259

Some fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a

line 260why, one step back
260// OutOrStdout returns output to stdout.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 261–264why, one step back
261func (c *Command) OutOrStdout() io.Writer {
262 return c.getOut(os.Stdout)263}264

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 265why, one step back
265// OutOrStderr returns output to stderr

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 266–271why, one step back
266func (c *Command) OutOrStderr() io.Writer {
267 return c.getOut(os.Stderr)268}269270func (c *Command) getOut(def io.Writer) io.Writer {271 if c.output != nil {

Avoid storing pointer to nil (#411)Tamir Dubersteinbefore adoption7aeaa2c

line 272why, one step back
272 return c.output

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 273–286why, one step back
273 }
274 if c.HasParent() {275 return c.parent.getOut(def)276 }277 return def278}279280// UsageFunc returns either the function set by SetUsageFunc for this command281// or a parent, or it returns a default usage function.282func (c *Command) UsageFunc() (f func(*Command) error) {283 if c.usageFunc != nil {284 return c.usageFunc285 }286 if c.HasParent() {

Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777

line 287why, one step back
287 return c.Parent().UsageFunc()

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 288–308why, one step back
288 }
289 return func(c *Command) error {290 c.mergePersistentFlags()291 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)292 if err != nil {293 c.Println(err)294 }295 return err296 }297}298299// Usage puts out the usage for the command.300// Used when a user provides invalid input.301// Can be defined by user by overriding UsageFunc.302func (c *Command) Usage() error {303 return c.UsageFunc()(c)304}305306// HelpFunc returns either the function set by SetHelpFunc for this command307// or a parent, or it returns a function with default help behavior.308func (c *Command) HelpFunc() func(*Command, []string) {

Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777

lines 309–310why, one step back
309 if c.helpFunc != nil {
310 return c.helpFunc

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 311why, one step back
311 }

Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777

lines 312–315why, one step back
312 if c.HasParent() {
313 return c.Parent().HelpFunc()314 }315 return func(c *Command, a []string) {

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 316–331why, one step back
316 c.mergePersistentFlags()
317 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)318 if err != nil {319 c.Println(err)320 }321 }322}323324// Help puts out the help for the command.325// Used when a user calls help [command].326// Can be defined by user by overriding HelpFunc.327func (c *Command) Help() error {328 c.HelpFunc()(c, []string{})329 return nil330}331

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 332why, one step back
332// UsageString return usage string.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 333–359why, one step back
333func (c *Command) UsageString() string {
334 tmpOutput := c.output335 bb := new(bytes.Buffer)336 c.SetOutput(bb)337 c.Usage()338 c.output = tmpOutput339 return bb.String()340}341342// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this343// command or a parent, or it returns a function which returns the original344// error.345func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {346 if c.flagErrorFunc != nil {347 return c.flagErrorFunc348 }349350 if c.HasParent() {351 return c.parent.FlagErrorFunc()352 }353 return func(c *Command, err error) error {354 return err355 }356}357358var minUsagePadding = 25359

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 360why, one step back
360// UsagePadding return padding for the usage.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 361–369why, one step back
361func (c *Command) UsagePadding() int {
362 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {363 return minUsagePadding364 }365 return c.parent.commandsMaxUseLen366}367368var minCommandPathPadding = 11369

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 370why, one step back
370// CommandPathPadding return padding for the command path.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 371–379why, one step back
371func (c *Command) CommandPathPadding() int {
372 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {373 return minCommandPathPadding374 }375 return c.parent.commandsMaxCommandPathLen376}377378var minNamePadding = 11379

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 380why, one step back
380// NamePadding returns padding for the name.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 381–387why, one step back
381func (c *Command) NamePadding() int {
382 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {383 return minNamePadding384 }385 return c.parent.commandsMaxNameLen386}387

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 388why, one step back
388// UsageTemplate returns usage template for the command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 389–397why, one step back
389func (c *Command) UsageTemplate() string {
390 if c.usageTemplate != "" {391 return c.usageTemplate392 }393394 if c.HasParent() {395 return c.parent.UsageTemplate()396 }397 return `Usage:{{if .Runnable}}

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 398–399why, one step back
398 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
399 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 400–401why, one step back
400
401Aliases:

Keep only one newline between Aliases and Flags in help (#410)Albert Nigmatzianovbefore adoption9350054

line 402why, one step back
402 {{.NameAndAliases}}{{end}}{{if .HasExample}}

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 403–404why, one step back
403
404Examples:

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 405why, one step back
405{{.Example}}{{end}}{{if .HasAvailableSubCommands}}

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 406why, one step back
406

Some fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a

lines 407–408why, one step back
407Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
408 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 409–410why, one step back
409
410Flags:

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 411why, one step back
411{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 412–413why, one step back
412
413Global Flags:

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 414why, one step back
414{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 415why, one step back
415

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

line 416why, one step back
416Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}

Some fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a

line 417why, one step back
417 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 418–422why, one step back
418
419Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}420`421}422

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 423why, one step back
423// HelpTemplate return help template for the command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 424–431why, one step back
424func (c *Command) HelpTemplate() string {
425 if c.helpTemplate != "" {426 return c.helpTemplate427 }428429 if c.HasParent() {430 return c.parent.HelpTemplate()431 }

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 432why, one step back
432 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 433–436why, one step back
433
434{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`435}436

Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce

lines 437–449why, one step back
437// VersionTemplate return version template for the command.
438func (c *Command) VersionTemplate() string {439 if c.versionTemplate != "" {440 return c.versionTemplate441 }442443 if c.HasParent() {444 return c.parent.VersionTemplate()445 }446 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}447`448}449

Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41

lines 450–451why, one step back
450func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
451 flag := fs.Lookup(name)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 452–454why, one step back
452 if flag == nil {
453 return false454 }

Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6

line 455why, one step back
455 return flag.NoOptDefVal != ""

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 456–457why, one step back
456}
457

Fix subcommand locations with NoOptDefValue flags (#391)Eric Parisbefore adoption92ea23a

line 458why, one step back
458func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {

Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41

lines 459–467why, one step back
459 if len(name) == 0 {
460 return false461 }462463 flag := fs.ShorthandLookup(name[:1])464 if flag == nil {465 return false466 }467 return flag.NoOptDefVal != ""

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 468–470why, one step back
468}
469470func stripFlags(args []string, c *Command) []string {

Simplify stripFlags functionAlbert Nigmatzianovbefore adoption9890b7b

line 471why, one step back
471 if len(args) == 0 {

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 472–476why, one step back
472 return args
473 }474 c.mergePersistentFlags()475476 commands := []string{}

Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6

line 477why, one step back
477 flags := c.Flags()

Simplify stripFlags functionAlbert Nigmatzianovbefore adoption9890b7b

lines 478–481why, one step back
478
479Loop:480 for len(args) > 0 {481 s := args[0]

Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6

line 482why, one step back
482 args = args[1:]

Fix tests so they give correct args (#445)Albert Nigmatzianovbefore adoption51b7cf5

line 483why, one step back
483 switch {

Terminate the stripping of flags when -- is found (#649)Di Xubefore adoptionc439c4f

lines 484–486why, one step back
484 case s == "--":
485 // "--" terminates the flags486 break Loop

Fix tests so they give correct args (#445)Albert Nigmatzianovbefore adoption51b7cf5

lines 487–498why, one step back
487 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
488 // If '--flag arg' then489 // delete arg from args.490 fallthrough // (do the same as below)491 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):492 // If '-f arg' then493 // delete 'arg' from args or break the loop if len(args) <= 1.494 if len(args) <= 1 {495 break Loop496 } else {497 args = args[1:]498 continue

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 499why, one step back
499 }

Fix tests so they give correct args (#445)Albert Nigmatzianovbefore adoption51b7cf5

lines 500–501why, one step back
500 case s != "" && !strings.HasPrefix(s, "-"):
501 commands = append(commands, s)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 502–521why, one step back
502 }
503 }504505 return commands506}507508// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like509// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).510func argsMinusFirstX(args []string, x string) []string {511 for i, y := range args {512 if x == y {513 ret := []string{}514 ret = append(ret, args[:i]...)515 ret = append(ret, args[i+1:]...)516 return ret517 }518 }519 return args520}521

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 522–526why, one step back
522func isFlagArg(arg string) bool {
523 return ((len(arg) >= 3 && arg[1] == '-') ||524 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))525}526

Add a tags field for user defined tags on a Command. (#359)Daniel Nephinbefore adoption99600f6

line 527why, one step back
527// Find the target command given the args and command tree

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 528–538why, one step back
528// Meant to be run on the highest node. Only searches down.
529func (c *Command) Find(args []string) (*Command, []string, error) {530 var innerfind func(*Command, []string) (*Command, []string)531532 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {533 argsWOflags := stripFlags(innerArgs, c)534 if len(argsWOflags) == 0 {535 return c, innerArgs536 }537 nextSubCmd := argsWOflags[0]538

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 539–541why, one step back
539 cmd := c.findNext(nextSubCmd)
540 if cmd != nil {541 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 542–546why, one step back
542 }
543 return c, innerArgs544 }545546 commandFound, a := innerfind(c, args)

Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9

lines 547–548why, one step back
547 if commandFound.Args == nil {
548 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 549–550why, one step back
549 }
550 return commandFound, a, nil

Allow commands to explicitly state if they do, or do not take arbitrary argumentsEric Parisbefore adoptiond89c499

lines 551–552why, one step back
551}
552

Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9

line 553why, one step back
553func (c *Command) findSuggestions(arg string) string {

Allow commands to explicitly state if they do, or do not take arbitrary argumentsEric Parisbefore adoptiond89c499

lines 554–560why, one step back
554 if c.DisableSuggestions {
555 return ""556 }557 if c.SuggestionsMinimumDistance <= 0 {558 c.SuggestionsMinimumDistance = 2559 }560 suggestionsString := ""

Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9

line 561why, one step back
561 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {

Allow commands to explicitly state if they do, or do not take arbitrary argumentsEric Parisbefore adoptiond89c499

lines 562–567why, one step back
562 suggestionsString += "\n\nDid you mean this?\n"
563 for _, s := range suggestions {564 suggestionsString += fmt.Sprintf("\t%v\n", s)565 }566 }567 return suggestionsString

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 568–569why, one step back
568}
569

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 570–573why, one step back
570func (c *Command) findNext(next string) *Command {
571 matches := make([]*Command, 0)572 for _, cmd := range c.commands {573 if cmd.Name() == next || cmd.HasAlias(next) {

Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983

line 574why, one step back
574 cmd.commandCalledAs.name = next

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 575–584why, one step back
575 return cmd
576 }577 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {578 matches = append(matches, cmd)579 }580 }581582 if len(matches) == 1 {583 return matches[0]584 }

Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983

line 585why, one step back
585

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 586–631why, one step back
586 return nil
587}588589// Traverse the command tree to find the command, and parse args for590// each parent.591func (c *Command) Traverse(args []string) (*Command, []string, error) {592 flags := []string{}593 inFlag := false594595 for i, arg := range args {596 switch {597 // A long flag with a space separated value598 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):599 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'600 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())601 flags = append(flags, arg)602 continue603 // A short flag with a space separated value604 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):605 inFlag = true606 flags = append(flags, arg)607 continue608 // The value for a flag609 case inFlag:610 inFlag = false611 flags = append(flags, arg)612 continue613 // A flag without a value, or with an `=` separated value614 case isFlagArg(arg):615 flags = append(flags, arg)616 continue617 }618619 cmd := c.findNext(arg)620 if cmd == nil {621 return c, args, nil622 }623624 if err := c.ParseFlags(flags); err != nil {625 return nil, args, err626 }627 return cmd.Traverse(args[i+1:])628 }629 return c, args, nil630}631

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 632why, one step back
632// SuggestionsFor provides suggestions for the typedName.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 633–652why, one step back
633func (c *Command) SuggestionsFor(typedName string) []string {
634 suggestions := []string{}635 for _, cmd := range c.commands {636 if cmd.IsAvailableCommand() {637 levenshteinDistance := ld(typedName, cmd.Name(), true)638 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance639 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))640 if suggestByLevenshtein || suggestByPrefix {641 suggestions = append(suggestions, cmd.Name())642 }643 for _, explicitSuggestion := range cmd.SuggestFor {644 if strings.EqualFold(typedName, explicitSuggestion) {645 suggestions = append(suggestions, cmd.Name())646 }647 }648 }649 }650 return suggestions651}652

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 653why, one step back
653// VisitParents visits all parents of the command and invokes fn on each parent.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 654why, one step back
654func (c *Command) VisitParents(fn func(*Command)) {

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 655–657why, one step back
655 if c.HasParent() {
656 fn(c.Parent())657 c.Parent().VisitParents(fn)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 658–660why, one step back
658 }
659}660

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 661why, one step back
661// Root finds root command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 662why, one step back
662func (c *Command) Root() *Command {

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 663–664why, one step back
663 if c.HasParent() {
664 return c.Parent().Root()

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 665why, one step back
665 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 666why, one step back
666 return c

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 667–668why, one step back
667}
668

Improve testsAlbert Nigmatzianovbefore adoption65c8acb

lines 669–670why, one step back
669// ArgsLenAtDash will return the length of c.Flags().Args at the moment
670// when a -- was found during args parsing.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 671–683why, one step back
671func (c *Command) ArgsLenAtDash() int {
672 return c.Flags().ArgsLenAtDash()673}674675func (c *Command) execute(a []string) (err error) {676 if c == nil {677 return fmt.Errorf("Called Execute() on a nil Command")678 }679680 if len(c.Deprecated) > 0 {681 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)682 }683

Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce

line 684why, one step back
684 // initialize help and version flag at the last point possible to allow for user

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 685why, one step back
685 // overriding

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

line 686why, one step back
686 c.InitDefaultHelpFlag()

Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce

line 687why, one step back
687 c.InitDefaultVersionFlag()

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 688–692why, one step back
688
689 err = c.ParseFlags(a)690 if err != nil {691 return c.FlagErrorFunc()(c, err)692 }

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

lines 693–694why, one step back
693
694 // If help is called, regardless of other flags, return we want help.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 695–698why, one step back
695 // Also say we need help if the command isn't runnable.
696 helpVal, err := c.Flags().GetBool("help")697 if err != nil {698 // should be impossible to get here as we always declare a help

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

line 699why, one step back
699 // flag in InitDefaultHelpFlag()

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 700–703why, one step back
700 c.Println("\"help\" flag declared as non-bool. Please correct your code")
701 return err702 }703

Ensure that '--version' flag works properly for root command (#595)Nick Miyakebefore adoptionccaecb1

line 704why, one step back
704 if helpVal {

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 705–707why, one step back
705 return flag.ErrHelp
706 }707

Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce

lines 708–721why, one step back
708 // for back-compat, only add version flag behavior if version is defined
709 if c.Version != "" {710 versionVal, err := c.Flags().GetBool("version")711 if err != nil {712 c.Println("\"version\" flag declared as non-bool. Please correct your code")713 return err714 }715 if versionVal {716 err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)717 if err != nil {718 c.Println(err)719 }720 return err721 }

Ensure that '--version' flag works properly for root command (#595)Nick Miyakebefore adoptionccaecb1

lines 722–725why, one step back
722 }
723724 if !c.Runnable() {725 return flag.ErrHelp

Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce

lines 726–727why, one step back
726 }
727

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 728–734why, one step back
728 c.preRun()
729730 argWoFlags := c.Flags().Args()731 if c.DisableFlagParsing {732 argWoFlags = a733 }734

Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9

lines 735–738why, one step back
735 if err := c.ValidateArgs(argWoFlags); err != nil {
736 return err737 }738

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 739–757why, one step back
739 for p := c; p != nil; p = p.Parent() {
740 if p.PersistentPreRunE != nil {741 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {742 return err743 }744 break745 } else if p.PersistentPreRun != nil {746 p.PersistentPreRun(c, argWoFlags)747 break748 }749 }750 if c.PreRunE != nil {751 if err := c.PreRunE(c, argWoFlags); err != nil {752 return err753 }754 } else if c.PreRun != nil {755 c.PreRun(c, argWoFlags)756 }757

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 758–760why, one step back
758 if err := c.validateRequiredFlags(); err != nil {
759 return err760 }

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 761–795why, one step back
761 if c.RunE != nil {
762 if err := c.RunE(c, argWoFlags); err != nil {763 return err764 }765 } else {766 c.Run(c, argWoFlags)767 }768 if c.PostRunE != nil {769 if err := c.PostRunE(c, argWoFlags); err != nil {770 return err771 }772 } else if c.PostRun != nil {773 c.PostRun(c, argWoFlags)774 }775 for p := c; p != nil; p = p.Parent() {776 if p.PersistentPostRunE != nil {777 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {778 return err779 }780 break781 } else if p.PersistentPostRun != nil {782 p.PersistentPostRun(c, argWoFlags)783 break784 }785 }786787 return nil788}789790func (c *Command) preRun() {791 for _, x := range initializers {792 x()793 }794}795

Fix typosAlbert Nigmatzianovbefore adoptione606913

line 796why, one step back
796// Execute uses the args (os.Args[1:] by default)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 797–803why, one step back
797// and run through the command tree finding appropriate matches
798// for commands and then corresponding flags.799func (c *Command) Execute() error {800 _, err := c.ExecuteC()801 return err802}803

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 804why, one step back
804// ExecuteC executes the command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 805–817why, one step back
805func (c *Command) ExecuteC() (cmd *Command, err error) {
806 // Regardless of what command execute is called on, run on Root only807 if c.HasParent() {808 return c.Root().ExecuteC()809 }810811 // windows hook812 if preExecHookFn != nil {813 preExecHookFn(c)814 }815816 // initialize help as the last point possible to allow for user817 // overriding

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

line 818why, one step back
818 c.InitDefaultHelpCmd()

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 819–828why, one step back
819
820 var args []string821822 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155823 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {824 args = os.Args[1:]825 } else {826 args = c.args827 }828

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 829–834why, one step back
829 var flags []string
830 if c.TraverseChildren {831 cmd, flags, err = c.Traverse(args)832 } else {833 cmd, flags, err = c.Find(args)834 }

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 835–845why, one step back
835 if err != nil {
836 // If found parse to a subcommand and then failed, talk about the subcommand837 if cmd != nil {838 c = cmd839 }840 if !c.SilenceErrors {841 c.Println("Error:", err.Error())842 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())843 }844 return c, err845 }

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

line 846why, one step back
846

Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983

lines 847–851why, one step back
847 cmd.commandCalledAs.called = true
848 if cmd.commandCalledAs.name == "" {849 cmd.commandCalledAs.name = cmd.Name()850 }851

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 852–872why, one step back
852 err = cmd.execute(flags)
853 if err != nil {854 // Always show help if requested, even if SilenceErrors is in855 // effect856 if err == flag.ErrHelp {857 cmd.HelpFunc()(cmd, args)858 return cmd, nil859 }860861 // If root command has SilentErrors flagged,862 // all subcommands should respect it863 if !cmd.SilenceErrors && !c.SilenceErrors {864 c.Println("Error:", err.Error())865 }866867 // If root command has SilentUsage flagged,868 // all subcommands should respect it869 if !cmd.SilenceUsage && !c.SilenceUsage {870 c.Println(cmd.UsageString())871 }872 }

Fix typosAlbert Nigmatzianovbefore adoptione606913

line 873why, one step back
873 return cmd, err

Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9

lines 874–880why, one step back
874}
875876func (c *Command) ValidateArgs(args []string) error {877 if c.Args == nil {878 return nil879 }880 return c.Args(c, args)

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 881–896why, one step back
881}
882883func (c *Command) validateRequiredFlags() error {884 flags := c.Flags()885 missingFlagNames := []string{}886 flags.VisitAll(func(pflag *flag.Flag) {887 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]888 if !found {889 return890 }891 if (requiredAnnotation[0] == "true") && !pflag.Changed {892 missingFlagNames = append(missingFlagNames, pflag.Name)893 }894 })895896 if len(missingFlagNames) > 0 {

Update error message for missing required flags (#580)Nick Miyakebefore adoption19e54c4

line 897why, one step back
897 return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 898–899why, one step back
898 }
899 return nil

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 900–901why, one step back
900}
901

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

lines 902–903why, one step back
902// InitDefaultHelpFlag adds default help flag to c.
903// It is called automatically by executing the c or by calling help and usage.

Add comment for InitDefaultHelpFlagAlbert Nigmatzianovbefore adoptiond83a1d7

line 904why, one step back
904// If c already has help flag, it will do nothing.

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

line 905why, one step back
905func (c *Command) InitDefaultHelpFlag() {

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 906–907why, one step back
906 c.mergePersistentFlags()
907 if c.Flags().Lookup("help") == nil {

Initialize help flag in initHelpCmdAlbert Nigmatzianovbefore adoption867d414

lines 908–914why, one step back
908 usage := "help for "
909 if c.Name() == "" {910 usage += "this command"911 } else {912 usage += c.Name()913 }914 c.Flags().BoolP("help", "h", false, usage)

Add support for --version flag (#584)Nick Miyakebefore adoptionb1ec2ce

lines 915–935why, one step back
915 }
916}917918// InitDefaultVersionFlag adds default version flag to c.919// It is called automatically by executing the c.920// If c already has a version flag, it will do nothing.921// If c.Version is empty, it will do nothing.922func (c *Command) InitDefaultVersionFlag() {923 if c.Version == "" {924 return925 }926927 c.mergePersistentFlags()928 if c.Flags().Lookup("version") == nil {929 usage := "version for "930 if c.Name() == "" {931 usage += "this command"932 } else {933 usage += c.Name()934 }935 c.Flags().Bool("version", false, usage)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 936–938why, one step back
936 }
937}938

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

lines 939–942why, one step back
939// InitDefaultHelpCmd adds default help command to c.
940// It is called automatically by executing the c or by calling help and usage.941// If c already has help command or c has no subcommands, it will do nothing.942func (c *Command) InitDefaultHelpCmd() {

Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02

line 943why, one step back
943 if !c.HasSubCommands() {

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

lines 944–945why, one step back
944 return
945 }

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 946why, one step back
946

Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02

lines 947–951why, one step back
947 if c.helpCommand == nil {
948 c.helpCommand = &Command{949 Use: "help [command]",950 Short: "Help about any command",951 Long: `Help provides help for any command in the application.

Delete tab in the long description of helpAlbert Nigmatzianovbefore adoptiond994347

line 952why, one step back
952Simply type ` + c.Name() + ` help [path to command] for full details.`,

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 953why, one step back
953

Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02

lines 954–964why, one step back
954 Run: func(c *Command, args []string) {
955 cmd, _, e := c.Root().Find(args)956 if cmd == nil || e != nil {957 c.Printf("Unknown help topic %#q\n", args)958 c.Root().Usage()959 } else {960 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown961 cmd.Help()962 }963 },964 }

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 965why, one step back
965 }

remove help command before adding it (#399)Tamir Dubersteinbefore adoption7be4bed

line 966why, one step back
966 c.RemoveCommand(c.helpCommand)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 967–969why, one step back
967 c.AddCommand(c.helpCommand)
968}969

Edit ResetFlags and ResetCommands descriptionsAlbert Nigmatzianovbefore adoptiond6a4305

line 970why, one step back
970// ResetCommands delete parent, subcommand and help command from c.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 971why, one step back
971func (c *Command) ResetCommands() {

Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf

line 972why, one step back
972 c.parent = nil

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 973–974why, one step back
973 c.commands = nil
974 c.helpCommand = nil

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

line 975why, one step back
975 c.parentsPflags = nil

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 976–1064why, one step back
976}
977978// Sorts commands by their names.979type commandSorterByName []*Command980981func (c commandSorterByName) Len() int { return len(c) }982func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }983func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }984985// Commands returns a sorted slice of child commands.986func (c *Command) Commands() []*Command {987 // do not sort commands if it already sorted or sorting was disabled988 if EnableCommandSorting && !c.commandsAreSorted {989 sort.Sort(commandSorterByName(c.commands))990 c.commandsAreSorted = true991 }992 return c.commands993}994995// AddCommand adds one or more commands to this parent command.996func (c *Command) AddCommand(cmds ...*Command) {997 for i, x := range cmds {998 if cmds[i] == c {999 panic("Command can't be a child of itself")1000 }1001 cmds[i].parent = c1002 // update max lengths1003 usageLen := len(x.Use)1004 if usageLen > c.commandsMaxUseLen {1005 c.commandsMaxUseLen = usageLen1006 }1007 commandPathLen := len(x.CommandPath())1008 if commandPathLen > c.commandsMaxCommandPathLen {1009 c.commandsMaxCommandPathLen = commandPathLen1010 }1011 nameLen := len(x.Name())1012 if nameLen > c.commandsMaxNameLen {1013 c.commandsMaxNameLen = nameLen1014 }1015 // If global normalization function exists, update all children1016 if c.globNormFunc != nil {1017 x.SetGlobalNormalizationFunc(c.globNormFunc)1018 }1019 c.commands = append(c.commands, x)1020 c.commandsAreSorted = false1021 }1022}10231024// RemoveCommand removes one or more commands from a parent command.1025func (c *Command) RemoveCommand(cmds ...*Command) {1026 commands := []*Command{}1027main:1028 for _, command := range c.commands {1029 for _, cmd := range cmds {1030 if command == cmd {1031 command.parent = nil1032 continue main1033 }1034 }1035 commands = append(commands, command)1036 }1037 c.commands = commands1038 // recompute all lengths1039 c.commandsMaxUseLen = 01040 c.commandsMaxCommandPathLen = 01041 c.commandsMaxNameLen = 01042 for _, command := range c.commands {1043 usageLen := len(command.Use)1044 if usageLen > c.commandsMaxUseLen {1045 c.commandsMaxUseLen = usageLen1046 }1047 commandPathLen := len(command.CommandPath())1048 if commandPathLen > c.commandsMaxCommandPathLen {1049 c.commandsMaxCommandPathLen = commandPathLen1050 }1051 nameLen := len(command.Name())1052 if nameLen > c.commandsMaxNameLen {1053 c.commandsMaxNameLen = nameLen1054 }1055 }1056}10571058// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1059func (c *Command) Print(i ...interface{}) {1060 fmt.Fprint(c.OutOrStderr(), i...)1061}10621063// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1064func (c *Command) Println(i ...interface{}) {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 1065why, one step back
1065 c.Print(fmt.Sprintln(i...))

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1066–1069why, one step back
1066}
10671068// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1069func (c *Command) Printf(format string, i ...interface{}) {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 1070why, one step back
1070 c.Print(fmt.Sprintf(format, i...))

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1071–1074why, one step back
1071}
10721073// CommandPath returns the full path to this command.1074func (c *Command) CommandPath() string {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 1075–1076why, one step back
1075 if c.HasParent() {
1076 return c.Parent().CommandPath() + " " + c.Name()

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1077why, one step back
1077 }

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 1078why, one step back
1078 return c.Name()

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1079–1082why, one step back
1079}
10801081// UseLine puts out the full usage for a given command (including parents).1082func (c *Command) UseLine() string {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 1083why, one step back
1083 var useline string

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1084why, one step back
1084 if c.HasParent() {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 1085–1087why, one step back
1085 useline = c.parent.CommandPath() + " " + c.Use
1086 } else {1087 useline = c.Use

Disable flags in UseLine (#552)Daniel Nephinbefore adoption34ceca5

lines 1088–1090why, one step back
1088 }
1089 if c.DisableFlagsInUseLine {1090 return useline

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1091why, one step back
1091 }

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 1092–1095why, one step back
1092 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
1093 useline += " [flags]"1094 }1095 return useline

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1096–1097why, one step back
1096}
1097

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1098why, one step back
1098// DebugFlags used to determine which flags have been assigned to which commands

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1099–1109why, one step back
1099// and which persist.
1100func (c *Command) DebugFlags() {1101 c.Println("DebugFlags called on", c.Name())1102 var debugflags func(*Command)11031104 debugflags = func(x *Command) {1105 if x.HasFlags() || x.HasPersistentFlags() {1106 c.Println(x.Name())1107 }1108 if x.HasFlags() {1109 x.flags.VisitAll(func(f *flag.Flag) {

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1110–1111why, one step back
1110 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {
1111 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1112–1127why, one step back
1112 } else {
1113 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1114 }1115 })1116 }1117 if x.HasPersistentFlags() {1118 x.pflags.VisitAll(func(f *flag.Flag) {1119 if x.HasFlags() {1120 if x.flags.Lookup(f.Name) == nil {1121 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1122 }1123 } else {1124 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1125 }1126 })1127 }

Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8

line 1128why, one step back
1128 c.Println(x.flagErrorBuf)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1129–1140why, one step back
1129 if x.HasSubCommands() {
1130 for _, y := range x.commands {1131 debugflags(y)1132 }1133 }1134 }11351136 debugflags(c)1137}11381139// Name returns the command's name: the first word in the use line.1140func (c *Command) Name() string {

Delete name field from Command (#547)Albert Nigmatzianovbefore adoption40f1880

lines 1141–1144why, one step back
1141 name := c.Use
1142 i := strings.Index(name, " ")1143 if i >= 0 {1144 name = name[:i]

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1145why, one step back
1145 }

Delete name field from Command (#547)Albert Nigmatzianovbefore adoption40f1880

line 1146why, one step back
1146 return name

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1147–1158why, one step back
1147}
11481149// HasAlias determines if a given string is an alias of the command.1150func (c *Command) HasAlias(s string) bool {1151 for _, a := range c.Aliases {1152 if a == s {1153 return true1154 }1155 }1156 return false1157}1158

Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983

lines 1159–1167why, one step back
1159// CalledAs returns the command name or alias that was used to invoke
1160// this command or an empty string if the command has not been called.1161func (c *Command) CalledAs() string {1162 if c.commandCalledAs.called {1163 return c.commandCalledAs.name1164 }1165 return ""1166}1167

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 1168–1171why, one step back
1168// hasNameOrAliasPrefix returns true if the Name or any of aliases start
1169// with prefix1170func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1171 if strings.HasPrefix(c.Name(), prefix) {

Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983

line 1172why, one step back
1172 c.commandCalledAs.name = c.Name()

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 1173–1176why, one step back
1173 return true
1174 }1175 for _, alias := range c.Aliases {1176 if strings.HasPrefix(alias, prefix) {

Add `CalledAs` method to cobra.Command (w/ tests) (#567)Tim Peoplesbefore adoptioneb58983

line 1177why, one step back
1177 c.commandCalledAs.name = alias

Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03

lines 1178–1184why, one step back
1178 return true
1179 }1180 }1181 return false1182}11831184// NameAndAliases returns a list of the command name and all aliases

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1185–1188why, one step back
1185func (c *Command) NameAndAliases() string {
1186 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1187}1188

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1189why, one step back
1189// HasExample determines if the command has example.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1190–1221why, one step back
1190func (c *Command) HasExample() bool {
1191 return len(c.Example) > 01192}11931194// Runnable determines if the command is itself runnable.1195func (c *Command) Runnable() bool {1196 return c.Run != nil || c.RunE != nil1197}11981199// HasSubCommands determines if the command has children commands.1200func (c *Command) HasSubCommands() bool {1201 return len(c.commands) > 01202}12031204// IsAvailableCommand determines if a command is available as a non-help command1205// (this includes all non deprecated/hidden commands).1206func (c *Command) IsAvailableCommand() bool {1207 if len(c.Deprecated) != 0 || c.Hidden {1208 return false1209 }12101211 if c.HasParent() && c.Parent().helpCommand == c {1212 return false1213 }12141215 if c.Runnable() || c.HasAvailableSubCommands() {1216 return true1217 }12181219 return false1220}1221

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

lines 1222–1227why, one step back
1222// IsAdditionalHelpTopicCommand determines if a command is an additional
1223// help topic command; additional help topic command is determined by the1224// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1225// are runnable/hidden/deprecated.1226// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1227func (c *Command) IsAdditionalHelpTopicCommand() bool {

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1228–1234why, one step back
1228 // if a command is runnable, deprecated, or hidden it is not a 'help' command
1229 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1230 return false1231 }12321233 // if any non-help sub commands are found, the command is not a 'help' command1234 for _, sub := range c.commands {

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

line 1235why, one step back
1235 if !sub.IsAdditionalHelpTopicCommand() {

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1236–1249why, one step back
1236 return false
1237 }1238 }12391240 // the command either has no sub commands, or no non-help sub commands1241 return true1242}12431244// HasHelpSubCommands determines if a command has any available 'help' sub commands1245// that need to be shown in the usage/help default template under 'additional help1246// topics'.1247func (c *Command) HasHelpSubCommands() bool {1248 // return true on the first found available 'help' sub command1249 for _, sub := range c.commands {

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

line 1250why, one step back
1250 if sub.IsAdditionalHelpTopicCommand() {

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1251–1269why, one step back
1251 return true
1252 }1253 }12541255 // the command either has no sub commands, or no available 'help' sub commands1256 return false1257}12581259// HasAvailableSubCommands determines if a command has available sub commands that1260// need to be shown in the usage/help default template under 'available commands'.1261func (c *Command) HasAvailableSubCommands() bool {1262 // return true on the first found available (non deprecated/help/hidden)1263 // sub command1264 for _, sub := range c.commands {1265 if sub.IsAvailableCommand() {1266 return true1267 }1268 }1269

Fix typo (#573)Pavol Loffaybefore adoptionf634327

line 1270why, one step back
1270 // the command either has no sub commands, or no available (non deprecated/help/hidden)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1271–1279why, one step back
1271 // sub commands
1272 return false1273}12741275// HasParent determines if the command is a child command.1276func (c *Command) HasParent() bool {1277 return c.parent != nil1278}1279

fix grammatical error in command.go (#626)Shamus Taylorbefore adoption3a7eb14

line 1280why, one step back
1280// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1281–1284why, one step back
1281func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
1282 return c.globNormFunc1283}1284

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1285why, one step back
1285// Flags returns the complete FlagSet that applies

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1286–1289why, one step back
1286// to this command (local and persistent declared here and by all parents).
1287func (c *Command) Flags() *flag.FlagSet {1288 if c.flags == nil {1289 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8

lines 1290–1293why, one step back
1290 if c.flagErrorBuf == nil {
1291 c.flagErrorBuf = new(bytes.Buffer)1292 }1293 c.flags.SetOutput(c.flagErrorBuf)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1294why, one step back
1294 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 1295why, one step back
1295

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1296–1315why, one step back
1296 return c.flags
1297}12981299// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1300func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1301 persistentFlags := c.PersistentFlags()13021303 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1304 c.LocalFlags().VisitAll(func(f *flag.Flag) {1305 if persistentFlags.Lookup(f.Name) == nil {1306 out.AddFlag(f)1307 }1308 })1309 return out1310}13111312// LocalFlags returns the local FlagSet specifically set in the current command.1313func (c *Command) LocalFlags() *flag.FlagSet {1314 c.mergePersistentFlags()1315

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1316–1317why, one step back
1316 if c.lflags == nil {
1317 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8

lines 1318–1321why, one step back
1318 if c.flagErrorBuf == nil {
1319 c.flagErrorBuf = new(bytes.Buffer)1320 }1321 c.lflags.SetOutput(c.flagErrorBuf)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1322why, one step back
1322 }

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

line 1323why, one step back
1323 c.lflags.SortFlags = c.Flags().SortFlags

Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf

lines 1324–1326why, one step back
1324 if c.globNormFunc != nil {
1325 c.lflags.SetNormalizeFunc(c.globNormFunc)1326 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1327–1332why, one step back
1327
1328 addToLocal := func(f *flag.Flag) {1329 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1330 c.lflags.AddFlag(f)1331 }1332 }

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

line 1333why, one step back
1333 c.Flags().VisitAll(addToLocal)

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1334–1335why, one step back
1334 c.PersistentFlags().VisitAll(addToLocal)
1335 return c.lflags

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1336–1341why, one step back
1336}
13371338// InheritedFlags returns all flags which were inherited from parents commands.1339func (c *Command) InheritedFlags() *flag.FlagSet {1340 c.mergePersistentFlags()1341

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1342–1343why, one step back
1342 if c.iflags == nil {
1343 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8

lines 1344–1347why, one step back
1344 if c.flagErrorBuf == nil {
1345 c.flagErrorBuf = new(bytes.Buffer)1346 }1347 c.iflags.SetOutput(c.flagErrorBuf)

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1348–1349why, one step back
1348 }
1349

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1350why, one step back
1350 local := c.LocalFlags()

Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf

lines 1351–1354why, one step back
1351 if c.globNormFunc != nil {
1352 c.iflags.SetNormalizeFunc(c.globNormFunc)1353 }1354

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1355–1357why, one step back
1355 c.parentsPflags.VisitAll(func(f *flag.Flag) {
1356 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1357 c.iflags.AddFlag(f)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1358why, one step back
1358 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1359–1360why, one step back
1359 })
1360 return c.iflags

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1361–1371why, one step back
1361}
13621363// NonInheritedFlags returns all flags which were not inherited from parent commands.1364func (c *Command) NonInheritedFlags() *flag.FlagSet {1365 return c.LocalFlags()1366}13671368// PersistentFlags returns the persistent FlagSet specifically set in the current command.1369func (c *Command) PersistentFlags() *flag.FlagSet {1370 if c.pflags == nil {1371 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8

lines 1372–1375why, one step back
1372 if c.flagErrorBuf == nil {
1373 c.flagErrorBuf = new(bytes.Buffer)1374 }1375 c.pflags.SetOutput(c.flagErrorBuf)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1376–1379why, one step back
1376 }
1377 return c.pflags1378}1379

Edit ResetFlags and ResetCommands descriptionsAlbert Nigmatzianovbefore adoptiond6a4305

line 1380why, one step back
1380// ResetFlags deletes all flags from command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1381why, one step back
1381func (c *Command) ResetFlags() {

Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8

lines 1382–1383why, one step back
1382 c.flagErrorBuf = new(bytes.Buffer)
1383 c.flagErrorBuf.Reset()

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1384why, one step back
1384 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8

line 1385why, one step back
1385 c.flags.SetOutput(c.flagErrorBuf)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1386why, one step back
1386 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8

line 1387why, one step back
1387 c.pflags.SetOutput(c.flagErrorBuf)

Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf

lines 1388–1391why, one step back
1388
1389 c.lflags = nil1390 c.iflags = nil1391 c.parentsPflags = nil

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1392–1393why, one step back
1392}
1393

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1394why, one step back
1394// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1395–1398why, one step back
1395func (c *Command) HasFlags() bool {
1396 return c.Flags().HasFlags()1397}1398

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1399why, one step back
1399// HasPersistentFlags checks if the command contains persistent flags.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1400–1403why, one step back
1400func (c *Command) HasPersistentFlags() bool {
1401 return c.PersistentFlags().HasFlags()1402}1403

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1404why, one step back
1404// HasLocalFlags checks if the command has flags specifically declared locally.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1405–1408why, one step back
1405func (c *Command) HasLocalFlags() bool {
1406 return c.LocalFlags().HasFlags()1407}1408

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1409why, one step back
1409// HasInheritedFlags checks if the command has flags inherited from its parent command.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1410–1413why, one step back
1410func (c *Command) HasInheritedFlags() bool {
1411 return c.InheritedFlags().HasFlags()1412}1413

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1414why, one step back
1414// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1415–1419why, one step back
1415// structure) which are not hidden or deprecated.
1416func (c *Command) HasAvailableFlags() bool {1417 return c.Flags().HasAvailableFlags()1418}1419

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1420why, one step back
1420// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1421–1424why, one step back
1421func (c *Command) HasAvailablePersistentFlags() bool {
1422 return c.PersistentFlags().HasAvailableFlags()1423}1424

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1425why, one step back
1425// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1426–1430why, one step back
1426// or deprecated.
1427func (c *Command) HasAvailableLocalFlags() bool {1428 return c.LocalFlags().HasAvailableFlags()1429}1430

Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af

line 1431why, one step back
1431// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1432–1453why, one step back
1432// not hidden or deprecated.
1433func (c *Command) HasAvailableInheritedFlags() bool {1434 return c.InheritedFlags().HasAvailableFlags()1435}14361437// Flag climbs up the command tree looking for matching flag.1438func (c *Command) Flag(name string) (flag *flag.Flag) {1439 flag = c.Flags().Lookup(name)14401441 if flag == nil {1442 flag = c.persistentFlag(name)1443 }14441445 return1446}14471448// Recursively find matching persistent flag.1449func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1450 if c.HasPersistentFlags() {1451 flag = c.PersistentFlags().Lookup(name)1452 }1453

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

lines 1454–1456why, one step back
1454 if flag == nil {
1455 c.updateParentsPflags()1456 flag = c.parentsPflags.Lookup(name)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1457–1461why, one step back
1457 }
1458 return1459}14601461// ParseFlags parses persistent flag tree and local flags.

Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83

line 1462why, one step back
1462func (c *Command) ParseFlags(args []string) error {

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1463–1465why, one step back
1463 if c.DisableFlagParsing {
1464 return nil1465 }

Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83

line 1466why, one step back
1466

Create new buffer if not present yet (#549)Thomas Cyronbefore adoption7b2c5ac

lines 1467–1469why, one step back
1467 if c.flagErrorBuf == nil {
1468 c.flagErrorBuf = new(bytes.Buffer)1469 }

Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83

line 1470why, one step back
1470 beforeErrorBufLen := c.flagErrorBuf.Len()

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1471why, one step back
1471 c.mergePersistentFlags()

Add support for ignoring parse errors (#662)Rajat Jindalbefore adoption4dab30c

lines 1472–1475why, one step back
1472
1473 //do it here after merging all flags and just before parse1474 c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)1475

Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83

lines 1476–1482why, one step back
1476 err := c.Flags().Parse(args)
1477 // Print warnings if they occurred (e.g. deprecated flag messages).1478 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1479 c.Print(c.flagErrorBuf.String())1480 }14811482 return err

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

lines 1483–1489why, one step back
1483}
14841485// Parent returns a commands parent command.1486func (c *Command) Parent() *Command {1487 return c.parent1488}1489

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

lines 1490–1492why, one step back
1490// mergePersistentFlags merges c.PersistentFlags() to c.Flags()
1491// and adds missing persistent flags of all parents.1492func (c *Command) mergePersistentFlags() {

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

line 1493why, one step back
1493 c.updateParentsPflags()

Fix incorrect merge of pflag.CommandLine to cmd.Flags()Albert Nigmatzianovbefore adoption7d22e77

line 1494why, one step back
1494 c.Flags().AddFlagSet(c.PersistentFlags())

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

line 1495why, one step back
1495 c.Flags().AddFlagSet(c.parentsPflags)

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

lines 1496–1498why, one step back
1496}
14971498// updateParentsPflags updates c.parentsPflags by adding

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

line 1499why, one step back
1499// new persistent flags of all parents.

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

line 1500why, one step back
1500// If c.parentsPflags == nil, it makes new.

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

line 1501why, one step back
1501func (c *Command) updateParentsPflags() {

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1502–1503why, one step back
1502 if c.parentsPflags == nil {
1503 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8

line 1504why, one step back
1504 c.parentsPflags.SetOutput(c.flagErrorBuf)

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

line 1505why, one step back
1505 c.parentsPflags.SortFlags = false

Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf

lines 1506–1509why, one step back
1506 }
15071508 if c.globNormFunc != nil {1509 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1510why, one step back
1510 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 1511why, one step back
1511

Add merging of CommandLine flags to Root commandAlbert Nigmatzianovbefore adoption458d797

lines 1512–1513why, one step back
1512 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)
1513

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

lines 1514–1515why, one step back
1514 c.VisitParents(func(parent *Command) {
1515 c.parentsPflags.AddFlagSet(parent.PersistentFlags())

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 1516why, one step back
1516 })

echo msg not echo msg msg (#364)Yuanxiaobefore adoption9495bc0

line 1517why, one step back
1517}