Skip to content
Myr

command.go

This file

Path

command.go

1,289 lines · 36.4 KiB · Go

Last changed by

Fix typosAlbert Nigmatzianovbefore adoptione606913

History of this file

Take it

The walk stopped after 200 commits: lines older than 1d9d665 point at it.

improving project path guessingspf13before adoption1d9d665

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.

improving project path guessingspf13before adoption1d9d665

lines 16–22why, one step back
16package cobra
1718import (19 "bytes"20 "fmt"21 "io"22 "os"

Limit the verbose test workaround to "cobra.test" onlyAnthony Fokbefore adoptione576205

line 23why, one step back
23 "path/filepath"

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 24why, one step back
24 "sort"

improving project path guessingspf13before adoption1d9d665

lines 25–30why, one step back
25 "strings"
2627 flag "github.com/spf13/pflag"28)2930// Command is just that, a command for your application.

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

line 36why, one step back
36 Use string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 37why, one step back
37

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 40why, one step back
40

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 44why, one step back
44

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

line 46why, one step back
46 Short 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 // Long is the long message shown in the 'help <this-command>' output.

improving project path guessingspf13before adoption1d9d665

line 49why, one step back
49 Long 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 // Example is examples of how to use the command.

improving project path guessingspf13before adoption1d9d665

line 52why, one step back
52 Example 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 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions

improving project path guessingspf13before adoption1d9d665

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 56why, one step back
56

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Merge pull request #257 from sttts/sttts-noun-aliasesEric Parisbefore adoption60267ae

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 61why, one step back
61

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

line 63why, one step back
63 BashCompletionFunction string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 64why, one step back
64

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

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

improving project path guessingspf13before adoption1d9d665

line 66why, one step back
66 Deprecated string

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 67why, one step back
67

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

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

improving project path guessingspf13before adoption1d9d665

line 69why, one step back
69 Hidden bool

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 70why, one step back
70

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

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

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

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 74why, one step back
74

improving project path guessingspf13before adoption1d9d665

lines 75–80why, one step back
75 // The *Run functions are executed in the following order:
76 // * PersistentPreRun()77 // * PreRun()78 // * Run()79 // * PostRun()80 // * PersistentPostRun()

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 82why, one step back
82 //

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

lines 103–109why, one step back
103
104 // SilenceErrors is an option to quiet errors down stream.105 SilenceErrors bool106107 // SilenceUsage is an option to silence usage when an error occurs.108 SilenceUsage bool109

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 113why, one step back
113

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a

line 116why, one step back
116 DisableAutoGenTag bool

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 117–124why, one step back
117
118 // DisableSuggestions disables the suggestions based on Levenshtein distance119 // that go along with 'unknown command' messages.120 DisableSuggestions bool121 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.122 // Must be > 0.123 SuggestionsMinimumDistance int124

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

lines 125–126why, one step back
125 // name is the command name, usually the executable's name.
126 name string

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

line 130why, one step back
130 parent *Command

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

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

improving project path guessingspf13before adoption1d9d665

lines 132–134why, one step back
132 commandsMaxUseLen int
133 commandsMaxCommandPathLen int134 commandsMaxNameLen int

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

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

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 136why, one step back
136 commandsAreSorted bool

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

line 137why, one step back
137

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

lines 140–155why, one step back
140 // flagErrorBuf contains all error messages from pflag.
141 flagErrorBuf *bytes.Buffer142 // flags is full set of flags.143 flags *flag.FlagSet144 // pflags contains persistent flags.145 pflags *flag.FlagSet146 // lflags contains local flags.147 lflags *flag.FlagSet148 // iflags contains inherited flags.149 iflags *flag.FlagSet150 // parentsPflags is all persistent flags of cmd's parents.151 parentsPflags *flag.FlagSet152 // globNormFunc is the global normalization function153 // that we can use on every pflag set and children commands154 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName155

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 156–163why, one step back
156 // output is an output writer defined by user.
157 output io.Writer158 // usageFunc is usage func defined by user.159 usageFunc func(*Command) error160 // usageTemplate is usage template defined by user.161 usageTemplate string162 // flagErrorFunc is func defined by user and it's called when the parsing of163 // flags returns an error.

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 165–168why, one step back
165 // helpTemplate is help template defined by user.
166 helpTemplate string167 // helpFunc is help func defined by user.168 helpFunc func(*Command, []string)

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

improving project path guessingspf13before adoption1d9d665

lines 172–173why, one step back
172}
173

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

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

improving project path guessingspf13before adoption1d9d665

lines 175–182why, one step back
175// particularly useful when testing.
176func (c *Command) SetArgs(a []string) {177 c.args = a178}179180// SetOutput sets the destination for usage and error messages.181// If output is nil, os.Stderr is used.182func (c *Command) SetOutput(output io.Writer) {

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

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

improving project path guessingspf13before adoption1d9d665

lines 184–185why, one step back
184}
185

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

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

improving project path guessingspf13before adoption1d9d665

lines 187–190why, one step back
187func (c *Command) SetUsageFunc(f func(*Command) error) {
188 c.usageFunc = f189}190

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

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

improving project path guessingspf13before adoption1d9d665

lines 192–195why, one step back
192func (c *Command) SetUsageTemplate(s string) {
193 c.usageTemplate = s194}195

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

line 196why, one step back
196// SetFlagErrorFunc sets a function to generate an error when flag parsing

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

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

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

lines 198–201why, one step back
198func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
199 c.flagErrorFunc = f200}201

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

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

improving project path guessingspf13before adoption1d9d665

lines 203–206why, one step back
203func (c *Command) SetHelpFunc(f func(*Command, []string)) {
204 c.helpFunc = f205}206

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

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

improving project path guessingspf13before adoption1d9d665

