Skip to content
Myr

command.go

This file

Path

command.go

1,411 lines · 38.9 KiB · Go

Last changed by

enforce required flags (#502)Di Xubefore adoption4d6af28

History of this file

Take it

The walk stopped after 200 commits: lines older than 65a708c point at it.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 24why, one step back
24 "sort"

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 56why, one step back
56

Update documentationAlbert Nigmatzianovbefore adoption1723331

lines 57–59why, one step back
57 // Expected arguments
58 Args PositionalArgs59

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

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

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 64why, one step back
64

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 66why, one step back
66 BashCompletionFunction 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 // Deprecated defines, if this command is deprecated and should print this string when used.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 69why, one step back
69 Deprecated 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 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 72why, one step back
72 Hidden bool

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 73why, one step back
73

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

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

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

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 77why, one step back
77

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 85why, one step back
85 //

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

lines 106–112why, one step back
106
107 // SilenceErrors is an option to quiet errors down stream.108 SilenceErrors bool109110 // SilenceUsage is an option to silence usage when an error occurs.111 SilenceUsage bool112

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

line 116why, one step back
116

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 119why, one step back
119 DisableAutoGenTag bool

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 120–127why, one step back
120
121 // DisableSuggestions disables the suggestions based on Levenshtein distance122 // that go along with 'unknown command' messages.123 DisableSuggestions bool124 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.125 // Must be > 0.126 SuggestionsMinimumDistance int127

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

lines 128–130why, one step back
128 // TraverseChildren parses flags on all parents before executing child command.
129 TraverseChildren bool130

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 136why, one step back
136 parent *Command

Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 138–140why, one step back
138 commandsMaxUseLen int
139 commandsMaxCommandPathLen int140 commandsMaxNameLen int

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

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

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 142why, one step back
142 commandsAreSorted bool

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

line 143why, one step back
143

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

lines 146–161why, one step back
146 // flagErrorBuf contains all error messages from pflag.
147 flagErrorBuf *bytes.Buffer148 // flags is full set of flags.149 flags *flag.FlagSet150 // pflags contains persistent flags.151 pflags *flag.FlagSet152 // lflags contains local flags.153 lflags *flag.FlagSet154 // iflags contains inherited flags.155 iflags *flag.FlagSet156 // parentsPflags is all persistent flags of cmd's parents.157 parentsPflags *flag.FlagSet158 // globNormFunc is the global normalization function159 // that we can use on every pflag set and children commands160 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName161

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 162–169why, one step back
162 // output is an output writer defined by user.
163 output io.Writer164 // usageFunc is usage func defined by user.165 usageFunc func(*Command) error166 // usageTemplate is usage template defined by user.167 usageTemplate string168 // flagErrorFunc is func defined by user and it's called when the parsing of169 // flags returns an error.

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

lines 171–174why, one step back
171 // helpTemplate is help template defined by user.
172 helpTemplate string173 // helpFunc is help func defined by user.174 helpFunc func(*Command, []string)

Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8

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

Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 178–179why, one step back
178}
179

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 190–191why, one step back
190}
191

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 193–196why, one step back
193func (c *Command) SetUsageFunc(f func(*Command) error) {
194 c.usageFunc = f195}196

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 198–201why, one step back
198func (c *Command) SetUsageTemplate(s string) {
199 c.usageTemplate = s200}201

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

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

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

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

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

