Skip to content
Myr

command.go

This file

Path

command.go

1,638 lines · 45.1 KiB · Go

Last changed by

Ignore required flags when DisableFlagParsing (#1095)Marc Khouzambefore adoption5155946

History of this file

Take it

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1–19why, 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.1314// 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.16package cobra1718import (19 "bytes"

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

line 20why, one step back
20 "context"

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 21–30why, one step back
21 "fmt"
22 "io"23 "os"24 "path/filepath"25 "sort"26 "strings"2728 flag "github.com/spf13/pflag"29)30

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

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 34–59why, one step back
34// Command is just that, a command for your application.
35// E.g. 'go run ...' - 'run' is the command. Cobra requires36// you to define the usage and description as part of your command37// definition to ensure usability.38type Command struct {39 // Use is the one-line usage message.40 Use string4142 // Aliases is an array of aliases that can be used instead of the first word in Use.43 Aliases []string4445 // SuggestFor is an array of command names for which this command will be suggested -46 // similar to aliases but only suggests.47 SuggestFor []string4849 // Short is the short description shown in the 'help' output.50 Short string5152 // Long is the long message shown in the 'help <this-command>' output.53 Long string5455 // Example is examples of how to use the command.56 Example string5758 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions59 ValidArgs []string

Add support for custom completions in Go (#1035)Marc Khouzambefore adoptionb80aeb1

lines 60–62why, one step back
60 // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.
61 // It is a dynamic version of using ValidArgs.62 // Only one of ValidArgs and ValidArgsFunction can be used for a command.

Rename BashCompDirectives to ShellCompDirectives (#1082)Marc Khouzambefore adoptionb84ef40

line 63why, one step back
63 ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

line 64why, one step back
64

Update documentationAlbert Nigmatzianovbefore adoption1723331

lines 65–67why, one step back
65 // Expected arguments
66 Args PositionalArgs67

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 68–85why, one step back
68 // ArgAliases is List of aliases for ValidArgs.
69 // These are not suggested to the user in the bash completion,70 // but accepted if entered manually.71 ArgAliases []string7273 // BashCompletionFunction is custom functions used by the bash autocompletion generator.74 BashCompletionFunction string7576 // Deprecated defines, if this command is deprecated and should print this string when used.77 Deprecated string7879 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.80 Hidden bool8182 // Annotations are key/value pairs that can be used by applications to identify or83 // group commands.84 Annotations map[string]string85

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

lines 86–87why, one step back
86 // Version defines the version for this command. If this value is non-empty and the command does not
87 // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,

Add short version flag -v when not otherwise set (#996)Dave Hendersonbefore adoption95f2f73

lines 88–89why, one step back
88 // will print content of the "Version" variable. A shorthand "v" flag will also be added if the
89 // command does not define one.

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

lines 90–91why, one step back
90 Version string
91

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 92–134why, one step back
92 // The *Run functions are executed in the following order:
93 // * PersistentPreRun()94 // * PreRun()95 // * Run()96 // * PostRun()97 // * PersistentPostRun()98 // All functions get the same args, the arguments after the command name.99 //100 // PersistentPreRun: children of this command will inherit and execute.101 PersistentPreRun func(cmd *Command, args []string)102 // PersistentPreRunE: PersistentPreRun but returns an error.103 PersistentPreRunE func(cmd *Command, args []string) error104 // PreRun: children of this command will not inherit.105 PreRun func(cmd *Command, args []string)106 // PreRunE: PreRun but returns an error.107 PreRunE func(cmd *Command, args []string) error108 // Run: Typically the actual work function. Most commands will only implement this.109 Run func(cmd *Command, args []string)110 // RunE: Run but returns an error.111 RunE func(cmd *Command, args []string) error112 // PostRun: run after the Run command.113 PostRun func(cmd *Command, args []string)114 // PostRunE: PostRun but returns an error.115 PostRunE func(cmd *Command, args []string) error116 // PersistentPostRun: children of this command will inherit and execute after PostRun.117 PersistentPostRun func(cmd *Command, args []string)118 // PersistentPostRunE: PersistentPostRun but returns an error.119 PersistentPostRunE func(cmd *Command, args []string) error120121 // SilenceErrors is an option to quiet errors down stream.122 SilenceErrors bool123124 // SilenceUsage is an option to silence usage when an error occurs.125 SilenceUsage bool126127 // DisableFlagParsing disables the flag parsing.128 // If this is true all flags will be passed to the command as arguments.129 DisableFlagParsing bool130131 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")132 // will be printed by generating docs for this command.133 DisableAutoGenTag bool134

Disable flags in UseLine (#552)Daniel Nephinbefore adoption34ceca5

lines 135–138why, one step back
135 // DisableFlagsInUseLine will disable the addition of [flags] to the usage
136 // line of a command when printing help or generating docs137 DisableFlagsInUseLine bool138

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 139–145why, one step back
139 // DisableSuggestions disables the suggestions based on Levenshtein distance
140 // that go along with 'unknown command' messages.141 DisableSuggestions bool142 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.143 // Must be > 0.144 SuggestionsMinimumDistance int145

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

lines 146–148why, one step back
146 // TraverseChildren parses flags on all parents before executing child command.
147 TraverseChildren bool148

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

line 149why, one step back
149 // FParseErrWhitelist flag parse errors to be ignored

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

lines 150–151why, one step back
150 FParseErrWhitelist FParseErrWhitelist
151

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 152–153why, one step back
152 ctx context.Context
153

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 154–163why, one step back
154 // commands is the list of commands supported by this program.
155 commands []*Command156 // parent is a parent command for this command.157 parent *Command158 // Max lengths of commands' string lengths for use in padding.159 commandsMaxUseLen int160 commandsMaxCommandPathLen int161 commandsMaxNameLen int162 // commandsAreSorted defines, if command slice are sorted or not.163 commandsAreSorted bool

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

lines 164–168why, one step back
164 // commandCalledAs is the name or alias value used to call this command.
165 commandCalledAs struct {166 name string167 called bool168 }

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 169–201why, one step back
169
170 // args is actual args parsed from flags.171 args []string172 // flagErrorBuf contains all error messages from pflag.173 flagErrorBuf *bytes.Buffer174 // flags is full set of flags.175 flags *flag.FlagSet176 // pflags contains persistent flags.177 pflags *flag.FlagSet178 // lflags contains local flags.179 lflags *flag.FlagSet180 // iflags contains inherited flags.181 iflags *flag.FlagSet182 // parentsPflags is all persistent flags of cmd's parents.183 parentsPflags *flag.FlagSet184 // globNormFunc is the global normalization function185 // that we can use on every pflag set and children commands186 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName187188 // usageFunc is usage func defined by user.189 usageFunc func(*Command) error190 // usageTemplate is usage template defined by user.191 usageTemplate string192 // flagErrorFunc is func defined by user and it's called when the parsing of193 // flags returns an error.194 flagErrorFunc func(*Command, error) error195 // helpTemplate is help template defined by user.196 helpTemplate string197 // helpFunc is help func defined by user.198 helpFunc func(*Command, []string)199 // helpCommand is command with usage 'help'. If it's not defined by user,200 // cobra uses default help command.201 helpCommand *Command

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

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 204–210why, one step back
204
205 // inReader is a reader defined by the user that replaces stdin206 inReader io.Reader207 // outWriter is a writer defined by the user that replaces stdout208 outWriter io.Writer209 // errWriter is a writer defined by the user that replaces stderr210 errWriter io.Writer

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

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

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 213–218why, one step back
213// Context returns underlying command context. If command wasn't
214// executed with ExecuteContext Context returns Background context.215func (c *Command) Context() context.Context {216 return c.ctx217}218

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 219–226why, one step back
219// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
220// particularly useful when testing.221func (c *Command) SetArgs(a []string) {222 c.args = a223}224225// SetOutput sets the destination for usage and error messages.226// If output is nil, os.Stderr is used.

Deprecate and maintain backwards compatibilityJuan Lenibefore adoptioncb27ce1

line 227why, one step back
227// Deprecated: Use SetOut and/or SetErr instead

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

line 228why, one step back
228func (c *Command) SetOutput(output io.Writer) {

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

line 229why, one step back
229 c.outWriter = output

Deprecate and maintain backwards compatibilityJuan Lenibefore adoptioncb27ce1

line 230why, one step back
230 c.errWriter = output

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 231–232why, one step back
231}
232

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 233–235why, one step back
233// SetOut sets the destination for usage messages.
234// If newOut is nil, os.Stdout is used.235func (c *Command) SetOut(newOut io.Writer) {

Fixed linter issuesJuan Lenibefore adoption0ea93dd

line 236why, one step back
236 c.outWriter = newOut

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 237–240why, one step back
237}
238239// SetErr sets the destination for error messages.240// If newErr is nil, os.Stderr is used.

Fixed linter issuesJuan Lenibefore adoption0ea93dd

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 242–244why, one step back
242 c.errWriter = newErr
243}244

Correct all complaints from golintBruce Downsbefore adoption51f06c7

line 245why, one step back
245// SetIn sets the source for input data

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 246–250why, one step back
246// If newIn is nil, os.Stdin is used.
247func (c *Command) SetIn(newIn io.Reader) {248 c.inReader = newIn249}250

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 251–281why, one step back
251// SetUsageFunc sets usage function. Usage can be defined by application.
252func (c *Command) SetUsageFunc(f func(*Command) error) {253 c.usageFunc = f254}255256// SetUsageTemplate sets usage template. Can be defined by Application.257func (c *Command) SetUsageTemplate(s string) {258 c.usageTemplate = s259}260261// SetFlagErrorFunc sets a function to generate an error when flag parsing262// fails.263func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {264 c.flagErrorFunc = f265}266267// SetHelpFunc sets help function. Can be defined by Application.268func (c *Command) SetHelpFunc(f func(*Command, []string)) {269 c.helpFunc = f270}271272// SetHelpCommand sets help command.273func (c *Command) SetHelpCommand(cmd *Command) {274 c.helpCommand = cmd275}276277// SetHelpTemplate sets help template to be used. Application can use it to set custom template.278func (c *Command) SetHelpTemplate(s string) {279 c.helpTemplate = s280}281

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

lines 282–286why, one step back
282// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
283func (c *Command) SetVersionTemplate(s string) {284 c.versionTemplate = s285}286

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 287–308why, one step back
287// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
288// The user should not have a cyclic dependency on commands.289func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {290 c.Flags().SetNormalizeFunc(n)291 c.PersistentFlags().SetNormalizeFunc(n)292 c.globNormFunc = n293294 for _, command := range c.commands {295 command.SetGlobalNormalizationFunc(n)296 }297}298299// OutOrStdout returns output to stdout.300func (c *Command) OutOrStdout() io.Writer {301 return c.getOut(os.Stdout)302}303304// OutOrStderr returns output to stderr305func (c *Command) OutOrStderr() io.Writer {306 return c.getOut(os.Stderr)307}308

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 309–313why, one step back
309// ErrOrStderr returns output to stderr
310func (c *Command) ErrOrStderr() io.Writer {311 return c.getErr(os.Stderr)312}313

Correct documentation for InOrStdin (#929)Daniel Espondabefore adoption3c26245

line 314why, one step back
314// InOrStdin returns input to stdin

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 315–318why, one step back
315func (c *Command) InOrStdin() io.Reader {
316 return c.getIn(os.Stdin)317}318

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

line 319why, one step back
319func (c *Command) getOut(def io.Writer) io.Writer {

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 320–321why, one step back
320 if c.outWriter != nil {
321 return c.outWriter

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 322–328why, one step back
322 }
323 if c.HasParent() {324 return c.parent.getOut(def)325 }326 return def327}328

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 329–348why, one step back
329func (c *Command) getErr(def io.Writer) io.Writer {
330 if c.errWriter != nil {331 return c.errWriter332 }333 if c.HasParent() {334 return c.parent.getErr(def)335 }336 return def337}338339func (c *Command) getIn(def io.Reader) io.Reader {340 if c.inReader != nil {341 return c.inReader342 }343 if c.HasParent() {344 return c.parent.getIn(def)345 }346 return def347}348

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 349–385why, one step back
349// UsageFunc returns either the function set by SetUsageFunc for this command
350// or a parent, or it returns a default usage function.351func (c *Command) UsageFunc() (f func(*Command) error) {352 if c.usageFunc != nil {353 return c.usageFunc354 }355 if c.HasParent() {356 return c.Parent().UsageFunc()357 }358 return func(c *Command) error {359 c.mergePersistentFlags()360 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)361 if err != nil {362 c.Println(err)363 }364 return err365 }366}367368// Usage puts out the usage for the command.369// Used when a user provides invalid input.370// Can be defined by user by overriding UsageFunc.371func (c *Command) Usage() error {372 return c.UsageFunc()(c)373}374375// HelpFunc returns either the function set by SetHelpFunc for this command376// or a parent, or it returns a function with default help behavior.377func (c *Command) HelpFunc() func(*Command, []string) {378 if c.helpFunc != nil {379 return c.helpFunc380 }381 if c.HasParent() {382 return c.Parent().HelpFunc()383 }384 return func(c *Command, a []string) {385 c.mergePersistentFlags()

Revert change so help is printed on stdout again (#1004)Marc Khouzambefore adoption0d9d2d4

lines 386–388why, one step back
386 // The help should be sent to stdout
387 // See https://github.com/spf13/cobra/issues/1002388 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 389–402why, one step back
389 if err != nil {
390 c.Println(err)391 }392 }393}394395// Help puts out the help for the command.396// Used when a user calls help [command].397// Can be defined by user by overriding HelpFunc.398func (c *Command) Help() error {399 c.HelpFunc()(c, []string{})400 return nil401}402

considering stderr in UsageStringJuan Lenibefore adoptionb635726

line 403why, one step back
403// UsageString returns usage string.

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

line 404why, one step back
404func (c *Command) UsageString() string {

considering stderr in UsageStringJuan Lenibefore adoptionb635726

line 405why, one step back
405 // Storing normal writers

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

line 406why, one step back
406 tmpOutput := c.outWriter

considering stderr in UsageStringJuan Lenibefore adoptionb635726

lines 407–408why, one step back
407 tmpErr := c.errWriter
408

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

line 409why, one step back
409 bb := new(bytes.Buffer)

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

line 410why, one step back
410 c.outWriter = bb

considering stderr in UsageStringJuan Lenibefore adoptionb635726

lines 411–412why, one step back
411 c.errWriter = bb
412

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

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

considering stderr in UsageStringJuan Lenibefore adoptionb635726

lines 414–415why, one step back
414
415 // Setting things back to normal

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

line 416why, one step back
416 c.outWriter = tmpOutput

considering stderr in UsageStringJuan Lenibefore adoptionb635726

lines 417–418why, one step back
417 c.errWriter = tmpErr
418

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 419–516why, one step back
419 return bb.String()
420}421422// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this423// command or a parent, or it returns a function which returns the original424// error.425func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {426 if c.flagErrorFunc != nil {427 return c.flagErrorFunc428 }429430 if c.HasParent() {431 return c.parent.FlagErrorFunc()432 }433 return func(c *Command, err error) error {434 return err435 }436}437438var minUsagePadding = 25439440// UsagePadding return padding for the usage.441func (c *Command) UsagePadding() int {442 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {443 return minUsagePadding444 }445 return c.parent.commandsMaxUseLen446}447448var minCommandPathPadding = 11449450// CommandPathPadding return padding for the command path.451func (c *Command) CommandPathPadding() int {452 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {453 return minCommandPathPadding454 }455 return c.parent.commandsMaxCommandPathLen456}457458var minNamePadding = 11459460// NamePadding returns padding for the name.461func (c *Command) NamePadding() int {462 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {463 return minNamePadding464 }465 return c.parent.commandsMaxNameLen466}467468// UsageTemplate returns usage template for the command.469func (c *Command) UsageTemplate() string {470 if c.usageTemplate != "" {471 return c.usageTemplate472 }473474 if c.HasParent() {475 return c.parent.UsageTemplate()476 }477 return `Usage:{{if .Runnable}}478 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}479 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}480481Aliases:482 {{.NameAndAliases}}{{end}}{{if .HasExample}}483484Examples:485{{.Example}}{{end}}{{if .HasAvailableSubCommands}}486487Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}488 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}489490Flags:491{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}492493Global Flags:494{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}495496Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}497 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}498499Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}500`501}502503// HelpTemplate return help template for the command.504func (c *Command) HelpTemplate() string {505 if c.helpTemplate != "" {506 return c.helpTemplate507 }508509 if c.HasParent() {510 return c.parent.HelpTemplate()511 }512 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}513514{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`515}516

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

lines 517–529why, one step back
517// VersionTemplate return version template for the command.
518func (c *Command) VersionTemplate() string {519 if c.versionTemplate != "" {520 return c.versionTemplate521 }522523 if c.HasParent() {524 return c.parent.VersionTemplate()525 }526 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}527`528}529

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 530–563why, one step back
530func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
531 flag := fs.Lookup(name)532 if flag == nil {533 return false534 }535 return flag.NoOptDefVal != ""536}537538func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {539 if len(name) == 0 {540 return false541 }542543 flag := fs.ShorthandLookup(name[:1])544 if flag == nil {545 return false546 }547 return flag.NoOptDefVal != ""548}549550func stripFlags(args []string, c *Command) []string {551 if len(args) == 0 {552 return args553 }554 c.mergePersistentFlags()555556 commands := []string{}557 flags := c.Flags()558559Loop:560 for len(args) > 0 {561 s := args[0]562 args = args[1:]563 switch {

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

lines 564–566why, one step back
564 case s == "--":
565 // "--" terminates the flags566 break Loop

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 567–601why, one step back
567 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
568 // If '--flag arg' then569 // delete arg from args.570 fallthrough // (do the same as below)571 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):572 // If '-f arg' then573 // delete 'arg' from args or break the loop if len(args) <= 1.574 if len(args) <= 1 {575 break Loop576 } else {577 args = args[1:]578 continue579 }580 case s != "" && !strings.HasPrefix(s, "-"):581 commands = append(commands, s)582 }583 }584585 return commands586}587588// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like589// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).590func argsMinusFirstX(args []string, x string) []string {591 for i, y := range args {592 if x == y {593 ret := []string{}594 ret = append(ret, args[:i]...)595 ret = append(ret, args[i+1:]...)596 return ret597 }598 }599 return args600}601

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

lines 602–606why, one step back
602func isFlagArg(arg string) bool {
603 return ((len(arg) >= 3 && arg[1] == '-') ||604 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))605}606

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 607–618why, one step back
607// Find the target command given the args and command tree
608// Meant to be run on the highest node. Only searches down.609func (c *Command) Find(args []string) (*Command, []string, error) {610 var innerfind func(*Command, []string) (*Command, []string)611612 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {613 argsWOflags := stripFlags(innerArgs, c)614 if len(argsWOflags) == 0 {615 return c, innerArgs616 }617 nextSubCmd := argsWOflags[0]618

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

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 622–649why, one step back
622 }
623 return c, innerArgs624 }625626 commandFound, a := innerfind(c, args)627 if commandFound.Args == nil {628 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))629 }630 return commandFound, a, nil631}632633func (c *Command) findSuggestions(arg string) string {634 if c.DisableSuggestions {635 return ""636 }637 if c.SuggestionsMinimumDistance <= 0 {638 c.SuggestionsMinimumDistance = 2639 }640 suggestionsString := ""641 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {642 suggestionsString += "\n\nDid you mean this?\n"643 for _, s := range suggestions {644 suggestionsString += fmt.Sprintf("\t%v\n", s)645 }646 }647 return suggestionsString648}649

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

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

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

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

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

lines 655–664why, one step back
655 return cmd
656 }657 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {658 matches = append(matches, cmd)659 }660 }661662 if len(matches) == 1 {663 return matches[0]664 }

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

line 665why, one step back
665

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

lines 666–711why, one step back
666 return nil
667}668669// Traverse the command tree to find the command, and parse args for670// each parent.671func (c *Command) Traverse(args []string) (*Command, []string, error) {672 flags := []string{}673 inFlag := false674675 for i, arg := range args {676 switch {677 // A long flag with a space separated value678 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):679 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'680 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())681 flags = append(flags, arg)682 continue683 // A short flag with a space separated value684 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):685 inFlag = true686 flags = append(flags, arg)687 continue688 // The value for a flag689 case inFlag:690 inFlag = false691 flags = append(flags, arg)692 continue693 // A flag without a value, or with an `=` separated value694 case isFlagArg(arg):695 flags = append(flags, arg)696 continue697 }698699 cmd := c.findNext(arg)700 if cmd == nil {701 return c, args, nil702 }703704 if err := c.ParseFlags(flags); err != nil {705 return nil, args, err706 }707 return cmd.Traverse(args[i+1:])708 }709 return c, args, nil710}711

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 712–748why, one step back
712// SuggestionsFor provides suggestions for the typedName.
713func (c *Command) SuggestionsFor(typedName string) []string {714 suggestions := []string{}715 for _, cmd := range c.commands {716 if cmd.IsAvailableCommand() {717 levenshteinDistance := ld(typedName, cmd.Name(), true)718 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance719 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))720 if suggestByLevenshtein || suggestByPrefix {721 suggestions = append(suggestions, cmd.Name())722 }723 for _, explicitSuggestion := range cmd.SuggestFor {724 if strings.EqualFold(typedName, explicitSuggestion) {725 suggestions = append(suggestions, cmd.Name())726 }727 }728 }729 }730 return suggestions731}732733// VisitParents visits all parents of the command and invokes fn on each parent.734func (c *Command) VisitParents(fn func(*Command)) {735 if c.HasParent() {736 fn(c.Parent())737 c.Parent().VisitParents(fn)738 }739}740741// Root finds root command.742func (c *Command) Root() *Command {743 if c.HasParent() {744 return c.Parent().Root()745 }746 return c747}748

Improve testsAlbert Nigmatzianovbefore adoption65c8acb

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 751–763why, one step back
751func (c *Command) ArgsLenAtDash() int {
752 return c.Flags().ArgsLenAtDash()753}754755func (c *Command) execute(a []string) (err error) {756 if c == nil {757 return fmt.Errorf("Called Execute() on a nil Command")758 }759760 if len(c.Deprecated) > 0 {761 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)762 }763

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

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 765–766why, one step back
765 // overriding
766 c.InitDefaultHelpFlag()

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

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 768–783why, one step back
768
769 err = c.ParseFlags(a)770 if err != nil {771 return c.FlagErrorFunc()(c, err)772 }773774 // If help is called, regardless of other flags, return we want help.775 // Also say we need help if the command isn't runnable.776 helpVal, err := c.Flags().GetBool("help")777 if err != nil {778 // should be impossible to get here as we always declare a help779 // flag in InitDefaultHelpFlag()780 c.Println("\"help\" flag declared as non-bool. Please correct your code")781 return err782 }783

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

line 784why, one step back
784 if helpVal {

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 785–787why, one step back
785 return flag.ErrHelp
786 }787

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

lines 788–801why, one step back
788 // for back-compat, only add version flag behavior if version is defined
789 if c.Version != "" {790 versionVal, err := c.Flags().GetBool("version")791 if err != nil {792 c.Println("\"version\" flag declared as non-bool. Please correct your code")793 return err794 }795 if versionVal {796 err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)797 if err != nil {798 c.Println(err)799 }800 return err801 }

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

lines 802–804why, one step back
802 }
803804 if !c.Runnable() {

Partial Revert of #922 (#1068)Joshua Harshmanbefore adoption6607e6b

line 805why, one step back
805 return flag.ErrHelp

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

lines 806–807why, one step back
806 }
807

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 808–837why, one step back
808 c.preRun()
809810 argWoFlags := c.Flags().Args()811 if c.DisableFlagParsing {812 argWoFlags = a813 }814815 if err := c.ValidateArgs(argWoFlags); err != nil {816 return err817 }818819 for p := c; p != nil; p = p.Parent() {820 if p.PersistentPreRunE != nil {821 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {822 return err823 }824 break825 } else if p.PersistentPreRun != nil {826 p.PersistentPreRun(c, argWoFlags)827 break828 }829 }830 if c.PreRunE != nil {831 if err := c.PreRunE(c, argWoFlags); err != nil {832 return err833 }834 } else if c.PreRun != nil {835 c.PreRun(c, argWoFlags)836 }837

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 838–840why, one step back
838 if err := c.validateRequiredFlags(); err != nil {
839 return err840 }

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 841–875why, one step back
841 if c.RunE != nil {
842 if err := c.RunE(c, argWoFlags); err != nil {843 return err844 }845 } else {846 c.Run(c, argWoFlags)847 }848 if c.PostRunE != nil {849 if err := c.PostRunE(c, argWoFlags); err != nil {850 return err851 }852 } else if c.PostRun != nil {853 c.PostRun(c, argWoFlags)854 }855 for p := c; p != nil; p = p.Parent() {856 if p.PersistentPostRunE != nil {857 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {858 return err859 }860 break861 } else if p.PersistentPostRun != nil {862 p.PersistentPostRun(c, argWoFlags)863 break864 }865 }866867 return nil868}869870func (c *Command) preRun() {871 for _, x := range initializers {872 x()873 }874}875

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 876–882why, one step back
876// ExecuteContext is the same as Execute(), but sets the ctx on the command.
877// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle functions.878func (c *Command) ExecuteContext(ctx context.Context) error {879 c.ctx = ctx880 return c.Execute()881}882

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 883–892why, one step back
883// Execute uses the args (os.Args[1:] by default)
884// and run through the command tree finding appropriate matches885// for commands and then corresponding flags.886func (c *Command) Execute() error {887 _, err := c.ExecuteC()888 return err889}890891// ExecuteC executes the command.892func (c *Command) ExecuteC() (cmd *Command, err error) {

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 893–896why, one step back
893 if c.ctx == nil {
894 c.ctx = context.Background()895 }896

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 897–910why, one step back
897 // Regardless of what command execute is called on, run on Root only
898 if c.HasParent() {899 return c.Root().ExecuteC()900 }901902 // windows hook903 if preExecHookFn != nil {904 preExecHookFn(c)905 }906907 // initialize help as the last point possible to allow for user908 // overriding909 c.InitDefaultHelpCmd()910

[TrivialPatches] Typos in README.md, fix and update CI, update projects list... (#840)umarcorbefore adoption5755ecf

line 911why, one step back
911 args := c.args

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 912–916why, one step back
912
913 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155914 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {915 args = os.Args[1:]916 }

Add support for custom completions in Go (#1035)Marc Khouzambefore adoptionb80aeb1

lines 917–919why, one step back
917
918 // initialize the hidden command to be used for bash completion919 c.initCompleteCmd(args)

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

line 920why, one step back
920

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

lines 921–926why, one step back
921 var flags []string
922 if c.TraverseChildren {923 cmd, flags, err = c.Traverse(args)924 } else {925 cmd, flags, err = c.Find(args)926 }

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 927–937why, one step back
927 if err != nil {
928 // If found parse to a subcommand and then failed, talk about the subcommand929 if cmd != nil {930 c = cmd931 }932 if !c.SilenceErrors {933 c.Println("Error:", err.Error())934 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())935 }936 return c, err937 }

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

line 938why, one step back
938

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

lines 939–943why, one step back
939 cmd.commandCalledAs.called = true
940 if cmd.commandCalledAs.name == "" {941 cmd.commandCalledAs.name = cmd.Name()942 }943

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 944–949why, one step back
944 // We have to pass global context to children command
945 // if context is present on the parent command.946 if cmd.ctx == nil {947 cmd.ctx = c.ctx948 }949

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 950–978why, one step back
950 err = cmd.execute(flags)
951 if err != nil {952 // Always show help if requested, even if SilenceErrors is in953 // effect954 if err == flag.ErrHelp {955 cmd.HelpFunc()(cmd, args)956 return cmd, nil957 }958959 // If root command has SilentErrors flagged,960 // all subcommands should respect it961 if !cmd.SilenceErrors && !c.SilenceErrors {962 c.Println("Error:", err.Error())963 }964965 // If root command has SilentUsage flagged,966 // all subcommands should respect it967 if !cmd.SilenceUsage && !c.SilenceUsage {968 c.Println(cmd.UsageString())969 }970 }971 return cmd, err972}973974func (c *Command) ValidateArgs(args []string) error {975 if c.Args == nil {976 return nil977 }978 return c.Args(c, args)

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 979–981why, one step back
979}
980981func (c *Command) validateRequiredFlags() error {

Ignore required flags when DisableFlagParsing (#1095)Marc Khouzambefore adoption5155946

lines 982–985why, one step back
982 if c.DisableFlagParsing {
983 return nil984 }985

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 986–998why, one step back
986 flags := c.Flags()
987 missingFlagNames := []string{}988 flags.VisitAll(func(pflag *flag.Flag) {989 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]990 if !found {991 return992 }993 if (requiredAnnotation[0] == "true") && !pflag.Changed {994 missingFlagNames = append(missingFlagNames, pflag.Name)995 }996 })997998 if len(missingFlagNames) > 0 {

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

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

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 1000–1001why, one step back
1000 }
1001 return nil

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1002–1016why, one step back
1002}
10031004// InitDefaultHelpFlag adds default help flag to c.1005// It is called automatically by executing the c or by calling help and usage.1006// If c already has help flag, it will do nothing.1007func (c *Command) InitDefaultHelpFlag() {1008 c.mergePersistentFlags()1009 if c.Flags().Lookup("help") == nil {1010 usage := "help for "1011 if c.Name() == "" {1012 usage += "this command"1013 } else {1014 usage += c.Name()1015 }1016 c.Flags().BoolP("help", "h", false, usage)

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

lines 1017–1036why, one step back
1017 }
1018}10191020// InitDefaultVersionFlag adds default version flag to c.1021// It is called automatically by executing the c.1022// If c already has a version flag, it will do nothing.1023// If c.Version is empty, it will do nothing.1024func (c *Command) InitDefaultVersionFlag() {1025 if c.Version == "" {1026 return1027 }10281029 c.mergePersistentFlags()1030 if c.Flags().Lookup("version") == nil {1031 usage := "version for "1032 if c.Name() == "" {1033 usage += "this command"1034 } else {1035 usage += c.Name()1036 }

Add short version flag -v when not otherwise set (#996)Dave Hendersonbefore adoption95f2f73

lines 1037–1041why, one step back
1037 if c.Flags().ShorthandLookup("v") == nil {
1038 c.Flags().BoolP("version", "v", false, usage)1039 } else {1040 c.Flags().Bool("version", false, usage)1041 }

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1042–1075why, one step back
1042 }
1043}10441045// InitDefaultHelpCmd adds default help command to c.1046// It is called automatically by executing the c or by calling help and usage.1047// If c already has help command or c has no subcommands, it will do nothing.1048func (c *Command) InitDefaultHelpCmd() {1049 if !c.HasSubCommands() {1050 return1051 }10521053 if c.helpCommand == nil {1054 c.helpCommand = &Command{1055 Use: "help [command]",1056 Short: "Help about any command",1057 Long: `Help provides help for any command in the application.1058Simply type ` + c.Name() + ` help [path to command] for full details.`,10591060 Run: func(c *Command, args []string) {1061 cmd, _, e := c.Root().Find(args)1062 if cmd == nil || e != nil {1063 c.Printf("Unknown help topic %#q\n", args)1064 c.Root().Usage()1065 } else {1066 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1067 cmd.Help()1068 }1069 },1070 }1071 }1072 c.RemoveCommand(c.helpCommand)1073 c.AddCommand(c.helpCommand)1074}1075

Edit ResetFlags and ResetCommands descriptionsAlbert Nigmatzianovbefore adoptiond6a4305

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

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

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

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1079–1178why, one step back
1079 c.commands = nil
1080 c.helpCommand = nil1081 c.parentsPflags = nil1082}10831084// Sorts commands by their names.1085type commandSorterByName []*Command10861087func (c commandSorterByName) Len() int { return len(c) }1088func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }1089func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }10901091// Commands returns a sorted slice of child commands.1092func (c *Command) Commands() []*Command {1093 // do not sort commands if it already sorted or sorting was disabled1094 if EnableCommandSorting && !c.commandsAreSorted {1095 sort.Sort(commandSorterByName(c.commands))1096 c.commandsAreSorted = true1097 }1098 return c.commands1099}11001101// AddCommand adds one or more commands to this parent command.1102func (c *Command) AddCommand(cmds ...*Command) {1103 for i, x := range cmds {1104 if cmds[i] == c {1105 panic("Command can't be a child of itself")1106 }1107 cmds[i].parent = c1108 // update max lengths1109 usageLen := len(x.Use)1110 if usageLen > c.commandsMaxUseLen {1111 c.commandsMaxUseLen = usageLen1112 }1113 commandPathLen := len(x.CommandPath())1114 if commandPathLen > c.commandsMaxCommandPathLen {1115 c.commandsMaxCommandPathLen = commandPathLen1116 }1117 nameLen := len(x.Name())1118 if nameLen > c.commandsMaxNameLen {1119 c.commandsMaxNameLen = nameLen1120 }1121 // If global normalization function exists, update all children1122 if c.globNormFunc != nil {1123 x.SetGlobalNormalizationFunc(c.globNormFunc)1124 }1125 c.commands = append(c.commands, x)1126 c.commandsAreSorted = false1127 }1128}11291130// RemoveCommand removes one or more commands from a parent command.1131func (c *Command) RemoveCommand(cmds ...*Command) {1132 commands := []*Command{}1133main:1134 for _, command := range c.commands {1135 for _, cmd := range cmds {1136 if command == cmd {1137 command.parent = nil1138 continue main1139 }1140 }1141 commands = append(commands, command)1142 }1143 c.commands = commands1144 // recompute all lengths1145 c.commandsMaxUseLen = 01146 c.commandsMaxCommandPathLen = 01147 c.commandsMaxNameLen = 01148 for _, command := range c.commands {1149 usageLen := len(command.Use)1150 if usageLen > c.commandsMaxUseLen {1151 c.commandsMaxUseLen = usageLen1152 }1153 commandPathLen := len(command.CommandPath())1154 if commandPathLen > c.commandsMaxCommandPathLen {1155 c.commandsMaxCommandPathLen = commandPathLen1156 }1157 nameLen := len(command.Name())1158 if nameLen > c.commandsMaxNameLen {1159 c.commandsMaxNameLen = nameLen1160 }1161 }1162}11631164// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1165func (c *Command) Print(i ...interface{}) {1166 fmt.Fprint(c.OutOrStderr(), i...)1167}11681169// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1170func (c *Command) Println(i ...interface{}) {1171 c.Print(fmt.Sprintln(i...))1172}11731174// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1175func (c *Command) Printf(format string, i ...interface{}) {1176 c.Print(fmt.Sprintf(format, i...))1177}1178

Allow for explicit output to err/stderrJuan Lenibefore adoption618bc00

lines 1179–1193why, one step back
1179// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.
1180func (c *Command) PrintErr(i ...interface{}) {1181 fmt.Fprint(c.ErrOrStderr(), i...)1182}11831184// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.1185func (c *Command) PrintErrln(i ...interface{}) {1186 c.Print(fmt.Sprintln(i...))1187}11881189// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.1190func (c *Command) PrintErrf(format string, i ...interface{}) {1191 c.Print(fmt.Sprintf(format, i...))1192}1193

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1194–1208why, one step back
1194// CommandPath returns the full path to this command.
1195func (c *Command) CommandPath() string {1196 if c.HasParent() {1197 return c.Parent().CommandPath() + " " + c.Name()1198 }1199 return c.Name()1200}12011202// UseLine puts out the full usage for a given command (including parents).1203func (c *Command) UseLine() string {1204 var useline string1205 if c.HasParent() {1206 useline = c.parent.CommandPath() + " " + c.Use1207 } else {1208 useline = c.Use

Disable flags in UseLine (#552)Daniel Nephinbefore adoption34ceca5

lines 1209–1211why, one step back
1209 }
1210 if c.DisableFlagsInUseLine {1211 return useline

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1212–1261why, one step back
1212 }
1213 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1214 useline += " [flags]"1215 }1216 return useline1217}12181219// DebugFlags used to determine which flags have been assigned to which commands1220// and which persist.1221func (c *Command) DebugFlags() {1222 c.Println("DebugFlags called on", c.Name())1223 var debugflags func(*Command)12241225 debugflags = func(x *Command) {1226 if x.HasFlags() || x.HasPersistentFlags() {1227 c.Println(x.Name())1228 }1229 if x.HasFlags() {1230 x.flags.VisitAll(func(f *flag.Flag) {1231 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1232 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1233 } else {1234 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1235 }1236 })1237 }1238 if x.HasPersistentFlags() {1239 x.pflags.VisitAll(func(f *flag.Flag) {1240 if x.HasFlags() {1241 if x.flags.Lookup(f.Name) == nil {1242 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1243 }1244 } else {1245 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1246 }1247 })1248 }1249 c.Println(x.flagErrorBuf)1250 if x.HasSubCommands() {1251 for _, y := range x.commands {1252 debugflags(y)1253 }1254 }1255 }12561257 debugflags(c)1258}12591260// Name returns the command's name: the first word in the use line.1261func (c *Command) Name() string {

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

lines 1262–1265why, one step back
1262 name := c.Use
1263 i := strings.Index(name, " ")1264 if i >= 0 {1265 name = name[:i]

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

line 1266why, one step back
1266 }

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

line 1267why, one step back
1267 return name

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1268–1279why, one step back
1268}
12691270// HasAlias determines if a given string is an alias of the command.1271func (c *Command) HasAlias(s string) bool {1272 for _, a := range c.Aliases {1273 if a == s {1274 return true1275 }1276 }1277 return false1278}1279

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

lines 1280–1288why, one step back
1280// CalledAs returns the command name or alias that was used to invoke
1281// this command or an empty string if the command has not been called.1282func (c *Command) CalledAs() string {1283 if c.commandCalledAs.called {1284 return c.commandCalledAs.name1285 }1286 return ""1287}1288

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

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

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

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

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

lines 1294–1297why, one step back
1294 return true
1295 }1296 for _, alias := range c.Aliases {1297 if strings.HasPrefix(alias, prefix) {

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

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

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

lines 1299–1305why, one step back
1299 return true
1300 }1301 }1302 return false1303}13041305// NameAndAliases returns a list of the command name and all aliases

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1306–1390why, one step back
1306func (c *Command) NameAndAliases() string {
1307 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1308}13091310// HasExample determines if the command has example.1311func (c *Command) HasExample() bool {1312 return len(c.Example) > 01313}13141315// Runnable determines if the command is itself runnable.1316func (c *Command) Runnable() bool {1317 return c.Run != nil || c.RunE != nil1318}13191320// HasSubCommands determines if the command has children commands.1321func (c *Command) HasSubCommands() bool {1322 return len(c.commands) > 01323}13241325// IsAvailableCommand determines if a command is available as a non-help command1326// (this includes all non deprecated/hidden commands).1327func (c *Command) IsAvailableCommand() bool {1328 if len(c.Deprecated) != 0 || c.Hidden {1329 return false1330 }13311332 if c.HasParent() && c.Parent().helpCommand == c {1333 return false1334 }13351336 if c.Runnable() || c.HasAvailableSubCommands() {1337 return true1338 }13391340 return false1341}13421343// IsAdditionalHelpTopicCommand determines if a command is an additional1344// help topic command; additional help topic command is determined by the1345// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1346// are runnable/hidden/deprecated.1347// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1348func (c *Command) IsAdditionalHelpTopicCommand() bool {1349 // if a command is runnable, deprecated, or hidden it is not a 'help' command1350 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1351 return false1352 }13531354 // if any non-help sub commands are found, the command is not a 'help' command1355 for _, sub := range c.commands {1356 if !sub.IsAdditionalHelpTopicCommand() {1357 return false1358 }1359 }13601361 // the command either has no sub commands, or no non-help sub commands1362 return true1363}13641365// HasHelpSubCommands determines if a command has any available 'help' sub commands1366// that need to be shown in the usage/help default template under 'additional help1367// topics'.1368func (c *Command) HasHelpSubCommands() bool {1369 // return true on the first found available 'help' sub command1370 for _, sub := range c.commands {1371 if sub.IsAdditionalHelpTopicCommand() {1372 return true1373 }1374 }13751376 // the command either has no sub commands, or no available 'help' sub commands1377 return false1378}13791380// HasAvailableSubCommands determines if a command has available sub commands that1381// need to be shown in the usage/help default template under 'available commands'.1382func (c *Command) HasAvailableSubCommands() bool {1383 // return true on the first found available (non deprecated/help/hidden)1384 // sub command1385 for _, sub := range c.commands {1386 if sub.IsAvailableCommand() {1387 return true1388 }1389 }1390

Fix typo (#573)Pavol Loffaybefore adoptionf634327

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1392–1400why, one step back
1392 // sub commands
1393 return false1394}13951396// HasParent determines if the command is a child command.1397func (c *Command) HasParent() bool {1398 return c.parent != nil1399}1400

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

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1402–1444why, one step back
1402func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
1403 return c.globNormFunc1404}14051406// Flags returns the complete FlagSet that applies1407// to this command (local and persistent declared here and by all parents).1408func (c *Command) Flags() *flag.FlagSet {1409 if c.flags == nil {1410 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1411 if c.flagErrorBuf == nil {1412 c.flagErrorBuf = new(bytes.Buffer)1413 }1414 c.flags.SetOutput(c.flagErrorBuf)1415 }14161417 return c.flags1418}14191420// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1421func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1422 persistentFlags := c.PersistentFlags()14231424 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1425 c.LocalFlags().VisitAll(func(f *flag.Flag) {1426 if persistentFlags.Lookup(f.Name) == nil {1427 out.AddFlag(f)1428 }1429 })1430 return out1431}14321433// LocalFlags returns the local FlagSet specifically set in the current command.1434func (c *Command) LocalFlags() *flag.FlagSet {1435 c.mergePersistentFlags()14361437 if c.lflags == nil {1438 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1439 if c.flagErrorBuf == nil {1440 c.flagErrorBuf = new(bytes.Buffer)1441 }1442 c.lflags.SetOutput(c.flagErrorBuf)1443 }1444 c.lflags.SortFlags = c.Flags().SortFlags

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

lines 1445–1447why, one step back
1445 if c.globNormFunc != nil {
1446 c.lflags.SetNormalizeFunc(c.globNormFunc)1447 }

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1448–1458why, one step back
1448
1449 addToLocal := func(f *flag.Flag) {1450 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1451 c.lflags.AddFlag(f)1452 }1453 }1454 c.Flags().VisitAll(addToLocal)1455 c.PersistentFlags().VisitAll(addToLocal)1456 return c.lflags1457}1458

[TrivialPatches] Typos in README.md, fix and update CI, update projects list... (#840)umarcorbefore adoption5755ecf

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1460–1471why, one step back
1460func (c *Command) InheritedFlags() *flag.FlagSet {
1461 c.mergePersistentFlags()14621463 if c.iflags == nil {1464 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1465 if c.flagErrorBuf == nil {1466 c.flagErrorBuf = new(bytes.Buffer)1467 }1468 c.iflags.SetOutput(c.flagErrorBuf)1469 }14701471 local := c.LocalFlags()

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

lines 1472–1475why, one step back
1472 if c.globNormFunc != nil {
1473 c.iflags.SetNormalizeFunc(c.globNormFunc)1474 }1475

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1476–1500why, one step back
1476 c.parentsPflags.VisitAll(func(f *flag.Flag) {
1477 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1478 c.iflags.AddFlag(f)1479 }1480 })1481 return c.iflags1482}14831484// NonInheritedFlags returns all flags which were not inherited from parent commands.1485func (c *Command) NonInheritedFlags() *flag.FlagSet {1486 return c.LocalFlags()1487}14881489// PersistentFlags returns the persistent FlagSet specifically set in the current command.1490func (c *Command) PersistentFlags() *flag.FlagSet {1491 if c.pflags == nil {1492 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1493 if c.flagErrorBuf == nil {1494 c.flagErrorBuf = new(bytes.Buffer)1495 }1496 c.pflags.SetOutput(c.flagErrorBuf)1497 }1498 return c.pflags1499}1500

Edit ResetFlags and ResetCommands descriptionsAlbert Nigmatzianovbefore adoptiond6a4305

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

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1502–1508why, one step back
1502func (c *Command) ResetFlags() {
1503 c.flagErrorBuf = new(bytes.Buffer)1504 c.flagErrorBuf.Reset()1505 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1506 c.flags.SetOutput(c.flagErrorBuf)1507 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1508 c.pflags.SetOutput(c.flagErrorBuf)

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

lines 1509–1512why, one step back
1509
1510 c.lflags = nil1511 c.iflags = nil1512 c.parentsPflags = nil

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1513–1587why, one step back
1513}
15141515// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1516func (c *Command) HasFlags() bool {1517 return c.Flags().HasFlags()1518}15191520// HasPersistentFlags checks if the command contains persistent flags.1521func (c *Command) HasPersistentFlags() bool {1522 return c.PersistentFlags().HasFlags()1523}15241525// HasLocalFlags checks if the command has flags specifically declared locally.1526func (c *Command) HasLocalFlags() bool {1527 return c.LocalFlags().HasFlags()1528}15291530// HasInheritedFlags checks if the command has flags inherited from its parent command.1531func (c *Command) HasInheritedFlags() bool {1532 return c.InheritedFlags().HasFlags()1533}15341535// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1536// structure) which are not hidden or deprecated.1537func (c *Command) HasAvailableFlags() bool {1538 return c.Flags().HasAvailableFlags()1539}15401541// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1542func (c *Command) HasAvailablePersistentFlags() bool {1543 return c.PersistentFlags().HasAvailableFlags()1544}15451546// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1547// or deprecated.1548func (c *Command) HasAvailableLocalFlags() bool {1549 return c.LocalFlags().HasAvailableFlags()1550}15511552// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1553// not hidden or deprecated.1554func (c *Command) HasAvailableInheritedFlags() bool {1555 return c.InheritedFlags().HasAvailableFlags()1556}15571558// Flag climbs up the command tree looking for matching flag.1559func (c *Command) Flag(name string) (flag *flag.Flag) {1560 flag = c.Flags().Lookup(name)15611562 if flag == nil {1563 flag = c.persistentFlag(name)1564 }15651566 return1567}15681569// Recursively find matching persistent flag.1570func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1571 if c.HasPersistentFlags() {1572 flag = c.PersistentFlags().Lookup(name)1573 }15741575 if flag == nil {1576 c.updateParentsPflags()1577 flag = c.parentsPflags.Lookup(name)1578 }1579 return1580}15811582// ParseFlags parses persistent flag tree and local flags.1583func (c *Command) ParseFlags(args []string) error {1584 if c.DisableFlagParsing {1585 return nil1586 }1587

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

lines 1588–1590why, one step back
1588 if c.flagErrorBuf == nil {
1589 c.flagErrorBuf = new(bytes.Buffer)1590 }

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1591–1592why, one step back
1591 beforeErrorBufLen := c.flagErrorBuf.Len()
1592 c.mergePersistentFlags()

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

line 1593why, one step back
1593

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

line 1594why, one step back
1594 // do it here after merging all flags and just before parse

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

lines 1595–1596why, one step back
1595 c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)
1596

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1597–1626why, one step back
1597 err := c.Flags().Parse(args)
1598 // Print warnings if they occurred (e.g. deprecated flag messages).1599 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1600 c.Print(c.flagErrorBuf.String())1601 }16021603 return err1604}16051606// Parent returns a commands parent command.1607func (c *Command) Parent() *Command {1608 return c.parent1609}16101611// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1612// and adds missing persistent flags of all parents.1613func (c *Command) mergePersistentFlags() {1614 c.updateParentsPflags()1615 c.Flags().AddFlagSet(c.PersistentFlags())1616 c.Flags().AddFlagSet(c.parentsPflags)1617}16181619// updateParentsPflags updates c.parentsPflags by adding1620// new persistent flags of all parents.1621// If c.parentsPflags == nil, it makes new.1622func (c *Command) updateParentsPflags() {1623 if c.parentsPflags == nil {1624 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1625 c.parentsPflags.SetOutput(c.flagErrorBuf)1626 c.parentsPflags.SortFlags = false

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

lines 1627–1630why, one step back
1627 }
16281629 if c.globNormFunc != nil {1630 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)

travis: Update Go versionsAnthony Fokbefore adoptiond4c40bb

lines 1631–1638why, one step back
1631 }
16321633 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)16341635 c.VisitParents(func(parent *Command) {1636 c.parentsPflags.AddFlagSet(parent.PersistentFlags())1637 })1638}