lines 208–211why, one step back
208func (c *Command) SetHelpCommand(cmd *Command) {
209 c.helpCommand = cmd210}211

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

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

improving project path guessingspf13before adoption1d9d665

lines 213–228why, one step back
213func (c *Command) SetHelpTemplate(s string) {
214 c.helpTemplate = s215}216217// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.218// The user should not have a cyclic dependency on commands.219func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {220 c.Flags().SetNormalizeFunc(n)221 c.PersistentFlags().SetNormalizeFunc(n)222 c.globNormFunc = n223224 for _, command := range c.commands {225 command.SetGlobalNormalizationFunc(n)226 }227}228

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

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

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

line 230why, one step back
230func (c *Command) OutOrStdout() io.Writer {

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 231–233why, one step back
231 return c.getOut(os.Stdout)
232}233

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

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

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

line 235why, one step back
235func (c *Command) OutOrStderr() io.Writer {

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 236–240why, one step back
236 return c.getOut(os.Stderr)
237}238239func (c *Command) getOut(def io.Writer) io.Writer {240 if c.output != nil {

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

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 242–249why, one step back
242 }
243 if c.HasParent() {244 return c.parent.getOut(def)245 }246 return def247}248249// UsageFunc returns either the function set by SetUsageFunc for this command

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 250why, one step back
250// or a parent, or it returns a default usage function.

improving project path guessingspf13before adoption1d9d665

lines 251–255why, one step back
251func (c *Command) UsageFunc() (f func(*Command) error) {
252 if c.usageFunc != nil {253 return c.usageFunc254 }255 if c.HasParent() {

Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777

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

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

lines 257–258why, one step back
257 }
258 return func(c *Command) error {

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

lines 259–260why, one step back
259 c.mergePersistentFlags()
260 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 261why, one step back
261 if err != nil {

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

line 262why, one step back
262 c.Println(err)

improving project path guessingspf13before adoption1d9d665

line 263why, one step back
263 }

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 264why, one step back
264 return err

improving project path guessingspf13before adoption1d9d665

lines 265–267why, one step back
265 }
266}267

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

lines 268–270why, one step back
268// Usage puts out the usage for the command.
269// Used when a user provides invalid input.270// Can be defined by user by overriding UsageFunc.

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

lines 271–274why, one step back
271func (c *Command) Usage() error {
272 return c.UsageFunc()(c)273}274

improving project path guessingspf13before adoption1d9d665

line 275why, one step back
275// HelpFunc returns either the function set by SetHelpFunc for this command

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 276why, one step back
276// or a parent, or it returns a function with default help behavior.

improving project path guessingspf13before adoption1d9d665

line 277why, one step back
277func (c *Command) HelpFunc() func(*Command, []string) {

Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777

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

improving project path guessingspf13before adoption1d9d665

line 280why, one step back
280 }

Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777

lines 281–284why, one step back
281 if c.HasParent() {
282 return c.Parent().HelpFunc()283 }284 return func(c *Command, a []string) {

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

lines 285–286why, one step back
285 c.mergePersistentFlags()
286 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)

improving project path guessingspf13before adoption1d9d665

lines 287–292why, one step back
287 if err != nil {
288 c.Println(err)289 }290 }291}292

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

lines 293–295why, one step back
293// Help puts out the help for the command.
294// Used when a user calls help [command].295// Can be defined by user by overriding HelpFunc.

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

lines 296–300why, one step back
296func (c *Command) Help() error {
297 c.HelpFunc()(c, []string{})298 return nil299}300

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

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 302–305why, one step back
302func (c *Command) UsageString() string {
303 tmpOutput := c.output304 bb := new(bytes.Buffer)305 c.SetOutput(bb)

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

line 306why, one step back
306 c.Usage()

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 307–310why, one step back
307 c.output = tmpOutput
308 return bb.String()309}310

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

lines 311–326why, one step back
311// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
312// command or a parent, or it returns a function which returns the original313// error.314func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {315 if c.flagErrorFunc != nil {316 return c.flagErrorFunc317 }318319 if c.HasParent() {320 return c.parent.FlagErrorFunc()321 }322 return func(c *Command, err error) error {323 return err324 }325}326

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 327why, one step back
327var minUsagePadding = 25

improving project path guessingspf13before adoption1d9d665

line 328why, one step back
328

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

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

improving project path guessingspf13before adoption1d9d665

lines 330–333why, one step back
330func (c *Command) UsagePadding() int {
331 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {332 return minUsagePadding333 }

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 334why, one step back
334 return c.parent.commandsMaxUseLen

improving project path guessingspf13before adoption1d9d665

lines 335–336why, one step back
335}
336

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 337why, one step back
337var minCommandPathPadding = 11

improving project path guessingspf13before adoption1d9d665

line 338why, one step back
338

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

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

improving project path guessingspf13before adoption1d9d665

lines 340–343why, one step back
340func (c *Command) CommandPathPadding() int {
341 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {342 return minCommandPathPadding343 }

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 344why, one step back
344 return c.parent.commandsMaxCommandPathLen

improving project path guessingspf13before adoption1d9d665

lines 345–346why, one step back
345}
346

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 347why, one step back
347var minNamePadding = 11

improving project path guessingspf13before adoption1d9d665

line 348why, one step back
348

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

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

improving project path guessingspf13before adoption1d9d665

lines 350–353why, one step back
350func (c *Command) NamePadding() int {
351 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {352 return minNamePadding353 }

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 354why, one step back
354 return c.parent.commandsMaxNameLen

improving project path guessingspf13before adoption1d9d665

lines 355–356why, one step back
355}
356

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

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

improving project path guessingspf13before adoption1d9d665