lines 204–207why, one step back
204func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
205 c.flagErrorFunc = f206}207

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 209–212why, one step back
209func (c *Command) SetHelpFunc(f func(*Command, []string)) {
210 c.helpFunc = f211}212

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 214–217why, one step back
214func (c *Command) SetHelpCommand(cmd *Command) {
215 c.helpCommand = cmd216}217

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 219–234why, one step back
219func (c *Command) SetHelpTemplate(s string) {
220 c.helpTemplate = s221}222223// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.224// The user should not have a cyclic dependency on commands.225func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {226 c.Flags().SetNormalizeFunc(n)227 c.PersistentFlags().SetNormalizeFunc(n)228 c.globNormFunc = n229230 for _, command := range c.commands {231 command.SetGlobalNormalizationFunc(n)232 }233}234

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

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

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 237–239why, one step back
237 return c.getOut(os.Stdout)
238}239

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

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

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 242–246why, one step back
242 return c.getOut(os.Stderr)
243}244245func (c *Command) getOut(def io.Writer) io.Writer {246 if c.output != nil {

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

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 248–255why, one step back
248 }
249 if c.HasParent() {250 return c.parent.getOut(def)251 }252 return def253}254255// UsageFunc returns either the function set by SetUsageFunc for this command

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 257–261why, one step back
257func (c *Command) UsageFunc() (f func(*Command) error) {
258 if c.usageFunc != nil {259 return c.usageFunc260 }261 if c.HasParent() {

Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777

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

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

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

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

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

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

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 269why, one step back
269 }

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

line 270why, one step back
270 return err

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 271–273why, one step back
271 }
272}273

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

lines 277–280why, one step back
277func (c *Command) Usage() error {
278 return c.UsageFunc()(c)279}280

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 286why, one step back
286 }

Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777

lines 287–290why, one step back
287 if c.HasParent() {
288 return c.Parent().HelpFunc()289 }290 return func(c *Command, a []string) {

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 293–298why, one step back
293 if err != nil {
294 c.Println(err)295 }296 }297}298

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

lines 302–306why, one step back
302func (c *Command) Help() error {
303 c.HelpFunc()(c, []string{})304 return nil305}306

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

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 308–311why, one step back
308func (c *Command) UsageString() string {
309 tmpOutput := c.output310 bb := new(bytes.Buffer)311 c.SetOutput(bb)

Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d

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

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

lines 313–316why, one step back
313 c.output = tmpOutput
314 return bb.String()315}316

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

lines 317–332why, one step back
317// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
318// command or a parent, or it returns a function which returns the original319// error.320func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {321 if c.flagErrorFunc != nil {322 return c.flagErrorFunc323 }324325 if c.HasParent() {326 return c.parent.FlagErrorFunc()327 }328 return func(c *Command, err error) error {329 return err330 }331}332

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 334why, one step back
334

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 336–339why, one step back
336func (c *Command) UsagePadding() int {
337 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {338 return minUsagePadding339 }

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 341–342why, one step back
341}
342

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 344why, one step back
344

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 346–349why, one step back
346func (c *Command) CommandPathPadding() int {
347 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {348 return minCommandPathPadding349 }

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 351–352why, one step back
351}
352

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 354why, one step back
354

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 356–359why, one step back
356func (c *Command) NamePadding() int {
357 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {358 return minNamePadding359 }

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 361–362why, one step back
361}
362

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 364–370why, one step back
364func (c *Command) UsageTemplate() string {
365 if c.usageTemplate != "" {366 return c.usageTemplate367 }368369 if c.HasParent() {370 return c.parent.UsageTemplate()

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

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

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 375–376why, one step back
375
376Aliases:

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 381why, one step back
381

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 384–385why, one step back
384
385Flags:

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 387–388why, one step back
387
388Global Flags:

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 390why, one step back
390

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

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

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 393–397why, one step back
393
394Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}395`396}397

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 399–405why, one step back
399func (c *Command) HelpTemplate() string {
400 if c.helpTemplate != "" {401 return c.helpTemplate402 }403404 if c.HasParent() {405 return c.parent.HelpTemplate()

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

line 406why, one step back
406 }

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 408–411why, one step back
408
409{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`410}411

Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 414–416why, one step back
414 if flag == nil {
415 return false416 }

Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 418–419why, one step back
418}
419

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

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

Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41

lines 421–429why, one step back
421 if len(name) == 0 {
422 return false423 }424425 flag := fs.ShorthandLookup(name[:1])426 if flag == nil {427 return false428 }429 return flag.NoOptDefVal != ""

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 430–432why, one step back
430}
431432func stripFlags(args []string, c *Command) []string {

Simplify stripFlags functionAlbert Nigmatzianovbefore adoption9890b7b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 434–438why, one step back
434 return args
435 }436 c.mergePersistentFlags()437438 commands := []string{}

Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6

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

Simplify stripFlags functionAlbert Nigmatzianovbefore adoption9890b7b

lines 440–443why, one step back
440
441Loop:442 for len(args) > 0 {443 s := args[0]

Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6

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

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

lines 445–457why, one step back
445 switch {
446 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):447 // If '--flag arg' then448 // delete arg from args.449 fallthrough // (do the same as below)450 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):451 // If '-f arg' then452 // delete 'arg' from args or break the loop if len(args) <= 1.453 if len(args) <= 1 {454 break Loop455 } else {456 args = args[1:]457 continue

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 458why, one step back
458 }

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 461–480why, one step back
461 }
462 }463464 return commands465}466467// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like468// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).469func argsMinusFirstX(args []string, x string) []string {470 for i, y := range args {471 if x == y {472 ret := []string{}473 ret = append(ret, args[:i]...)474 ret = append(ret, args[i+1:]...)475 return ret476 }477 }478 return args479}480

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

lines 481–485why, one step back
481func isFlagArg(arg string) bool {
482 return ((len(arg) >= 3 && arg[1] == '-') ||483 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))484}485

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 487–497why, one step back
487// Meant to be run on the highest node. Only searches down.
488func (c *Command) Find(args []string) (*Command, []string, error) {489 var innerfind func(*Command, []string) (*Command, []string)490491 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {492 argsWOflags := stripFlags(innerArgs, c)493 if len(argsWOflags) == 0 {494 return c, innerArgs495 }496 nextSubCmd := argsWOflags[0]497

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 501–505why, one step back
501 }
502 return c, innerArgs503 }504505 commandFound, a := innerfind(c, args)

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 508–509why, one step back
508 }
509 return commandFound, a, nil

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

lines 510–511why, one step back
510}
511

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

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

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

lines 513–519why, one step back
513 if c.DisableSuggestions {
514 return ""515 }516 if c.SuggestionsMinimumDistance <= 0 {517 c.SuggestionsMinimumDistance = 2518 }519 suggestionsString := ""

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

line 520why, one step back
520 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 521–526why, one step back
521 suggestionsString += "\n\nDid you mean this?\n"
522 for _, s := range suggestions {523 suggestionsString += fmt.Sprintf("\t%v\n", s)524 }525 }526 return suggestionsString

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 527–528why, one step back
527}
528

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

lines 529–588why, one step back
529func (c *Command) findNext(next string) *Command {
530 matches := make([]*Command, 0)531 for _, cmd := range c.commands {532 if cmd.Name() == next || cmd.HasAlias(next) {533 return cmd534 }535 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {536 matches = append(matches, cmd)537 }538 }539540 if len(matches) == 1 {541 return matches[0]542 }543 return nil544}545546// Traverse the command tree to find the command, and parse args for547// each parent.548func (c *Command) Traverse(args []string) (*Command, []string, error) {549 flags := []string{}550 inFlag := false551552 for i, arg := range args {553 switch {554 // A long flag with a space separated value555 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):556 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'557 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())558 flags = append(flags, arg)559 continue560 // A short flag with a space separated value561 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):562 inFlag = true563 flags = append(flags, arg)564 continue565 // The value for a flag566 case inFlag:567 inFlag = false568 flags = append(flags, arg)569 continue570 // A flag without a value, or with an `=` separated value571 case isFlagArg(arg):572 flags = append(flags, arg)573 continue574 }575576 cmd := c.findNext(arg)577 if cmd == nil {578 return c, args, nil579 }580581 if err := c.ParseFlags(flags); err != nil {582 return nil, args, err583 }584 return cmd.Traverse(args[i+1:])585 }586 return c, args, nil587}588

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 590–609why, one step back
590func (c *Command) SuggestionsFor(typedName string) []string {
591 suggestions := []string{}592 for _, cmd := range c.commands {593 if cmd.IsAvailableCommand() {594 levenshteinDistance := ld(typedName, cmd.Name(), true)595 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance596 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))597 if suggestByLevenshtein || suggestByPrefix {598 suggestions = append(suggestions, cmd.Name())599 }600 for _, explicitSuggestion := range cmd.SuggestFor {601 if strings.EqualFold(typedName, explicitSuggestion) {602 suggestions = append(suggestions, cmd.Name())603 }604 }605 }606 }607 return suggestions608}609

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 612–614why, one step back
612 if c.HasParent() {
613 fn(c.Parent())614 c.Parent().VisitParents(fn)

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 615–617why, one step back
615 }
616}617

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 622why, one step back
622 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 623why, one step back
623 return c

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 624–644why, one step back
624}
625626// ArgsLenAtDash will return the length of f.Args at the moment when a -- was627// found during arg parsing. This allows your program to know which args were628// before the -- and which came after. (Description from629// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).630func (c *Command) ArgsLenAtDash() int {631 return c.Flags().ArgsLenAtDash()632}633634func (c *Command) execute(a []string) (err error) {635 if c == nil {636 return fmt.Errorf("Called Execute() on a nil Command")637 }638639 if len(c.Deprecated) > 0 {640 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)641 }642643 // initialize help flag as the last point possible to allow for user644 // overriding

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 646–648why, one step back
646
647 err = c.ParseFlags(a)648 if err != nil {

Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 650why, one step back
650 }

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 658–660why, one step back
658 c.Println("\"help\" flag declared as non-bool. Please correct your code")
659 return err660 }

Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c