lines 358–364why, one step back
358func (c *Command) UsageTemplate() string {
359 if c.usageTemplate != "" {360 return c.usageTemplate361 }362363 if c.HasParent() {364 return c.parent.UsageTemplate()

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

lines 365–366why, one step back
365 }
366 return `Usage:{{if .Runnable}}

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

improving project path guessingspf13before adoption1d9d665

lines 369–370why, one step back
369
370Aliases:

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

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

improving project path guessingspf13before adoption1d9d665

lines 372–373why, one step back
372
373Examples:

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

improving project path guessingspf13before adoption1d9d665

line 375why, one step back
375

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

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

improving project path guessingspf13before adoption1d9d665

lines 378–379why, one step back
378
379Flags:

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

improving project path guessingspf13before adoption1d9d665

lines 381–382why, one step back
381
382Global Flags:

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

improving project path guessingspf13before adoption1d9d665

line 384why, one step back
384

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

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

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

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

improving project path guessingspf13before adoption1d9d665

lines 387–391why, one step back
387
388Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}389`390}391

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

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

improving project path guessingspf13before adoption1d9d665

lines 393–399why, one step back
393func (c *Command) HelpTemplate() string {
394 if c.helpTemplate != "" {395 return c.helpTemplate396 }397398 if c.HasParent() {399 return c.parent.HelpTemplate()

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 400why, one step back
400 }

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

improving project path guessingspf13before adoption1d9d665

lines 402–405why, one step back
402
403{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`404}405

Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41

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

improving project path guessingspf13before adoption1d9d665

lines 408–410why, one step back
408 if flag == nil {
409 return false410 }

Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6

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

improving project path guessingspf13before adoption1d9d665

lines 412–413why, one step back
412}
413

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

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

Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41

lines 415–423why, one step back
415 if len(name) == 0 {
416 return false417 }418419 flag := fs.ShorthandLookup(name[:1])420 if flag == nil {421 return false422 }423 return flag.NoOptDefVal != ""

improving project path guessingspf13before adoption1d9d665

lines 424–426why, one step back
424}
425426func stripFlags(args []string, c *Command) []string {

Simplify stripFlags functionAlbert Nigmatzianovbefore adoption9890b7b

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

improving project path guessingspf13before adoption1d9d665

lines 428–432why, one step back
428 return args
429 }430 c.mergePersistentFlags()431432 commands := []string{}

Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6

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

Simplify stripFlags functionAlbert Nigmatzianovbefore adoption9890b7b

lines 434–437why, one step back
434
435Loop:436 for len(args) > 0 {437 s := args[0]

Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6

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

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

lines 439–451why, one step back
439 switch {
440 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):441 // If '--flag arg' then442 // delete arg from args.443 fallthrough // (do the same as below)444 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):445 // If '-f arg' then446 // delete 'arg' from args or break the loop if len(args) <= 1.447 if len(args) <= 1 {448 break Loop449 } else {450 args = args[1:]451 continue

improving project path guessingspf13before adoption1d9d665

line 452why, one step back
452 }

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

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

improving project path guessingspf13before adoption1d9d665

lines 455–474why, one step back
455 }
456 }457458 return commands459}460461// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like462// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).463func argsMinusFirstX(args []string, x string) []string {464 for i, y := range args {465 if x == y {466 ret := []string{}467 ret = append(ret, args[:i]...)468 ret = append(ret, args[i+1:]...)469 return ret470 }471 }472 return args473}474

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

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

improving project path guessingspf13before adoption1d9d665

lines 476–542why, one step back
476// Meant to be run on the highest node. Only searches down.
477func (c *Command) Find(args []string) (*Command, []string, error) {478 if c == nil {479 return nil, nil, fmt.Errorf("Called find() on a nil Command")480 }481482 var innerfind func(*Command, []string) (*Command, []string)483484 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {485 argsWOflags := stripFlags(innerArgs, c)486 if len(argsWOflags) == 0 {487 return c, innerArgs488 }489 nextSubCmd := argsWOflags[0]490 matches := make([]*Command, 0)491 for _, cmd := range c.commands {492 if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match493 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))494 }495 if EnablePrefixMatching {496 if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match497 matches = append(matches, cmd)498 }499 for _, x := range cmd.Aliases {500 if strings.HasPrefix(x, nextSubCmd) {501 matches = append(matches, cmd)502 }503 }504 }505 }506507 // only accept a single prefix match - multiple matches would be ambiguous508 if len(matches) == 1 {509 return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))510 }511512 return c, innerArgs513 }514515 commandFound, a := innerfind(c, args)516 argsWOflags := stripFlags(a, commandFound)517518 // no subcommand, always take args519 if !commandFound.HasSubCommands() {520 return commandFound, a, nil521 }522523 // root command with subcommands, do subcommand checking524 if commandFound == c && len(argsWOflags) > 0 {525 suggestionsString := ""526 if !c.DisableSuggestions {527 if c.SuggestionsMinimumDistance <= 0 {528 c.SuggestionsMinimumDistance = 2529 }530 if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {531 suggestionsString += "\n\nDid you mean this?\n"532 for _, s := range suggestions {533 suggestionsString += fmt.Sprintf("\t%v\n", s)534 }535 }536 }537 return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)538 }539540 return commandFound, a, nil541}542

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

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

improving project path guessingspf13before adoption1d9d665

lines 544–563why, one step back
544func (c *Command) SuggestionsFor(typedName string) []string {
545 suggestions := []string{}546 for _, cmd := range c.commands {547 if cmd.IsAvailableCommand() {548 levenshteinDistance := ld(typedName, cmd.Name(), true)549 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance550 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))551 if suggestByLevenshtein || suggestByPrefix {552 suggestions = append(suggestions, cmd.Name())553 }554 for _, explicitSuggestion := range cmd.SuggestFor {555 if strings.EqualFold(typedName, explicitSuggestion) {556 suggestions = append(suggestions, cmd.Name())557 }558 }559 }560 }561 return suggestions562}563

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

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

add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 566–568why, one step back
566 if c.HasParent() {
567 fn(c.Parent())568 c.Parent().VisitParents(fn)

add a flag to disable autogen tag in man and markdown generatorsAustin Riendeaubefore adoption5144a3a

lines 569–571why, one step back
569 }
570}571

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

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

improving project path guessingspf13before adoption1d9d665

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

improving project path guessingspf13before adoption1d9d665

line 576why, one step back
576 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 577why, one step back
577 return c

improving project path guessingspf13before adoption1d9d665

lines 578–598why, one step back
578}
579580// ArgsLenAtDash will return the length of f.Args at the moment when a -- was581// found during arg parsing. This allows your program to know which args were582// before the -- and which came after. (Description from583// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).584func (c *Command) ArgsLenAtDash() int {585 return c.Flags().ArgsLenAtDash()586}587588func (c *Command) execute(a []string) (err error) {589 if c == nil {590 return fmt.Errorf("Called Execute() on a nil Command")591 }592593 if len(c.Deprecated) > 0 {594 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)595 }596597 // initialize help flag as the last point possible to allow for user598 // overriding

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

improving project path guessingspf13before adoption1d9d665

lines 600–602why, one step back
600
601 err = c.ParseFlags(a)602 if err != nil {

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

line 603why, one step back
603 return c.FlagErrorFunc()(c, err)

improving project path guessingspf13before adoption1d9d665

line 604why, one step back
604 }

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

improving project path guessingspf13before adoption1d9d665

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

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

improving project path guessingspf13before adoption1d9d665

lines 612–614why, one step back
612 c.Println("\"help\" flag declared as non-bool. Please correct your code")
613 return err614 }

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

line 615why, one step back
615

improving project path guessingspf13before adoption1d9d665

lines 616–620why, one step back
616 if helpVal || !c.Runnable() {
617 return flag.ErrHelp618 }619620 c.preRun()

Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048

line 621why, one step back
621

improving project path guessingspf13before adoption1d9d665

line 622why, one step back
622 argWoFlags := c.Flags().Args()

Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048

lines 623–625why, one step back
623 if c.DisableFlagParsing {
624 argWoFlags = a625 }

improving project path guessingspf13before adoption1d9d665

lines 626–680why, one step back
626
627 for p := c; p != nil; p = p.Parent() {628 if p.PersistentPreRunE != nil {629 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {630 return err631 }632 break633 } else if p.PersistentPreRun != nil {634 p.PersistentPreRun(c, argWoFlags)635 break636 }637 }638 if c.PreRunE != nil {639 if err := c.PreRunE(c, argWoFlags); err != nil {640 return err641 }642 } else if c.PreRun != nil {643 c.PreRun(c, argWoFlags)644 }645646 if c.RunE != nil {647 if err := c.RunE(c, argWoFlags); err != nil {648 return err649 }650 } else {651 c.Run(c, argWoFlags)652 }653 if c.PostRunE != nil {654 if err := c.PostRunE(c, argWoFlags); err != nil {655 return err656 }657 } else if c.PostRun != nil {658 c.PostRun(c, argWoFlags)659 }660 for p := c; p != nil; p = p.Parent() {661 if p.PersistentPostRunE != nil {662 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {663 return err664 }665 break666 } else if p.PersistentPostRun != nil {667 p.PersistentPostRun(c, argWoFlags)668 break669 }670 }671672 return nil673}674675func (c *Command) preRun() {676 for _, x := range initializers {677 x()678 }679}680

Fix typosAlbert Nigmatzianovbefore adoptione606913

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

improving project path guessingspf13before adoption1d9d665

lines 682–683why, one step back
682// and run through the command tree finding appropriate matches
683// for commands and then corresponding flags.

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

lines 684–687why, one step back
684func (c *Command) Execute() error {
685 _, err := c.ExecuteC()686 return err687}

improving project path guessingspf13before adoption1d9d665

line 688why, one step back
688

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

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

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

line 690why, one step back
690func (c *Command) ExecuteC() (cmd *Command, err error) {

improving project path guessingspf13before adoption1d9d665

lines 691–692why, one step back
691 // Regardless of what command execute is called on, run on Root only
692 if c.HasParent() {

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

line 693why, one step back
693 return c.Root().ExecuteC()

improving project path guessingspf13before adoption1d9d665

lines 694–695why, one step back
694 }
695

Merge pull request #197 from magiconair/issue-195-mousetrap-win-onlyEric Parisbefore adoption7366561

lines 696–698why, one step back
696 // windows hook
697 if preExecHookFn != nil {698 preExecHookFn(c)

improving project path guessingspf13before adoption1d9d665

lines 699–702why, one step back
699 }
700701 // initialize help as the last point possible to allow for user702 // overriding

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

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

improving project path guessingspf13before adoption1d9d665

lines 704–706why, one step back
704
705 var args []string706

Limit the verbose test workaround to "cobra.test" onlyAnthony Fokbefore adoptione576205

line 707why, one step back
707 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155

Use nil instead of len for arg check.Jonathan Reynabefore adoption1ef0913

line 708why, one step back
708 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {

improving project path guessingspf13before adoption1d9d665

lines 709–723why, one step back
709 args = os.Args[1:]
710 } else {711 args = c.args712 }713714 cmd, flags, err := c.Find(args)715 if err != nil {716 // If found parse to a subcommand and then failed, talk about the subcommand717 if cmd != nil {718 c = cmd719 }720 if !c.SilenceErrors {721 c.Println("Error:", err.Error())722 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())723 }

Merge pull request #192 from apriendeau/executeCEric Parisbefore adoptioncb63a06

line 724why, one step back
724 return c, err

improving project path guessingspf13before adoption1d9d665

lines 725–727why, one step back
725 }
726 err = cmd.execute(flags)727 if err != nil {

always show help if requested, even if SilenceErrors is enabledSascha Holzleiterbefore adoption2bd8a73

lines 728–734why, one step back
728 // Always show help if requested, even if SilenceErrors is in
729 // effect730 if err == flag.ErrHelp {731 cmd.HelpFunc()(cmd, args)732 return cmd, nil733 }734

improving project path guessingspf13before adoption1d9d665

lines 735–746why, one step back
735 // If root command has SilentErrors flagged,
736 // all subcommands should respect it737 if !cmd.SilenceErrors && !c.SilenceErrors {738 c.Println("Error:", err.Error())739 }740741 // If root command has SilentUsage flagged,742 // all subcommands should respect it743 if !cmd.SilenceUsage && !c.SilenceUsage {744 c.Println(cmd.UsageString())745 }746 }

Fix typosAlbert Nigmatzianovbefore adoptione606913

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

improving project path guessingspf13before adoption1d9d665

lines 748–749why, one step back
748}
749

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

Add comment for InitDefaultHelpFlagAlbert Nigmatzianovbefore adoptiond83a1d7

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

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

Merge pull request #286 from dnephin/merge_flags_before_adding_helpEric Parisbefore adoptionec2fe78

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

improving project path guessingspf13before adoption1d9d665

line 755why, one step back
755 if c.Flags().Lookup("help") == nil {

Initialize help flag in initHelpCmdAlbert Nigmatzianovbefore adoption867d414

lines 756–762why, one step back
756 usage := "help for "
757 if c.Name() == "" {758 usage += "this command"759 } else {760 usage += c.Name()761 }762 c.Flags().BoolP("help", "h", false, usage)

improving project path guessingspf13before adoption1d9d665

lines 763–765why, one step back
763 }
764}765

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

lines 766–772why, one step back
766// InitDefaultHelpCmd adds default help command to c.
767// It is called automatically by executing the c or by calling help and usage.768// If c already has help command or c has no subcommands, it will do nothing.769func (c *Command) InitDefaultHelpCmd() {770 if c.helpCommand != nil || !c.HasSubCommands() {771 return772 }

improving project path guessingspf13before adoption1d9d665

line 773why, one step back
773

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

lines 774–777why, one step back
774 c.helpCommand = &Command{
775 Use: "help [command]",776 Short: "Help about any command",777 Long: `Help provides help for any command in the application.

improving project path guessingspf13before adoption1d9d665

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

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

lines 779–780why, one step back
779 PersistentPreRun: func(cmd *Command, args []string) {},
780 PersistentPostRun: func(cmd *Command, args []string) {},

improving project path guessingspf13before adoption1d9d665

line 781why, one step back
781

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

lines 782–791why, one step back
782 Run: func(c *Command, args []string) {
783 cmd, _, e := c.Root().Find(args)784 if cmd == nil || e != nil {785 c.Printf("Unknown help topic %#q\n", args)786 c.Root().Usage()787 } else {788 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown789 cmd.Help()790 }791 },

improving project path guessingspf13before adoption1d9d665

line 792why, one step back
792 }

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

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

improving project path guessingspf13before adoption1d9d665

lines 794–796why, one step back
794 c.AddCommand(c.helpCommand)
795}796

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