line 661why, one step back
661

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 662–666why, one step back
662 if helpVal || !c.Runnable() {
663 return flag.ErrHelp664 }665666 c.preRun()

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

line 667why, one step back
667

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

lines 669–671why, one step back
669 if c.DisableFlagParsing {
670 argWoFlags = a671 }

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 672why, one step back
672

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

lines 673–676why, one step back
673 if err := c.ValidateArgs(argWoFlags); err != nil {
674 return err675 }676

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 677–695why, one step back
677 for p := c; p != nil; p = p.Parent() {
678 if p.PersistentPreRunE != nil {679 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {680 return err681 }682 break683 } else if p.PersistentPreRun != nil {684 p.PersistentPreRun(c, argWoFlags)685 break686 }687 }688 if c.PreRunE != nil {689 if err := c.PreRunE(c, argWoFlags); err != nil {690 return err691 }692 } else if c.PreRun != nil {693 c.PreRun(c, argWoFlags)694 }695

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 696–698why, one step back
696 if err := c.validateRequiredFlags(); err != nil {
697 return err698 }

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 699–733why, one step back
699 if c.RunE != nil {
700 if err := c.RunE(c, argWoFlags); err != nil {701 return err702 }703 } else {704 c.Run(c, argWoFlags)705 }706 if c.PostRunE != nil {707 if err := c.PostRunE(c, argWoFlags); err != nil {708 return err709 }710 } else if c.PostRun != nil {711 c.PostRun(c, argWoFlags)712 }713 for p := c; p != nil; p = p.Parent() {714 if p.PersistentPostRunE != nil {715 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {716 return err717 }718 break719 } else if p.PersistentPostRun != nil {720 p.PersistentPostRun(c, argWoFlags)721 break722 }723 }724725 return nil726}727728func (c *Command) preRun() {729 for _, x := range initializers {730 x()731 }732}733