line 797why, one step back
797// ResetCommands used for testing.

improving project path guessingspf13before adoption1d9d665

lines 798–800why, one step back
798func (c *Command) ResetCommands() {
799 c.commands = nil800 c.helpCommand = nil

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

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

improving project path guessingspf13before adoption1d9d665

lines 802–803why, one step back
802}
803

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 804why, one step back
804// Sorts commands by their names.

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

lines 805–811why, one step back
805type commandSorterByName []*Command
806807func (c commandSorterByName) Len() int { return len(c) }808func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }809func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }810811// Commands returns a sorted slice of child commands.

improving project path guessingspf13before adoption1d9d665

line 812why, one step back
812func (c *Command) Commands() []*Command {

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 813why, one step back
813 // do not sort commands if it already sorted or sorting was disabled

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

line 814why, one step back
814 if EnableCommandSorting && !c.commandsAreSorted {

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

lines 815–817why, one step back
815 sort.Sort(commandSorterByName(c.commands))
816 c.commandsAreSorted = true817 }

improving project path guessingspf13before adoption1d9d665

lines 818–840why, one step back
818 return c.commands
819}820821// AddCommand adds one or more commands to this parent command.822func (c *Command) AddCommand(cmds ...*Command) {823 for i, x := range cmds {824 if cmds[i] == c {825 panic("Command can't be a child of itself")826 }827 cmds[i].parent = c828 // update max lengths829 usageLen := len(x.Use)830 if usageLen > c.commandsMaxUseLen {831 c.commandsMaxUseLen = usageLen832 }833 commandPathLen := len(x.CommandPath())834 if commandPathLen > c.commandsMaxCommandPathLen {835 c.commandsMaxCommandPathLen = commandPathLen836 }837 nameLen := len(x.Name())838 if nameLen > c.commandsMaxNameLen {839 c.commandsMaxNameLen = nameLen840 }

Merge pull request #211 from NanXiao/patch-1Eric Parisbefore adoptionea3bf16

line 841why, one step back
841 // If global normalization function exists, update all children

improving project path guessingspf13before adoption1d9d665

lines 842–845why, one step back
842 if c.globNormFunc != nil {
843 x.SetGlobalNormalizationFunc(c.globNormFunc)844 }845 c.commands = append(c.commands, x)

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 846why, one step back
846 c.commandsAreSorted = false

improving project path guessingspf13before adoption1d9d665

lines 847–849why, one step back
847 }
848}849

Merge pull request #278 from kevintpeng/patch-1Eric Parisbefore adoptionf368244

line 850why, one step back
850// RemoveCommand removes one or more commands from a parent command.

improving project path guessingspf13before adoption1d9d665

lines 851–883why, one step back
851func (c *Command) RemoveCommand(cmds ...*Command) {
852 commands := []*Command{}853main:854 for _, command := range c.commands {855 for _, cmd := range cmds {856 if command == cmd {857 command.parent = nil858 continue main859 }860 }861 commands = append(commands, command)862 }863 c.commands = commands864 // recompute all lengths865 c.commandsMaxUseLen = 0866 c.commandsMaxCommandPathLen = 0867 c.commandsMaxNameLen = 0868 for _, command := range c.commands {869 usageLen := len(command.Use)870 if usageLen > c.commandsMaxUseLen {871 c.commandsMaxUseLen = usageLen872 }873 commandPathLen := len(command.CommandPath())874 if commandPathLen > c.commandsMaxCommandPathLen {875 c.commandsMaxCommandPathLen = commandPathLen876 }877 nameLen := len(command.Name())878 if nameLen > c.commandsMaxNameLen {879 c.commandsMaxNameLen = nameLen880 }881 }882}883

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 884why, one step back
884// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.

improving project path guessingspf13before adoption1d9d665

line 885why, one step back
885func (c *Command) Print(i ...interface{}) {

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

line 886why, one step back
886 fmt.Fprint(c.OutOrStderr(), i...)

improving project path guessingspf13before adoption1d9d665

lines 887–888why, one step back
887}
888

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 889why, one step back
889// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.

improving project path guessingspf13before adoption1d9d665

line 890why, one step back
890func (c *Command) Println(i ...interface{}) {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

improving project path guessingspf13before adoption1d9d665

lines 892–893why, one step back
892}
893

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 894why, one step back
894// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.

improving project path guessingspf13before adoption1d9d665

line 895why, one step back
895func (c *Command) Printf(format string, i ...interface{}) {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

improving project path guessingspf13before adoption1d9d665

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

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

improving project path guessingspf13before adoption1d9d665

line 903why, one step back
903 }

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

improving project path guessingspf13before adoption1d9d665

lines 905–906why, one step back
905}
906

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 907why, one step back
907// UseLine puts out the full usage for a given command (including parents).