Fix typosAlbert Nigmatzianovbefore adoptione606913

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 735–741why, one step back
735// and run through the command tree finding appropriate matches
736// for commands and then corresponding flags.737func (c *Command) Execute() error {738 _, err := c.ExecuteC()739 return err740}741

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 743–755why, one step back
743func (c *Command) ExecuteC() (cmd *Command, err error) {
744 // Regardless of what command execute is called on, run on Root only745 if c.HasParent() {746 return c.Root().ExecuteC()747 }748749 // windows hook750 if preExecHookFn != nil {751 preExecHookFn(c)752 }753754 // initialize help as the last point possible to allow for user755 // overriding

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 757–766why, one step back
757
758 var args []string759760 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155761 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {762 args = os.Args[1:]763 } else {764 args = c.args765 }766

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

lines 767–772why, one step back
767 var flags []string
768 if c.TraverseChildren {769 cmd, flags, err = c.Traverse(args)770 } else {771 cmd, flags, err = c.Find(args)772 }

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 773–783why, one step back
773 if err != nil {
774 // If found parse to a subcommand and then failed, talk about the subcommand775 if cmd != nil {776 c = cmd777 }778 if !c.SilenceErrors {779 c.Println("Error:", err.Error())780 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())781 }782 return c, err783 }

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

line 784why, one step back
784

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 785–805why, one step back
785 err = cmd.execute(flags)
786 if err != nil {787 // Always show help if requested, even if SilenceErrors is in788 // effect789 if err == flag.ErrHelp {790 cmd.HelpFunc()(cmd, args)791 return cmd, nil792 }793794 // If root command has SilentErrors flagged,795 // all subcommands should respect it796 if !cmd.SilenceErrors && !c.SilenceErrors {797 c.Println("Error:", err.Error())798 }799800 // If root command has SilentUsage flagged,801 // all subcommands should respect it802 if !cmd.SilenceUsage && !c.SilenceUsage {803 c.Println(cmd.UsageString())804 }805 }

Fix typosAlbert Nigmatzianovbefore adoptione606913

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

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

lines 807–813why, one step back
807}
808809func (c *Command) ValidateArgs(args []string) error {810 if c.Args == nil {811 return nil812 }813 return c.Args(c, args)

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 814–832why, one step back
814}
815816func (c *Command) validateRequiredFlags() error {817 flags := c.Flags()818 missingFlagNames := []string{}819 flags.VisitAll(func(pflag *flag.Flag) {820 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]821 if !found {822 return823 }824 if (requiredAnnotation[0] == "true") && !pflag.Changed {825 missingFlagNames = append(missingFlagNames, pflag.Name)826 }827 })828829 if len(missingFlagNames) > 0 {830 return fmt.Errorf(`Required flag(s) "%s" have/has not been set`, strings.Join(missingFlagNames, `", "`))831 }832 return nil

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 833–834why, one step back
833}
834

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

Add comment for InitDefaultHelpFlagAlbert Nigmatzianovbefore adoptiond83a1d7

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

Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e

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

Merge pull request #286 from dnephin/merge_flags_before_adding_helpEric Parisbefore adoptionec2fe78

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Initialize help flag in initHelpCmdAlbert Nigmatzianovbefore adoption867d414

lines 841–847why, one step back
841 usage := "help for "
842 if c.Name() == "" {843 usage += "this command"844 } else {845 usage += c.Name()846 }847 c.Flags().BoolP("help", "h", false, usage)

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

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

Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02

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

Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1

lines 856–857why, one step back
856 return
857 }

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 858why, one step back
858

Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02

lines 859–863why, one step back
859 if c.helpCommand == nil {
860 c.helpCommand = &Command{861 Use: "help [command]",862 Short: "Help about any command",863 Long: `Help provides help for any command in the application.

Delete tab in the long description of helpAlbert Nigmatzianovbefore adoptiond994347

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 865why, one step back
865

Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02

lines 866–876why, one step back
866 Run: func(c *Command, args []string) {
867 cmd, _, e := c.Root().Find(args)868 if cmd == nil || e != nil {869 c.Printf("Unknown help topic %#q\n", args)870 c.Root().Usage()871 } else {872 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown873 cmd.Help()874 }875 },876 }

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 877why, one step back
877 }

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 879–881why, one step back
879 c.AddCommand(c.helpCommand)
880}881

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 885–886why, one step back
885 c.commands = nil
886 c.helpCommand = nil

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

lines 891–897why, one step back
891type commandSorterByName []*Command
892893func (c commandSorterByName) Len() int { return len(c) }894func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }895func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }896897// Commands returns a sorted slice of child commands.

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

line 899why, one step back
899 // 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 900why, one step back
900 if EnableCommandSorting && !c.commandsAreSorted {

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

lines 901–903why, one step back
901 sort.Sort(commandSorterByName(c.commands))
902 c.commandsAreSorted = true903 }

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 904–931why, one step back
904 return c.commands
905}906907// AddCommand adds one or more commands to this parent command.908func (c *Command) AddCommand(cmds ...*Command) {909 for i, x := range cmds {910 if cmds[i] == c {911 panic("Command can't be a child of itself")912 }913 cmds[i].parent = c914 // update max lengths915 usageLen := len(x.Use)916 if usageLen > c.commandsMaxUseLen {917 c.commandsMaxUseLen = usageLen918 }919 commandPathLen := len(x.CommandPath())920 if commandPathLen > c.commandsMaxCommandPathLen {921 c.commandsMaxCommandPathLen = commandPathLen922 }923 nameLen := len(x.Name())924 if nameLen > c.commandsMaxNameLen {925 c.commandsMaxNameLen = nameLen926 }927 // If global normalization function exists, update all children928 if c.globNormFunc != nil {929 x.SetGlobalNormalizationFunc(c.globNormFunc)930 }931 c.commands = append(c.commands, x)

Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 933–935why, one step back
933 }
934}935

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 937–969why, one step back
937func (c *Command) RemoveCommand(cmds ...*Command) {
938 commands := []*Command{}939main:940 for _, command := range c.commands {941 for _, cmd := range cmds {942 if command == cmd {943 command.parent = nil944 continue main945 }946 }947 commands = append(commands, command)948 }949 c.commands = commands950 // recompute all lengths951 c.commandsMaxUseLen = 0952 c.commandsMaxCommandPathLen = 0953 c.commandsMaxNameLen = 0954 for _, command := range c.commands {955 usageLen := len(command.Use)956 if usageLen > c.commandsMaxUseLen {957 c.commandsMaxUseLen = usageLen958 }959 commandPathLen := len(command.CommandPath())960 if commandPathLen > c.commandsMaxCommandPathLen {961 c.commandsMaxCommandPathLen = commandPathLen962 }963 nameLen := len(command.Name())964 if nameLen > c.commandsMaxNameLen {965 c.commandsMaxNameLen = nameLen966 }967 }968}969

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 978–979why, one step back
978}
979

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 989why, one step back
989 }

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 991–992why, one step back
991}
992

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

line 995why, one step back
995 var useline string

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 997–999why, one step back
997 useline = c.parent.CommandPath() + " " + c.Use
998 } else {999 useline = c.Use

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 1000why, one step back
1000 }

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 1001–1004why, one step back
1001 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
1002 useline += " [flags]"1003 }1004 return useline

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1005–1006why, one step back
1005}
1006

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1009–1018why, one step back
1009func (c *Command) DebugFlags() {
1010 c.Println("DebugFlags called on", c.Name())1011 var debugflags func(*Command)10121013 debugflags = func(x *Command) {1014 if x.HasFlags() || x.HasPersistentFlags() {1015 c.Println(x.Name())1016 }1017 if x.HasFlags() {1018 x.flags.VisitAll(func(f *flag.Flag) {

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1021–1036why, one step back
1021 } else {
1022 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1023 }1024 })1025 }1026 if x.HasPersistentFlags() {1027 x.pflags.VisitAll(func(f *flag.Flag) {1028 if x.HasFlags() {1029 if x.flags.Lookup(f.Name) == nil {1030 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1031 }1032 } else {1033 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1034 }1035 })1036 }

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1038–1049why, one step back
1038 if x.HasSubCommands() {
1039 for _, y := range x.commands {1040 debugflags(y)1041 }1042 }1043 }10441045 debugflags(c)1046}10471048// Name returns the command's name: the first word in the use line.1049func (c *Command) Name() string {

Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af

lines 1050–1056why, one step back
1050 if c.name == "" {
1051 name := c.Use1052 i := strings.Index(name, " ")1053 if i >= 0 {1054 name = name[:i]1055 }1056 c.name = name

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 1057why, one step back
1057 }

cache command name (#390)Di Xubefore adoptionb5d8e8f

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1059–1060why, one step back
1059}
1060

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1062–1070why, one step back
1062func (c *Command) HasAlias(s string) bool {
1063 for _, a := range c.Aliases {1064 if a == s {1065 return true1066 }1067 }1068 return false1069}1070

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

lines 1071–1085why, one step back
1071// hasNameOrAliasPrefix returns true if the Name or any of aliases start
1072// with prefix1073func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1074 if strings.HasPrefix(c.Name(), prefix) {1075 return true1076 }1077 for _, alias := range c.Aliases {1078 if strings.HasPrefix(alias, prefix) {1079 return true1080 }1081 }1082 return false1083}10841085// NameAndAliases returns a list of the command name and all aliases

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1086–1089why, one step back
1086func (c *Command) NameAndAliases() string {
1087 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1088}1089

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1091–1094why, one step back
1091func (c *Command) HasExample() bool {
1092 return len(c.Example) > 01093}1094

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1096–1099why, one step back
1096func (c *Command) Runnable() bool {
1097 return c.Run != nil || c.RunE != nil1098}1099

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1101–1105why, one step back
1101func (c *Command) HasSubCommands() bool {
1102 return len(c.commands) > 01103}11041105// IsAvailableCommand determines if a command is available as a non-help command

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1107–1122why, one step back
1107func (c *Command) IsAvailableCommand() bool {
1108 if len(c.Deprecated) != 0 || c.Hidden {1109 return false1110 }11111112 if c.HasParent() && c.Parent().helpCommand == c {1113 return false1114 }11151116 if c.Runnable() || c.HasAvailableSubCommands() {1117 return true1118 }11191120 return false1121}1122

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1129–1135why, one step back
1129 // if a command is runnable, deprecated, or hidden it is not a 'help' command
1130 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1131 return false1132 }11331134 // if any non-help sub commands are found, the command is not a 'help' command1135 for _, sub := range c.commands {

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1137–1144why, one step back
1137 return false
1138 }1139 }11401141 // the command either has no sub commands, or no non-help sub commands1142 return true1143}1144

Merge pull request #327 from bogem/fixesEric Parisbefore adoption1f47171

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1152–1160why, one step back
1152 return true
1153 }1154 }11551156 // the command either has no sub commands, or no available 'help' sub commands1157 return false1158}11591160// HasAvailableSubCommands determines if a command has available sub commands that

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1162–1175why, one step back
1162func (c *Command) HasAvailableSubCommands() bool {
1163 // return true on the first found available (non deprecated/help/hidden)1164 // sub command1165 for _, sub := range c.commands {1166 if sub.IsAvailableCommand() {1167 return true1168 }1169 }11701171 // the command either has no sub comamnds, or no available (non deprecated/help/hidden)1172 // sub commands1173 return false1174}1175

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1177–1180why, one step back
1177func (c *Command) HasParent() bool {
1178 return c.parent != nil1179}1180

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1182–1185why, one step back
1182func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
1183 return c.globNormFunc1184}1185

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

lines 1191–1194why, one step back
1191 if c.flagErrorBuf == nil {
1192 c.flagErrorBuf = new(bytes.Buffer)1193 }1194 c.flags.SetOutput(c.flagErrorBuf)

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 1195why, one step back
1195 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 1196why, one step back
1196

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1197–1199why, one step back
1197 return c.flags
1198}1199

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

line 1200why, one step back
1200// 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 1201–1212why, one step back
1201func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
1202 persistentFlags := c.PersistentFlags()12031204 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1205 c.LocalFlags().VisitAll(func(f *flag.Flag) {1206 if persistentFlags.Lookup(f.Name) == nil {1207 out.AddFlag(f)1208 }1209 })1210 return out1211}1212

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1214–1216why, one step back
1214func (c *Command) LocalFlags() *flag.FlagSet {
1215 c.mergePersistentFlags()1216

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

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

lines 1219–1222why, one step back
1219 if c.flagErrorBuf == nil {
1220 c.flagErrorBuf = new(bytes.Buffer)1221 }1222 c.lflags.SetOutput(c.flagErrorBuf)

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 1223why, one step back
1223 }

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

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

lines 1225–1227why, one step back
1225 if c.globNormFunc != nil {
1226 c.lflags.SetNormalizeFunc(c.globNormFunc)1227 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1228–1233why, one step back
1228
1229 addToLocal := func(f *flag.Flag) {1230 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1231 c.lflags.AddFlag(f)1232 }1233 }

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1237–1238why, one step back
1237}
1238

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1240–1242why, one step back
1240func (c *Command) InheritedFlags() *flag.FlagSet {
1241 c.mergePersistentFlags()1242

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

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

lines 1245–1248why, one step back
1245 if c.flagErrorBuf == nil {
1246 c.flagErrorBuf = new(bytes.Buffer)1247 }1248 c.iflags.SetOutput(c.flagErrorBuf)

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1249–1250why, one step back
1249 }
1250

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

lines 1252–1255why, one step back
1252 if c.globNormFunc != nil {
1253 c.iflags.SetNormalizeFunc(c.globNormFunc)1254 }1255

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 1259why, one step back
1259 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

lines 1260–1261why, one step back
1260 })
1261 return c.iflags

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1262–1263why, one step back
1262}
1263

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1265–1268why, one step back
1265func (c *Command) NonInheritedFlags() *flag.FlagSet {
1266 return c.LocalFlags()1267}1268

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

lines 1273–1276why, one step back
1273 if c.flagErrorBuf == nil {
1274 c.flagErrorBuf = new(bytes.Buffer)1275 }1276 c.pflags.SetOutput(c.flagErrorBuf)

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1277–1280why, one step back
1277 }
1278 return c.pflags1279}1280

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

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

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

lines 1289–1292why, one step back
1289
1290 c.lflags = nil1291 c.iflags = nil1292 c.parentsPflags = nil

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1293–1294why, one step back
1293}
1294

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1296–1299why, one step back
1296func (c *Command) HasFlags() bool {
1297 return c.Flags().HasFlags()1298}1299

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1301–1304why, one step back
1301func (c *Command) HasPersistentFlags() bool {
1302 return c.PersistentFlags().HasFlags()1303}1304

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1306–1309why, one step back
1306func (c *Command) HasLocalFlags() bool {
1307 return c.LocalFlags().HasFlags()1308}1309

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

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

lines 1313–1314why, one step back
1313}
1314

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

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

lines 1317–1320why, one step back
1317func (c *Command) HasAvailableFlags() bool {
1318 return c.Flags().HasAvailableFlags()1319}1320

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

line 1321why, one step back
1321// 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 1322–1325why, one step back
1322func (c *Command) HasAvailablePersistentFlags() bool {
1323 return c.PersistentFlags().HasAvailableFlags()1324}1325

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

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

lines 1328–1331why, one step back
1328func (c *Command) HasAvailableLocalFlags() bool {
1329 return c.LocalFlags().HasAvailableFlags()1330}1331

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

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

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

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

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1336–1337why, one step back
1336}
1337

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1339–1348why, one step back
1339func (c *Command) Flag(name string) (flag *flag.Flag) {
1340 flag = c.Flags().Lookup(name)13411342 if flag == nil {1343 flag = c.persistentFlag(name)1344 }13451346 return1347}1348

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1350–1354why, one step back
1350func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
1351 if c.HasPersistentFlags() {1352 flag = c.PersistentFlags().Lookup(name)1353 }1354

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

lines 1355–1357why, one step back
1355 if flag == nil {
1356 c.updateParentsPflags()1357 flag = c.parentsPflags.Lookup(name)

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1358–1361why, one step back
1358 }
1359 return1360}1361

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83

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

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

lines 1364–1366why, one step back
1364 if c.DisableFlagParsing {
1365 return nil1366 }

Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83

lines 1367–1368why, one step back
1367
1368 beforeErrorBufLen := c.flagErrorBuf.Len()

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

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

Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83

lines 1370–1376why, one step back
1370 err := c.Flags().Parse(args)
1371 // Print warnings if they occurred (e.g. deprecated flag messages).1372 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1373 c.Print(c.flagErrorBuf.String())1374 }13751376 return err

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1377–1378why, one step back
1377}
1378

Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b

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

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

lines 1380–1383why, one step back
1380func (c *Command) Parent() *Command {
1381 return c.parent1382}1383

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

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

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

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

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

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

lines 1390–1392why, one step back
1390}
13911392// updateParentsPflags updates c.parentsPflags by adding

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

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

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

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

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

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

Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4

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

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

lines 1400–1403why, one step back
1400 }
14011402 if c.globNormFunc != nil {1403 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 1404why, one step back
1404 }

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 1405why, one step back
1405

Add merging of CommandLine flags to Root commandAlbert Nigmatzianovbefore adoption458d797

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

Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867

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

Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59

line 1410why, one step back
1410 })

Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c

line 1411why, one step back
1411}