improving project path guessingspf13before adoption1d9d665

line 908why, one step back
908func (c *Command) UseLine() string {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 909why, one step back
909 var useline string

improving project path guessingspf13before adoption1d9d665

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

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 911–913why, one step back
911 useline = c.parent.CommandPath() + " " + c.Use
912 } else {913 useline = c.Use

improving project path guessingspf13before adoption1d9d665

line 914why, one step back
914 }

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 915–918why, one step back
915 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
916 useline += " [flags]"917 }918 return useline

improving project path guessingspf13before adoption1d9d665

lines 919–920why, one step back
919}
920

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 922why, one step back
922// and which persist.

improving project path guessingspf13before adoption1d9d665

lines 923–932why, one step back
923func (c *Command) DebugFlags() {
924 c.Println("DebugFlags called on", c.Name())925 var debugflags func(*Command)926927 debugflags = func(x *Command) {928 if x.HasFlags() || x.HasPersistentFlags() {929 c.Println(x.Name())930 }931 if x.HasFlags() {932 x.flags.VisitAll(func(f *flag.Flag) {

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

improving project path guessingspf13before adoption1d9d665

lines 935–950why, one step back
935 } else {
936 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")937 }938 })939 }940 if x.HasPersistentFlags() {941 x.pflags.VisitAll(func(f *flag.Flag) {942 if x.HasFlags() {943 if x.flags.Lookup(f.Name) == nil {944 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")945 }946 } else {947 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")948 }949 })950 }

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

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

improving project path guessingspf13before adoption1d9d665

lines 952–963why, one step back
952 if x.HasSubCommands() {
953 for _, y := range x.commands {954 debugflags(y)955 }956 }957 }958959 debugflags(c)960}961962// Name returns the command's name: the first word in the use line.963func (c *Command) Name() string {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 964–970why, one step back
964 if c.name == "" {
965 name := c.Use966 i := strings.Index(name, " ")967 if i >= 0 {968 name = name[:i]969 }970 c.name = name

improving project path guessingspf13before adoption1d9d665

line 971why, one step back
971 }

cache command name (#390)Di Xubefore adoptionb5d8e8f

line 972why, one step back
972 return c.name

improving project path guessingspf13before adoption1d9d665

lines 973–974why, one step back
973}
974

Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e

line 975why, one step back
975// HasAlias determines if a given string is an alias of the command.

improving project path guessingspf13before adoption1d9d665

lines 976–984why, one step back
976func (c *Command) HasAlias(s string) bool {
977 for _, a := range c.Aliases {978 if a == s {979 return true980 }981 }982 return false983}984

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

line 985why, one step back
985// NameAndAliases returns string containing name and all aliases

improving project path guessingspf13before adoption1d9d665

lines 986–989why, one step back
986func (c *Command) NameAndAliases() string {
987 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")988}989

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

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

improving project path guessingspf13before adoption1d9d665

lines 991–994why, one step back
991func (c *Command) HasExample() bool {
992 return len(c.Example) > 0993}994

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 995why, one step back
995// Runnable determines if the command is itself runnable.

improving project path guessingspf13before adoption1d9d665

lines 996–999why, one step back
996func (c *Command) Runnable() bool {
997 return c.Run != nil || c.RunE != nil998}999

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1000why, one step back
1000// HasSubCommands determines if the command has children commands.

improving project path guessingspf13before adoption1d9d665

lines 1001–1005why, one step back
1001func (c *Command) HasSubCommands() bool {
1002 return len(c.commands) > 01003}10041005// IsAvailableCommand determines if a command is available as a non-help command

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1006why, one step back
1006// (this includes all non deprecated/hidden commands).

improving project path guessingspf13before adoption1d9d665

lines 1007–1022why, one step back
1007func (c *Command) IsAvailableCommand() bool {
1008 if len(c.Deprecated) != 0 || c.Hidden {1009 return false1010 }10111012 if c.HasParent() && c.Parent().helpCommand == c {1013 return false1014 }10151016 if c.Runnable() || c.HasAvailableSubCommands() {1017 return true1018 }10191020 return false1021}1022

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

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

improving project path guessingspf13before adoption1d9d665

lines 1029–1035why, one step back
1029 // if a command is runnable, deprecated, or hidden it is not a 'help' command
1030 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1031 return false1032 }10331034 // if any non-help sub commands are found, the command is not a 'help' command1035 for _, sub := range c.commands {

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

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

improving project path guessingspf13before adoption1d9d665

lines 1037–1044why, one step back
1037 return false
1038 }1039 }10401041 // the command either has no sub commands, or no non-help sub commands1042 return true1043}1044

Merge pull request #327 from bogem/fixesEric Parisbefore adoption1f47171

line 1045why, one step back
1045// HasHelpSubCommands determines if a command has any available 'help' sub commands

improving project path guessingspf13before adoption1d9d665

line 1046why, one step back
1046// that need to be shown in the usage/help default template under 'additional help

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1047why, one step back
1047// topics'.

improving project path guessingspf13before adoption1d9d665

lines 1048–1050why, one step back
1048func (c *Command) HasHelpSubCommands() bool {
1049 // return true on the first found available 'help' sub command1050 for _, sub := range c.commands {

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

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

improving project path guessingspf13before adoption1d9d665

lines 1052–1060why, one step back
1052 return true
1053 }1054 }10551056 // the command either has no sub commands, or no available 'help' sub commands1057 return false1058}10591060// HasAvailableSubCommands determines if a command has available sub commands that

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1061why, one step back
1061// need to be shown in the usage/help default template under 'available commands'.

improving project path guessingspf13before adoption1d9d665

lines 1062–1075why, one step back
1062func (c *Command) HasAvailableSubCommands() bool {
1063 // return true on the first found available (non deprecated/help/hidden)1064 // sub command1065 for _, sub := range c.commands {1066 if sub.IsAvailableCommand() {1067 return true1068 }1069 }10701071 // the command either has no sub comamnds, or no available (non deprecated/help/hidden)1072 // sub commands1073 return false1074}1075

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1076why, one step back
1076// HasParent determines if the command is a child command.

improving project path guessingspf13before adoption1d9d665

lines 1077–1080why, one step back
1077func (c *Command) HasParent() bool {
1078 return c.parent != nil1079}1080

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

improving project path guessingspf13before adoption1d9d665

lines 1082–1085why, one step back
1082func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
1083 return c.globNormFunc1084}1085

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1087why, one step back
1087// to this command (local and persistent declared here and by all parents).

improving project path guessingspf13before adoption1d9d665

lines 1088–1090why, one step back
1088func (c *Command) Flags() *flag.FlagSet {
1089 if c.flags == nil {1090 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)

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

lines 1091–1094why, one step back
1091 if c.flagErrorBuf == nil {
1092 c.flagErrorBuf = new(bytes.Buffer)1093 }1094 c.flags.SetOutput(c.flagErrorBuf)

improving project path guessingspf13before adoption1d9d665

line 1095why, one step back
1095 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 1096why, one step back
1096

improving project path guessingspf13before adoption1d9d665

lines 1097–1099why, one step back
1097 return c.flags
1098}1099

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1100why, one step back
1100// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.

Merge pull request #288 from eparis/flags-vs-commandsEric Parisbefore adoptionc21ee9d

lines 1101–1112why, one step back
1101func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
1102 persistentFlags := c.PersistentFlags()11031104 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1105 c.LocalFlags().VisitAll(func(f *flag.Flag) {1106 if persistentFlags.Lookup(f.Name) == nil {1107 out.AddFlag(f)1108 }1109 })1110 return out1111}1112

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1113why, one step back
1113// LocalFlags returns the local FlagSet specifically set in the current command.

improving project path guessingspf13before adoption1d9d665

lines 1114–1116why, one step back
1114func (c *Command) LocalFlags() *flag.FlagSet {
1115 c.mergePersistentFlags()1116

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

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

lines 1119–1122why, one step back
1119 if c.flagErrorBuf == nil {
1120 c.flagErrorBuf = new(bytes.Buffer)1121 }1122 c.lflags.SetOutput(c.flagErrorBuf)

improving project path guessingspf13before adoption1d9d665

line 1123why, one step back
1123 }

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1125–1130why, one step back
1125
1126 addToLocal := func(f *flag.Flag) {1127 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1128 c.lflags.AddFlag(f)1129 }1130 }

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

improving project path guessingspf13before adoption1d9d665

lines 1134–1135why, one step back
1134}
1135

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1136why, one step back
1136// InheritedFlags returns all flags which were inherited from parents commands.

improving project path guessingspf13before adoption1d9d665

lines 1137–1139why, one step back
1137func (c *Command) InheritedFlags() *flag.FlagSet {
1138 c.mergePersistentFlags()1139

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

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

lines 1142–1145why, one step back
1142 if c.flagErrorBuf == nil {
1143 c.flagErrorBuf = new(bytes.Buffer)1144 }1145 c.iflags.SetOutput(c.flagErrorBuf)

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1146–1147why, one step back
1146 }
1147

improving project path guessingspf13before adoption1d9d665

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

improving project path guessingspf13before adoption1d9d665

line 1152why, one step back
1152 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1153–1154why, one step back
1153 })
1154 return c.iflags

improving project path guessingspf13before adoption1d9d665

lines 1155–1156why, one step back
1155}
1156

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1157why, one step back
1157// NonInheritedFlags returns all flags which were not inherited from parent commands.

improving project path guessingspf13before adoption1d9d665

lines 1158–1161why, one step back
1158func (c *Command) NonInheritedFlags() *flag.FlagSet {
1159 return c.LocalFlags()1160}1161

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1162why, one step back
1162// PersistentFlags returns the persistent FlagSet specifically set in the current command.

improving project path guessingspf13before adoption1d9d665

lines 1163–1165why, one step back
1163func (c *Command) PersistentFlags() *flag.FlagSet {
1164 if c.pflags == nil {1165 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)

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

lines 1166–1169why, one step back
1166 if c.flagErrorBuf == nil {
1167 c.flagErrorBuf = new(bytes.Buffer)1168 }1169 c.pflags.SetOutput(c.flagErrorBuf)

improving project path guessingspf13before adoption1d9d665

lines 1170–1173why, one step back
1170 }
1171 return c.pflags1172}1173

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1174why, one step back
1174// ResetFlags is used in testing.

improving project path guessingspf13before adoption1d9d665

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

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

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

improving project path guessingspf13before adoption1d9d665

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

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

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

improving project path guessingspf13before adoption1d9d665

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

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

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

improving project path guessingspf13before adoption1d9d665

lines 1182–1183why, one step back
1182}
1183

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

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

improving project path guessingspf13before adoption1d9d665

lines 1185–1188why, one step back
1185func (c *Command) HasFlags() bool {
1186 return c.Flags().HasFlags()1187}1188

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

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

improving project path guessingspf13before adoption1d9d665

lines 1190–1193why, one step back
1190func (c *Command) HasPersistentFlags() bool {
1191 return c.PersistentFlags().HasFlags()1192}1193

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

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

improving project path guessingspf13before adoption1d9d665

lines 1195–1198why, one step back
1195func (c *Command) HasLocalFlags() bool {
1196 return c.LocalFlags().HasFlags()1197}1198

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

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

improving project path guessingspf13before adoption1d9d665

lines 1200–1201why, one step back
1200func (c *Command) HasInheritedFlags() bool {
1201 return c.InheritedFlags().HasFlags()

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1202–1203why, one step back
1202}
1203

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1205why, one step back
1205// structure) which are not hidden or deprecated.

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1206–1209why, one step back
1206func (c *Command) HasAvailableFlags() bool {
1207 return c.Flags().HasAvailableFlags()1208}1209

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

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

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1211–1214why, one step back
1211func (c *Command) HasAvailablePersistentFlags() bool {
1212 return c.PersistentFlags().HasAvailableFlags()1213}1214

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1216why, one step back
1216// or deprecated.

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1217–1220why, one step back
1217func (c *Command) HasAvailableLocalFlags() bool {
1218 return c.LocalFlags().HasAvailableFlags()1219}1220

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1222why, one step back
1222// not hidden or deprecated.

Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b

lines 1223–1224why, one step back
1223func (c *Command) HasAvailableInheritedFlags() bool {
1224 return c.InheritedFlags().HasAvailableFlags()

improving project path guessingspf13before adoption1d9d665

lines 1225–1226why, one step back
1225}
1226

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1227why, one step back
1227// Flag climbs up the command tree looking for matching flag.

improving project path guessingspf13before adoption1d9d665

lines 1228–1237why, one step back
1228func (c *Command) Flag(name string) (flag *flag.Flag) {
1229 flag = c.Flags().Lookup(name)12301231 if flag == nil {1232 flag = c.persistentFlag(name)1233 }12341235 return1236}1237

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1238why, one step back
1238// Recursively find matching persistent flag.

improving project path guessingspf13before adoption1d9d665

lines 1239–1243why, one step back
1239func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
1240 if c.HasPersistentFlags() {1241 flag = c.PersistentFlags().Lookup(name)1242 }1243

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

lines 1244–1246why, one step back
1244 if flag == nil {
1245 c.updateParentsPflags()1246 flag = c.parentsPflags.Lookup(name)

improving project path guessingspf13before adoption1d9d665

lines 1247–1250why, one step back
1247 }
1248 return1249}1250

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1251why, one step back
1251// ParseFlags parses persistent flag tree and local flags.

improving project path guessingspf13before adoption1d9d665

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

Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048

lines 1253–1255why, one step back
1253 if c.DisableFlagParsing {
1254 return nil1255 }

improving project path guessingspf13before adoption1d9d665

lines 1256–1260why, one step back
1256 c.mergePersistentFlags()
1257 err = c.Flags().Parse(args)1258 return1259}1260

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1261why, one step back
1261// Parent returns a commands parent command.

improving project path guessingspf13before adoption1d9d665

lines 1262–1265why, one step back
1262func (c *Command) Parent() *Command {
1263 return c.parent1264}1265

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

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

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

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

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

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

lines 1272–1274why, one step back
1272}
12731274// updateParentsPflags updates c.parentsPflags by adding

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

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

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

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

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

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

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

improving project path guessingspf13before adoption1d9d665

line 1282why, one step back
1282 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 1283why, one step back
1283

Add merging of CommandLine flags to Root commandAlbert Nigmatzianovbefore adoption458d797

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

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 1288why, one step back
1288 })

improving project path guessingspf13before adoption1d9d665

line 1289why, one step back
1289}