Skip to content
Myr

command.go

This file

Path

command.go

1,664 lines · 46.4 KiB · Go

Last changed by

Add documentation for Use (#1188)Michael Murébefore adoption8cfa4b4

History of this file

Take it

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

Grammar addition (#543)Clayton Raybefore adoption5020481

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"

Grammar addition (#543)Clayton Raybefore adoption5020481

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 34–39why, 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.

Add documentation for Use (#1188)Michael Murébefore adoption8cfa4b4

lines 40–47why, one step back
40 // Recommended syntax is as follow:
41 // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.42 // ... indicates that you can specify multiple values for the previous argument.43 // | indicates mutually exclusive information. You can use the argument to the left of the separator or the44 // argument to the right of the separator. You cannot use both arguments in a single use of the command.45 // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are46 // optional, they are enclosed in brackets ([ ]).47 // Example: add [-F file | -D dir]... [-f format] profile

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 48–67why, one step back
48 Use string
4950 // Aliases is an array of aliases that can be used instead of the first word in Use.51 Aliases []string5253 // SuggestFor is an array of command names for which this command will be suggested -54 // similar to aliases but only suggests.55 SuggestFor []string5657 // Short is the short description shown in the 'help' output.58 Short string5960 // Long is the long message shown in the 'help <this-command>' output.61 Long string6263 // Example is examples of how to use the command.64 Example string6566 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions67 ValidArgs []string

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

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

Rename BashCompDirectives to ShellCompDirectives (#1082)Marc Khouzambefore adoptionb84ef40

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 72–93why, one step back
72
73 // Expected arguments74 Args PositionalArgs7576 // ArgAliases is List of aliases for ValidArgs.77 // These are not suggested to the user in the bash completion,78 // but accepted if entered manually.79 ArgAliases []string8081 // BashCompletionFunction is custom functions used by the bash autocompletion generator.82 BashCompletionFunction string8384 // Deprecated defines, if this command is deprecated and should print this string when used.85 Deprecated string8687 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.88 Hidden bool8990 // Annotations are key/value pairs that can be used by applications to identify or91 // group commands.92 Annotations map[string]string93

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

lines 94–95why, one step back
94 // Version defines the version for this command. If this value is non-empty and the command does not
95 // 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 96–97why, one step back
96 // will print content of the "Version" variable. A shorthand "v" flag will also be added if the
97 // command does not define one.

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

lines 98–99why, one step back
98 Version string
99

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 100–142why, one step back
100 // The *Run functions are executed in the following order:
101 // * PersistentPreRun()102 // * PreRun()103 // * Run()104 // * PostRun()105 // * PersistentPostRun()106 // All functions get the same args, the arguments after the command name.107 //108 // PersistentPreRun: children of this command will inherit and execute.109 PersistentPreRun func(cmd *Command, args []string)110 // PersistentPreRunE: PersistentPreRun but returns an error.111 PersistentPreRunE func(cmd *Command, args []string) error112 // PreRun: children of this command will not inherit.113 PreRun func(cmd *Command, args []string)114 // PreRunE: PreRun but returns an error.115 PreRunE func(cmd *Command, args []string) error116 // Run: Typically the actual work function. Most commands will only implement this.117 Run func(cmd *Command, args []string)118 // RunE: Run but returns an error.119 RunE func(cmd *Command, args []string) error120 // PostRun: run after the Run command.121 PostRun func(cmd *Command, args []string)122 // PostRunE: PostRun but returns an error.123 PostRunE func(cmd *Command, args []string) error124 // PersistentPostRun: children of this command will inherit and execute after PostRun.125 PersistentPostRun func(cmd *Command, args []string)126 // PersistentPostRunE: PersistentPostRun but returns an error.127 PersistentPostRunE func(cmd *Command, args []string) error128129 // SilenceErrors is an option to quiet errors down stream.130 SilenceErrors bool131132 // SilenceUsage is an option to silence usage when an error occurs.133 SilenceUsage bool134135 // DisableFlagParsing disables the flag parsing.136 // If this is true all flags will be passed to the command as arguments.137 DisableFlagParsing bool138139 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")140 // will be printed by generating docs for this command.141 DisableAutoGenTag bool142

Disable flags in UseLine (#552)Daniel Nephinbefore adoption34ceca5

lines 143–146why, one step back
143 // DisableFlagsInUseLine will disable the addition of [flags] to the usage
144 // line of a command when printing help or generating docs145 DisableFlagsInUseLine bool146

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 147–156why, one step back
147 // DisableSuggestions disables the suggestions based on Levenshtein distance
148 // that go along with 'unknown command' messages.149 DisableSuggestions bool150 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.151 // Must be > 0.152 SuggestionsMinimumDistance int153154 // TraverseChildren parses flags on all parents before executing child command.155 TraverseChildren bool156

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

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

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

lines 158–159why, one step back
158 FParseErrWhitelist FParseErrWhitelist
159

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 160–161why, one step back
160 ctx context.Context
161

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 162–171why, one step back
162 // commands is the list of commands supported by this program.
163 commands []*Command164 // parent is a parent command for this command.165 parent *Command166 // Max lengths of commands' string lengths for use in padding.167 commandsMaxUseLen int168 commandsMaxCommandPathLen int169 commandsMaxNameLen int170 // commandsAreSorted defines, if command slice are sorted or not.171 commandsAreSorted bool

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

lines 172–176why, one step back
172 // commandCalledAs is the name or alias value used to call this command.
173 commandCalledAs struct {174 name string175 called bool176 }

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 177–209why, one step back
177
178 // args is actual args parsed from flags.179 args []string180 // flagErrorBuf contains all error messages from pflag.181 flagErrorBuf *bytes.Buffer182 // flags is full set of flags.183 flags *flag.FlagSet184 // pflags contains persistent flags.185 pflags *flag.FlagSet186 // lflags contains local flags.187 lflags *flag.FlagSet188 // iflags contains inherited flags.189 iflags *flag.FlagSet190 // parentsPflags is all persistent flags of cmd's parents.191 parentsPflags *flag.FlagSet192 // globNormFunc is the global normalization function193 // that we can use on every pflag set and children commands194 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName195196 // usageFunc is usage func defined by user.197 usageFunc func(*Command) error198 // usageTemplate is usage template defined by user.199 usageTemplate string200 // flagErrorFunc is func defined by user and it's called when the parsing of201 // flags returns an error.202 flagErrorFunc func(*Command, error) error203 // helpTemplate is help template defined by user.204 helpTemplate string205 // helpFunc is help func defined by user.206 helpFunc func(*Command, []string)207 // helpCommand is command with usage 'help'. If it's not defined by user,208 // cobra uses default help command.209 helpCommand *Command

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

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 212–218why, one step back
212
213 // inReader is a reader defined by the user that replaces stdin214 inReader io.Reader215 // outWriter is a writer defined by the user that replaces stdout216 outWriter io.Writer217 // errWriter is a writer defined by the user that replaces stderr218 errWriter io.Writer

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 219–220why, one step back
219}
220

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 221–226why, one step back
221// Context returns underlying command context. If command wasn't
222// executed with ExecuteContext Context returns Background context.223func (c *Command) Context() context.Context {224 return c.ctx225}226

Grammar addition (#543)Clayton Raybefore adoption5020481

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

Deprecate and maintain backwards compatibilityJuan Lenibefore adoptioncb27ce1

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

Grammar addition (#543)Clayton Raybefore adoption5020481

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

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

Deprecate and maintain backwards compatibilityJuan Lenibefore adoptioncb27ce1

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 239–240why, one step back
239}
240

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

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

Fixed linter issuesJuan Lenibefore adoption0ea93dd

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

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

Fixed linter issuesJuan Lenibefore adoption0ea93dd

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 250–252why, one step back
250 c.errWriter = newErr
251}252

Correct all complaints from golintBruce Downsbefore adoption51f06c7

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 254–258why, one step back
254// If newIn is nil, os.Stdin is used.
255func (c *Command) SetIn(newIn io.Reader) {256 c.inReader = newIn257}258

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 259–289why, one step back
259// SetUsageFunc sets usage function. Usage can be defined by application.
260func (c *Command) SetUsageFunc(f func(*Command) error) {261 c.usageFunc = f262}263264// SetUsageTemplate sets usage template. Can be defined by Application.265func (c *Command) SetUsageTemplate(s string) {266 c.usageTemplate = s267}268269// SetFlagErrorFunc sets a function to generate an error when flag parsing270// fails.271func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {272 c.flagErrorFunc = f273}274275// SetHelpFunc sets help function. Can be defined by Application.276func (c *Command) SetHelpFunc(f func(*Command, []string)) {277 c.helpFunc = f278}279280// SetHelpCommand sets help command.281func (c *Command) SetHelpCommand(cmd *Command) {282 c.helpCommand = cmd283}284285// SetHelpTemplate sets help template to be used. Application can use it to set custom template.286func (c *Command) SetHelpTemplate(s string) {287 c.helpTemplate = s288}289

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

lines 290–294why, one step back
290// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
291func (c *Command) SetVersionTemplate(s string) {292 c.versionTemplate = s293}294

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 295–316why, one step back
295// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
296// The user should not have a cyclic dependency on commands.297func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {298 c.Flags().SetNormalizeFunc(n)299 c.PersistentFlags().SetNormalizeFunc(n)300 c.globNormFunc = n301302 for _, command := range c.commands {303 command.SetGlobalNormalizationFunc(n)304 }305}306307// OutOrStdout returns output to stdout.308func (c *Command) OutOrStdout() io.Writer {309 return c.getOut(os.Stdout)310}311312// OutOrStderr returns output to stderr313func (c *Command) OutOrStderr() io.Writer {314 return c.getOut(os.Stderr)315}316

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 317–321why, one step back
317// ErrOrStderr returns output to stderr
318func (c *Command) ErrOrStderr() io.Writer {319 return c.getErr(os.Stderr)320}321

Correct documentation for InOrStdin (#929)Daniel Espondabefore adoption3c26245

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 323–326why, one step back
323func (c *Command) InOrStdin() io.Reader {
324 return c.getIn(os.Stdin)325}326

Grammar addition (#543)Clayton Raybefore adoption5020481

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 330–336why, one step back
330 }
331 if c.HasParent() {332 return c.parent.getOut(def)333 }334 return def335}336

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

lines 337–356why, one step back
337func (c *Command) getErr(def io.Writer) io.Writer {
338 if c.errWriter != nil {339 return c.errWriter340 }341 if c.HasParent() {342 return c.parent.getErr(def)343 }344 return def345}346347func (c *Command) getIn(def io.Reader) io.Reader {348 if c.inReader != nil {349 return c.inReader350 }351 if c.HasParent() {352 return c.parent.getIn(def)353 }354 return def355}356

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 357–393why, one step back
357// UsageFunc returns either the function set by SetUsageFunc for this command
358// or a parent, or it returns a default usage function.359func (c *Command) UsageFunc() (f func(*Command) error) {360 if c.usageFunc != nil {361 return c.usageFunc362 }363 if c.HasParent() {364 return c.Parent().UsageFunc()365 }366 return func(c *Command) error {367 c.mergePersistentFlags()368 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)369 if err != nil {370 c.Println(err)371 }372 return err373 }374}375376// Usage puts out the usage for the command.377// Used when a user provides invalid input.378// Can be defined by user by overriding UsageFunc.379func (c *Command) Usage() error {380 return c.UsageFunc()(c)381}382383// HelpFunc returns either the function set by SetHelpFunc for this command384// or a parent, or it returns a function with default help behavior.385func (c *Command) HelpFunc() func(*Command, []string) {386 if c.helpFunc != nil {387 return c.helpFunc388 }389 if c.HasParent() {390 return c.Parent().HelpFunc()391 }392 return func(c *Command, a []string) {393 c.mergePersistentFlags()

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 397–410why, one step back
397 if err != nil {
398 c.Println(err)399 }400 }401}402403// Help puts out the help for the command.404// Used when a user calls help [command].405// Can be defined by user by overriding HelpFunc.406func (c *Command) Help() error {407 c.HelpFunc()(c, []string{})408 return nil409}410

considering stderr in UsageStringJuan Lenibefore adoptionb635726

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

Grammar addition (#543)Clayton Raybefore adoption5020481

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

considering stderr in UsageStringJuan Lenibefore adoptionb635726

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

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

considering stderr in UsageStringJuan Lenibefore adoptionb635726

lines 415–416why, one step back
415 tmpErr := c.errWriter
416

Grammar addition (#543)Clayton Raybefore adoption5020481

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

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

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

considering stderr in UsageStringJuan Lenibefore adoptionb635726

lines 419–420why, one step back
419 c.errWriter = bb
420

Grammar addition (#543)Clayton Raybefore adoption5020481

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

considering stderr in UsageStringJuan Lenibefore adoptionb635726

lines 422–423why, one step back
422
423 // Setting things back to normal

Extending redirection to stdout, stderr, stdinJuan Lenibefore adoption4a716d1

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

considering stderr in UsageStringJuan Lenibefore adoptionb635726

lines 425–426why, one step back
425 c.errWriter = tmpErr
426

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 427–524why, one step back
427 return bb.String()
428}429430// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this431// command or a parent, or it returns a function which returns the original432// error.433func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {434 if c.flagErrorFunc != nil {435 return c.flagErrorFunc436 }437438 if c.HasParent() {439 return c.parent.FlagErrorFunc()440 }441 return func(c *Command, err error) error {442 return err443 }444}445446var minUsagePadding = 25447448// UsagePadding return padding for the usage.449func (c *Command) UsagePadding() int {450 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {451 return minUsagePadding452 }453 return c.parent.commandsMaxUseLen454}455456var minCommandPathPadding = 11457458// CommandPathPadding return padding for the command path.459func (c *Command) CommandPathPadding() int {460 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {461 return minCommandPathPadding462 }463 return c.parent.commandsMaxCommandPathLen464}465466var minNamePadding = 11467468// NamePadding returns padding for the name.469func (c *Command) NamePadding() int {470 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {471 return minNamePadding472 }473 return c.parent.commandsMaxNameLen474}475476// UsageTemplate returns usage template for the command.477func (c *Command) UsageTemplate() string {478 if c.usageTemplate != "" {479 return c.usageTemplate480 }481482 if c.HasParent() {483 return c.parent.UsageTemplate()484 }485 return `Usage:{{if .Runnable}}486 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}487 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}488489Aliases:490 {{.NameAndAliases}}{{end}}{{if .HasExample}}491492Examples:493{{.Example}}{{end}}{{if .HasAvailableSubCommands}}494495Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}496 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}497498Flags:499{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}500501Global Flags:502{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}503504Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}505 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}506507Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}508`509}510511// HelpTemplate return help template for the command.512func (c *Command) HelpTemplate() string {513 if c.helpTemplate != "" {514 return c.helpTemplate515 }516517 if c.HasParent() {518 return c.parent.HelpTemplate()519 }520 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}521522{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`523}524

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

lines 525–537why, one step back
525// VersionTemplate return version template for the command.
526func (c *Command) VersionTemplate() string {527 if c.versionTemplate != "" {528 return c.versionTemplate529 }530531 if c.HasParent() {532 return c.parent.VersionTemplate()533 }534 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}535`536}537

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 538–571why, one step back
538func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
539 flag := fs.Lookup(name)540 if flag == nil {541 return false542 }543 return flag.NoOptDefVal != ""544}545546func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {547 if len(name) == 0 {548 return false549 }550551 flag := fs.ShorthandLookup(name[:1])552 if flag == nil {553 return false554 }555 return flag.NoOptDefVal != ""556}557558func stripFlags(args []string, c *Command) []string {559 if len(args) == 0 {560 return args561 }562 c.mergePersistentFlags()563564 commands := []string{}565 flags := c.Flags()566567Loop:568 for len(args) > 0 {569 s := args[0]570 args = args[1:]571 switch {

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

lines 572–574why, one step back
572 case s == "--":
573 // "--" terminates the flags574 break Loop

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 575–661why, one step back
575 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
576 // If '--flag arg' then577 // delete arg from args.578 fallthrough // (do the same as below)579 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):580 // If '-f arg' then581 // delete 'arg' from args or break the loop if len(args) <= 1.582 if len(args) <= 1 {583 break Loop584 } else {585 args = args[1:]586 continue587 }588 case s != "" && !strings.HasPrefix(s, "-"):589 commands = append(commands, s)590 }591 }592593 return commands594}595596// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like597// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).598func argsMinusFirstX(args []string, x string) []string {599 for i, y := range args {600 if x == y {601 ret := []string{}602 ret = append(ret, args[:i]...)603 ret = append(ret, args[i+1:]...)604 return ret605 }606 }607 return args608}609610func isFlagArg(arg string) bool {611 return ((len(arg) >= 3 && arg[1] == '-') ||612 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))613}614615// Find the target command given the args and command tree616// Meant to be run on the highest node. Only searches down.617func (c *Command) Find(args []string) (*Command, []string, error) {618 var innerfind func(*Command, []string) (*Command, []string)619620 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {621 argsWOflags := stripFlags(innerArgs, c)622 if len(argsWOflags) == 0 {623 return c, innerArgs624 }625 nextSubCmd := argsWOflags[0]626627 cmd := c.findNext(nextSubCmd)628 if cmd != nil {629 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))630 }631 return c, innerArgs632 }633634 commandFound, a := innerfind(c, args)635 if commandFound.Args == nil {636 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))637 }638 return commandFound, a, nil639}640641func (c *Command) findSuggestions(arg string) string {642 if c.DisableSuggestions {643 return ""644 }645 if c.SuggestionsMinimumDistance <= 0 {646 c.SuggestionsMinimumDistance = 2647 }648 suggestionsString := ""649 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {650 suggestionsString += "\n\nDid you mean this?\n"651 for _, s := range suggestions {652 suggestionsString += fmt.Sprintf("\t%v\n", s)653 }654 }655 return suggestionsString656}657658func (c *Command) findNext(next string) *Command {659 matches := make([]*Command, 0)660 for _, cmd := range c.commands {661 if cmd.Name() == next || cmd.HasAlias(next) {

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 663–672why, one step back
663 return cmd
664 }665 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {666 matches = append(matches, cmd)667 }668 }669670 if len(matches) == 1 {671 return matches[0]672 }

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

line 673why, one step back
673

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 674–756why, one step back
674 return nil
675}676677// Traverse the command tree to find the command, and parse args for678// each parent.679func (c *Command) Traverse(args []string) (*Command, []string, error) {680 flags := []string{}681 inFlag := false682683 for i, arg := range args {684 switch {685 // A long flag with a space separated value686 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):687 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'688 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())689 flags = append(flags, arg)690 continue691 // A short flag with a space separated value692 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):693 inFlag = true694 flags = append(flags, arg)695 continue696 // The value for a flag697 case inFlag:698 inFlag = false699 flags = append(flags, arg)700 continue701 // A flag without a value, or with an `=` separated value702 case isFlagArg(arg):703 flags = append(flags, arg)704 continue705 }706707 cmd := c.findNext(arg)708 if cmd == nil {709 return c, args, nil710 }711712 if err := c.ParseFlags(flags); err != nil {713 return nil, args, err714 }715 return cmd.Traverse(args[i+1:])716 }717 return c, args, nil718}719720// SuggestionsFor provides suggestions for the typedName.721func (c *Command) SuggestionsFor(typedName string) []string {722 suggestions := []string{}723 for _, cmd := range c.commands {724 if cmd.IsAvailableCommand() {725 levenshteinDistance := ld(typedName, cmd.Name(), true)726 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance727 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))728 if suggestByLevenshtein || suggestByPrefix {729 suggestions = append(suggestions, cmd.Name())730 }731 for _, explicitSuggestion := range cmd.SuggestFor {732 if strings.EqualFold(typedName, explicitSuggestion) {733 suggestions = append(suggestions, cmd.Name())734 }735 }736 }737 }738 return suggestions739}740741// VisitParents visits all parents of the command and invokes fn on each parent.742func (c *Command) VisitParents(fn func(*Command)) {743 if c.HasParent() {744 fn(c.Parent())745 c.Parent().VisitParents(fn)746 }747}748749// Root finds root command.750func (c *Command) Root() *Command {751 if c.HasParent() {752 return c.Parent().Root()753 }754 return c755}756

Improve testsAlbert Nigmatzianovbefore adoption65c8acb

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 759–771why, one step back
759func (c *Command) ArgsLenAtDash() int {
760 return c.Flags().ArgsLenAtDash()761}762763func (c *Command) execute(a []string) (err error) {764 if c == nil {765 return fmt.Errorf("Called Execute() on a nil Command")766 }767768 if len(c.Deprecated) > 0 {769 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)770 }771

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 773–774why, one step back
773 // overriding
774 c.InitDefaultHelpFlag()

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 776–791why, one step back
776
777 err = c.ParseFlags(a)778 if err != nil {779 return c.FlagErrorFunc()(c, err)780 }781782 // If help is called, regardless of other flags, return we want help.783 // Also say we need help if the command isn't runnable.784 helpVal, err := c.Flags().GetBool("help")785 if err != nil {786 // should be impossible to get here as we always declare a help787 // flag in InitDefaultHelpFlag()788 c.Println("\"help\" flag declared as non-bool. Please correct your code")789 return err790 }791

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

line 792why, one step back
792 if helpVal {

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 793–795why, one step back
793 return flag.ErrHelp
794 }795

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

lines 796–809why, one step back
796 // for back-compat, only add version flag behavior if version is defined
797 if c.Version != "" {798 versionVal, err := c.Flags().GetBool("version")799 if err != nil {800 c.Println("\"version\" flag declared as non-bool. Please correct your code")801 return err802 }803 if versionVal {804 err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)805 if err != nil {806 c.Println(err)807 }808 return err809 }

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

lines 810–812why, one step back
810 }
811812 if !c.Runnable() {

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

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

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

lines 814–815why, one step back
814 }
815

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 816–845why, one step back
816 c.preRun()
817818 argWoFlags := c.Flags().Args()819 if c.DisableFlagParsing {820 argWoFlags = a821 }822823 if err := c.ValidateArgs(argWoFlags); err != nil {824 return err825 }826827 for p := c; p != nil; p = p.Parent() {828 if p.PersistentPreRunE != nil {829 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {830 return err831 }832 break833 } else if p.PersistentPreRun != nil {834 p.PersistentPreRun(c, argWoFlags)835 break836 }837 }838 if c.PreRunE != nil {839 if err := c.PreRunE(c, argWoFlags); err != nil {840 return err841 }842 } else if c.PreRun != nil {843 c.PreRun(c, argWoFlags)844 }845

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 846–848why, one step back
846 if err := c.validateRequiredFlags(); err != nil {
847 return err848 }

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 849–883why, one step back
849 if c.RunE != nil {
850 if err := c.RunE(c, argWoFlags); err != nil {851 return err852 }853 } else {854 c.Run(c, argWoFlags)855 }856 if c.PostRunE != nil {857 if err := c.PostRunE(c, argWoFlags); err != nil {858 return err859 }860 } else if c.PostRun != nil {861 c.PostRun(c, argWoFlags)862 }863 for p := c; p != nil; p = p.Parent() {864 if p.PersistentPostRunE != nil {865 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {866 return err867 }868 break869 } else if p.PersistentPostRun != nil {870 p.PersistentPostRun(c, argWoFlags)871 break872 }873 }874875 return nil876}877878func (c *Command) preRun() {879 for _, x := range initializers {880 x()881 }882}883

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 884–890why, one step back
884// ExecuteContext is the same as Execute(), but sets the ctx on the command.
885// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle functions.886func (c *Command) ExecuteContext(ctx context.Context) error {887 c.ctx = ctx888 return c.Execute()889}890

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 891–900why, one step back
891// Execute uses the args (os.Args[1:] by default)
892// and run through the command tree finding appropriate matches893// for commands and then corresponding flags.894func (c *Command) Execute() error {895 _, err := c.ExecuteC()896 return err897}898899// ExecuteC executes the command.900func (c *Command) ExecuteC() (cmd *Command, err error) {

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 901–904why, one step back
901 if c.ctx == nil {
902 c.ctx = context.Background()903 }904

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 905–918why, one step back
905 // Regardless of what command execute is called on, run on Root only
906 if c.HasParent() {907 return c.Root().ExecuteC()908 }909910 // windows hook911 if preExecHookFn != nil {912 preExecHookFn(c)913 }914915 // initialize help as the last point possible to allow for user916 // overriding917 c.InitDefaultHelpCmd()918

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

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

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

lines 925–927why, one step back
925
926 // initialize the hidden command to be used for bash completion927 c.initCompleteCmd(args)

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 928–946why, one step back
928
929 var flags []string930 if c.TraverseChildren {931 cmd, flags, err = c.Traverse(args)932 } else {933 cmd, flags, err = c.Find(args)934 }935 if err != nil {936 // If found parse to a subcommand and then failed, talk about the subcommand937 if cmd != nil {938 c = cmd939 }940 if !c.SilenceErrors {941 c.Println("Error:", err.Error())942 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())943 }944 return c, err945 }946

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

lines 947–951why, one step back
947 cmd.commandCalledAs.called = true
948 if cmd.commandCalledAs.name == "" {949 cmd.commandCalledAs.name = cmd.Name()950 }951

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

lines 952–957why, one step back
952 // We have to pass global context to children command
953 // if context is present on the parent command.954 if cmd.ctx == nil {955 cmd.ctx = c.ctx956 }957

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 958–986why, one step back
958 err = cmd.execute(flags)
959 if err != nil {960 // Always show help if requested, even if SilenceErrors is in961 // effect962 if err == flag.ErrHelp {963 cmd.HelpFunc()(cmd, args)964 return cmd, nil965 }966967 // If root command has SilentErrors flagged,968 // all subcommands should respect it969 if !cmd.SilenceErrors && !c.SilenceErrors {970 c.Println("Error:", err.Error())971 }972973 // If root command has SilentUsage flagged,974 // all subcommands should respect it975 if !cmd.SilenceUsage && !c.SilenceUsage {976 c.Println(cmd.UsageString())977 }978 }979 return cmd, err980}981982func (c *Command) ValidateArgs(args []string) error {983 if c.Args == nil {984 return nil985 }986 return c.Args(c, args)

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 987–989why, one step back
987}
988989func (c *Command) validateRequiredFlags() error {

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

lines 990–993why, one step back
990 if c.DisableFlagParsing {
991 return nil992 }993

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 994–1006why, one step back
994 flags := c.Flags()
995 missingFlagNames := []string{}996 flags.VisitAll(func(pflag *flag.Flag) {997 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]998 if !found {999 return1000 }1001 if (requiredAnnotation[0] == "true") && !pflag.Changed {1002 missingFlagNames = append(missingFlagNames, pflag.Name)1003 }1004 })10051006 if len(missingFlagNames) > 0 {

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

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

enforce required flags (#502)Di Xubefore adoption4d6af28

lines 1008–1009why, one step back
1008 }
1009 return nil

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1010–1024why, one step back
1010}
10111012// InitDefaultHelpFlag adds default help flag to c.1013// It is called automatically by executing the c or by calling help and usage.1014// If c already has help flag, it will do nothing.1015func (c *Command) InitDefaultHelpFlag() {1016 c.mergePersistentFlags()1017 if c.Flags().Lookup("help") == nil {1018 usage := "help for "1019 if c.Name() == "" {1020 usage += "this command"1021 } else {1022 usage += c.Name()1023 }1024 c.Flags().BoolP("help", "h", false, usage)

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

lines 1025–1044why, one step back
1025 }
1026}10271028// InitDefaultVersionFlag adds default version flag to c.1029// It is called automatically by executing the c.1030// If c already has a version flag, it will do nothing.1031// If c.Version is empty, it will do nothing.1032func (c *Command) InitDefaultVersionFlag() {1033 if c.Version == "" {1034 return1035 }10361037 c.mergePersistentFlags()1038 if c.Flags().Lookup("version") == nil {1039 usage := "version for "1040 if c.Name() == "" {1041 usage += "this command"1042 } else {1043 usage += c.Name()1044 }

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

lines 1045–1049why, one step back
1045 if c.Flags().ShorthandLookup("v") == nil {
1046 c.Flags().BoolP("version", "v", false, usage)1047 } else {1048 c.Flags().Bool("version", false, usage)1049 }

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1050–1066why, one step back
1050 }
1051}10521053// InitDefaultHelpCmd adds default help command to c.1054// It is called automatically by executing the c or by calling help and usage.1055// If c already has help command or c has no subcommands, it will do nothing.1056func (c *Command) InitDefaultHelpCmd() {1057 if !c.HasSubCommands() {1058 return1059 }10601061 if c.helpCommand == nil {1062 c.helpCommand = &Command{1063 Use: "help [command]",1064 Short: "Help about any command",1065 Long: `Help provides help for any command in the application.1066Simply type ` + c.Name() + ` help [path to command] for full details.`,

Add completion for help command (#1136)Marc Khouzambefore adoption0431872

lines 1067–1085why, one step back
1067 ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
1068 var completions []string1069 cmd, _, e := c.Root().Find(args)1070 if e != nil {1071 return nil, ShellCompDirectiveNoFileComp1072 }1073 if cmd == nil {1074 // Root help command.1075 cmd = c.Root()1076 }1077 for _, subCmd := range cmd.Commands() {1078 if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {1079 if strings.HasPrefix(subCmd.Name(), toComplete) {1080 completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))1081 }1082 }1083 }1084 return completions, ShellCompDirectiveNoFileComp1085 },

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1086–1101why, one step back
1086 Run: func(c *Command, args []string) {
1087 cmd, _, e := c.Root().Find(args)1088 if cmd == nil || e != nil {1089 c.Printf("Unknown help topic %#q\n", args)1090 c.Root().Usage()1091 } else {1092 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1093 cmd.Help()1094 }1095 },1096 }1097 }1098 c.RemoveCommand(c.helpCommand)1099 c.AddCommand(c.helpCommand)1100}1101

Edit ResetFlags and ResetCommands descriptionsAlbert Nigmatzianovbefore adoptiond6a4305

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1103–1204why, one step back
1103func (c *Command) ResetCommands() {
1104 c.parent = nil1105 c.commands = nil1106 c.helpCommand = nil1107 c.parentsPflags = nil1108}11091110// Sorts commands by their names.1111type commandSorterByName []*Command11121113func (c commandSorterByName) Len() int { return len(c) }1114func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }1115func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }11161117// Commands returns a sorted slice of child commands.1118func (c *Command) Commands() []*Command {1119 // do not sort commands if it already sorted or sorting was disabled1120 if EnableCommandSorting && !c.commandsAreSorted {1121 sort.Sort(commandSorterByName(c.commands))1122 c.commandsAreSorted = true1123 }1124 return c.commands1125}11261127// AddCommand adds one or more commands to this parent command.1128func (c *Command) AddCommand(cmds ...*Command) {1129 for i, x := range cmds {1130 if cmds[i] == c {1131 panic("Command can't be a child of itself")1132 }1133 cmds[i].parent = c1134 // update max lengths1135 usageLen := len(x.Use)1136 if usageLen > c.commandsMaxUseLen {1137 c.commandsMaxUseLen = usageLen1138 }1139 commandPathLen := len(x.CommandPath())1140 if commandPathLen > c.commandsMaxCommandPathLen {1141 c.commandsMaxCommandPathLen = commandPathLen1142 }1143 nameLen := len(x.Name())1144 if nameLen > c.commandsMaxNameLen {1145 c.commandsMaxNameLen = nameLen1146 }1147 // If global normalization function exists, update all children1148 if c.globNormFunc != nil {1149 x.SetGlobalNormalizationFunc(c.globNormFunc)1150 }1151 c.commands = append(c.commands, x)1152 c.commandsAreSorted = false1153 }1154}11551156// RemoveCommand removes one or more commands from a parent command.1157func (c *Command) RemoveCommand(cmds ...*Command) {1158 commands := []*Command{}1159main:1160 for _, command := range c.commands {1161 for _, cmd := range cmds {1162 if command == cmd {1163 command.parent = nil1164 continue main1165 }1166 }1167 commands = append(commands, command)1168 }1169 c.commands = commands1170 // recompute all lengths1171 c.commandsMaxUseLen = 01172 c.commandsMaxCommandPathLen = 01173 c.commandsMaxNameLen = 01174 for _, command := range c.commands {1175 usageLen := len(command.Use)1176 if usageLen > c.commandsMaxUseLen {1177 c.commandsMaxUseLen = usageLen1178 }1179 commandPathLen := len(command.CommandPath())1180 if commandPathLen > c.commandsMaxCommandPathLen {1181 c.commandsMaxCommandPathLen = commandPathLen1182 }1183 nameLen := len(command.Name())1184 if nameLen > c.commandsMaxNameLen {1185 c.commandsMaxNameLen = nameLen1186 }1187 }1188}11891190// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.1191func (c *Command) Print(i ...interface{}) {1192 fmt.Fprint(c.OutOrStderr(), i...)1193}11941195// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.1196func (c *Command) Println(i ...interface{}) {1197 c.Print(fmt.Sprintln(i...))1198}11991200// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.1201func (c *Command) Printf(format string, i ...interface{}) {1202 c.Print(fmt.Sprintf(format, i...))1203}1204

Allow for explicit output to err/stderrJuan Lenibefore adoption618bc00

lines 1205–1219why, one step back
1205// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.
1206func (c *Command) PrintErr(i ...interface{}) {1207 fmt.Fprint(c.ErrOrStderr(), i...)1208}12091210// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.1211func (c *Command) PrintErrln(i ...interface{}) {1212 c.Print(fmt.Sprintln(i...))1213}12141215// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.1216func (c *Command) PrintErrf(format string, i ...interface{}) {1217 c.Print(fmt.Sprintf(format, i...))1218}1219

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1220–1234why, one step back
1220// CommandPath returns the full path to this command.
1221func (c *Command) CommandPath() string {1222 if c.HasParent() {1223 return c.Parent().CommandPath() + " " + c.Name()1224 }1225 return c.Name()1226}12271228// UseLine puts out the full usage for a given command (including parents).1229func (c *Command) UseLine() string {1230 var useline string1231 if c.HasParent() {1232 useline = c.parent.CommandPath() + " " + c.Use1233 } else {1234 useline = c.Use

Disable flags in UseLine (#552)Daniel Nephinbefore adoption34ceca5

lines 1235–1237why, one step back
1235 }
1236 if c.DisableFlagsInUseLine {1237 return useline

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1238–1287why, one step back
1238 }
1239 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1240 useline += " [flags]"1241 }1242 return useline1243}12441245// DebugFlags used to determine which flags have been assigned to which commands1246// and which persist.1247func (c *Command) DebugFlags() {1248 c.Println("DebugFlags called on", c.Name())1249 var debugflags func(*Command)12501251 debugflags = func(x *Command) {1252 if x.HasFlags() || x.HasPersistentFlags() {1253 c.Println(x.Name())1254 }1255 if x.HasFlags() {1256 x.flags.VisitAll(func(f *flag.Flag) {1257 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1258 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")1259 } else {1260 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1261 }1262 })1263 }1264 if x.HasPersistentFlags() {1265 x.pflags.VisitAll(func(f *flag.Flag) {1266 if x.HasFlags() {1267 if x.flags.Lookup(f.Name) == nil {1268 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1269 }1270 } else {1271 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1272 }1273 })1274 }1275 c.Println(x.flagErrorBuf)1276 if x.HasSubCommands() {1277 for _, y := range x.commands {1278 debugflags(y)1279 }1280 }1281 }12821283 debugflags(c)1284}12851286// Name returns the command's name: the first word in the use line.1287func (c *Command) Name() string {

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

lines 1288–1291why, one step back
1288 name := c.Use
1289 i := strings.Index(name, " ")1290 if i >= 0 {1291 name = name[:i]

Grammar addition (#543)Clayton Raybefore adoption5020481

line 1292why, one step back
1292 }

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

line 1293why, one step back
1293 return name

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1294–1305why, one step back
1294}
12951296// HasAlias determines if a given string is an alias of the command.1297func (c *Command) HasAlias(s string) bool {1298 for _, a := range c.Aliases {1299 if a == s {1300 return true1301 }1302 }1303 return false1304}1305

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

lines 1306–1314why, one step back
1306// CalledAs returns the command name or alias that was used to invoke
1307// this command or an empty string if the command has not been called.1308func (c *Command) CalledAs() string {1309 if c.commandCalledAs.called {1310 return c.commandCalledAs.name1311 }1312 return ""1313}1314

Grammar addition (#543)Clayton Raybefore adoption5020481

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

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1320–1323why, one step back
1320 return true
1321 }1322 for _, alias := range c.Aliases {1323 if strings.HasPrefix(alias, prefix) {

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1325–1416why, one step back
1325 return true
1326 }1327 }1328 return false1329}13301331// NameAndAliases returns a list of the command name and all aliases1332func (c *Command) NameAndAliases() string {1333 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1334}13351336// HasExample determines if the command has example.1337func (c *Command) HasExample() bool {1338 return len(c.Example) > 01339}13401341// Runnable determines if the command is itself runnable.1342func (c *Command) Runnable() bool {1343 return c.Run != nil || c.RunE != nil1344}13451346// HasSubCommands determines if the command has children commands.1347func (c *Command) HasSubCommands() bool {1348 return len(c.commands) > 01349}13501351// IsAvailableCommand determines if a command is available as a non-help command1352// (this includes all non deprecated/hidden commands).1353func (c *Command) IsAvailableCommand() bool {1354 if len(c.Deprecated) != 0 || c.Hidden {1355 return false1356 }13571358 if c.HasParent() && c.Parent().helpCommand == c {1359 return false1360 }13611362 if c.Runnable() || c.HasAvailableSubCommands() {1363 return true1364 }13651366 return false1367}13681369// IsAdditionalHelpTopicCommand determines if a command is an additional1370// help topic command; additional help topic command is determined by the1371// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1372// are runnable/hidden/deprecated.1373// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1374func (c *Command) IsAdditionalHelpTopicCommand() bool {1375 // if a command is runnable, deprecated, or hidden it is not a 'help' command1376 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1377 return false1378 }13791380 // if any non-help sub commands are found, the command is not a 'help' command1381 for _, sub := range c.commands {1382 if !sub.IsAdditionalHelpTopicCommand() {1383 return false1384 }1385 }13861387 // the command either has no sub commands, or no non-help sub commands1388 return true1389}13901391// HasHelpSubCommands determines if a command has any available 'help' sub commands1392// that need to be shown in the usage/help default template under 'additional help1393// topics'.1394func (c *Command) HasHelpSubCommands() bool {1395 // return true on the first found available 'help' sub command1396 for _, sub := range c.commands {1397 if sub.IsAdditionalHelpTopicCommand() {1398 return true1399 }1400 }14011402 // the command either has no sub commands, or no available 'help' sub commands1403 return false1404}14051406// HasAvailableSubCommands determines if a command has available sub commands that1407// need to be shown in the usage/help default template under 'available commands'.1408func (c *Command) HasAvailableSubCommands() bool {1409 // return true on the first found available (non deprecated/help/hidden)1410 // sub command1411 for _, sub := range c.commands {1412 if sub.IsAvailableCommand() {1413 return true1414 }1415 }1416

Fix typo (#573)Pavol Loffaybefore adoptionf634327

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1418–1426why, one step back
1418 // sub commands
1419 return false1420}14211422// HasParent determines if the command is a child command.1423func (c *Command) HasParent() bool {1424 return c.parent != nil1425}1426

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1428–1484why, one step back
1428func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
1429 return c.globNormFunc1430}14311432// Flags returns the complete FlagSet that applies1433// to this command (local and persistent declared here and by all parents).1434func (c *Command) Flags() *flag.FlagSet {1435 if c.flags == nil {1436 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1437 if c.flagErrorBuf == nil {1438 c.flagErrorBuf = new(bytes.Buffer)1439 }1440 c.flags.SetOutput(c.flagErrorBuf)1441 }14421443 return c.flags1444}14451446// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.1447func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1448 persistentFlags := c.PersistentFlags()14491450 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1451 c.LocalFlags().VisitAll(func(f *flag.Flag) {1452 if persistentFlags.Lookup(f.Name) == nil {1453 out.AddFlag(f)1454 }1455 })1456 return out1457}14581459// LocalFlags returns the local FlagSet specifically set in the current command.1460func (c *Command) LocalFlags() *flag.FlagSet {1461 c.mergePersistentFlags()14621463 if c.lflags == nil {1464 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1465 if c.flagErrorBuf == nil {1466 c.flagErrorBuf = new(bytes.Buffer)1467 }1468 c.lflags.SetOutput(c.flagErrorBuf)1469 }1470 c.lflags.SortFlags = c.Flags().SortFlags1471 if c.globNormFunc != nil {1472 c.lflags.SetNormalizeFunc(c.globNormFunc)1473 }14741475 addToLocal := func(f *flag.Flag) {1476 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1477 c.lflags.AddFlag(f)1478 }1479 }1480 c.Flags().VisitAll(addToLocal)1481 c.PersistentFlags().VisitAll(addToLocal)1482 return c.lflags1483}1484

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1486–1526why, one step back
1486func (c *Command) InheritedFlags() *flag.FlagSet {
1487 c.mergePersistentFlags()14881489 if c.iflags == nil {1490 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1491 if c.flagErrorBuf == nil {1492 c.flagErrorBuf = new(bytes.Buffer)1493 }1494 c.iflags.SetOutput(c.flagErrorBuf)1495 }14961497 local := c.LocalFlags()1498 if c.globNormFunc != nil {1499 c.iflags.SetNormalizeFunc(c.globNormFunc)1500 }15011502 c.parentsPflags.VisitAll(func(f *flag.Flag) {1503 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1504 c.iflags.AddFlag(f)1505 }1506 })1507 return c.iflags1508}15091510// NonInheritedFlags returns all flags which were not inherited from parent commands.1511func (c *Command) NonInheritedFlags() *flag.FlagSet {1512 return c.LocalFlags()1513}15141515// PersistentFlags returns the persistent FlagSet specifically set in the current command.1516func (c *Command) PersistentFlags() *flag.FlagSet {1517 if c.pflags == nil {1518 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1519 if c.flagErrorBuf == nil {1520 c.flagErrorBuf = new(bytes.Buffer)1521 }1522 c.pflags.SetOutput(c.flagErrorBuf)1523 }1524 return c.pflags1525}1526

Edit ResetFlags and ResetCommands descriptionsAlbert Nigmatzianovbefore adoptiond6a4305

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1528–1613why, one step back
1528func (c *Command) ResetFlags() {
1529 c.flagErrorBuf = new(bytes.Buffer)1530 c.flagErrorBuf.Reset()1531 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1532 c.flags.SetOutput(c.flagErrorBuf)1533 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1534 c.pflags.SetOutput(c.flagErrorBuf)15351536 c.lflags = nil1537 c.iflags = nil1538 c.parentsPflags = nil1539}15401541// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).1542func (c *Command) HasFlags() bool {1543 return c.Flags().HasFlags()1544}15451546// HasPersistentFlags checks if the command contains persistent flags.1547func (c *Command) HasPersistentFlags() bool {1548 return c.PersistentFlags().HasFlags()1549}15501551// HasLocalFlags checks if the command has flags specifically declared locally.1552func (c *Command) HasLocalFlags() bool {1553 return c.LocalFlags().HasFlags()1554}15551556// HasInheritedFlags checks if the command has flags inherited from its parent command.1557func (c *Command) HasInheritedFlags() bool {1558 return c.InheritedFlags().HasFlags()1559}15601561// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire1562// structure) which are not hidden or deprecated.1563func (c *Command) HasAvailableFlags() bool {1564 return c.Flags().HasAvailableFlags()1565}15661567// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.1568func (c *Command) HasAvailablePersistentFlags() bool {1569 return c.PersistentFlags().HasAvailableFlags()1570}15711572// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden1573// or deprecated.1574func (c *Command) HasAvailableLocalFlags() bool {1575 return c.LocalFlags().HasAvailableFlags()1576}15771578// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are1579// not hidden or deprecated.1580func (c *Command) HasAvailableInheritedFlags() bool {1581 return c.InheritedFlags().HasAvailableFlags()1582}15831584// Flag climbs up the command tree looking for matching flag.1585func (c *Command) Flag(name string) (flag *flag.Flag) {1586 flag = c.Flags().Lookup(name)15871588 if flag == nil {1589 flag = c.persistentFlag(name)1590 }15911592 return1593}15941595// Recursively find matching persistent flag.1596func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1597 if c.HasPersistentFlags() {1598 flag = c.PersistentFlags().Lookup(name)1599 }16001601 if flag == nil {1602 c.updateParentsPflags()1603 flag = c.parentsPflags.Lookup(name)1604 }1605 return1606}16071608// ParseFlags parses persistent flag tree and local flags.1609func (c *Command) ParseFlags(args []string) error {1610 if c.DisableFlagParsing {1611 return nil1612 }1613

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

lines 1614–1616why, one step back
1614 if c.flagErrorBuf == nil {
1615 c.flagErrorBuf = new(bytes.Buffer)1616 }

Grammar addition (#543)Clayton Raybefore adoption5020481

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

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

line 1619why, one step back
1619

Add support for context.ContextAlexandr Burdiyanbefore adoption0da0687

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

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

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

Grammar addition (#543)Clayton Raybefore adoption5020481

lines 1623–1664why, one step back
1623 err := c.Flags().Parse(args)
1624 // Print warnings if they occurred (e.g. deprecated flag messages).1625 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1626 c.Print(c.flagErrorBuf.String())1627 }16281629 return err1630}16311632// Parent returns a commands parent command.1633func (c *Command) Parent() *Command {1634 return c.parent1635}16361637// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1638// and adds missing persistent flags of all parents.1639func (c *Command) mergePersistentFlags() {1640 c.updateParentsPflags()1641 c.Flags().AddFlagSet(c.PersistentFlags())1642 c.Flags().AddFlagSet(c.parentsPflags)1643}16441645// updateParentsPflags updates c.parentsPflags by adding1646// new persistent flags of all parents.1647// If c.parentsPflags == nil, it makes new.1648func (c *Command) updateParentsPflags() {1649 if c.parentsPflags == nil {1650 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1651 c.parentsPflags.SetOutput(c.flagErrorBuf)1652 c.parentsPflags.SortFlags = false1653 }16541655 if c.globNormFunc != nil {1656 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)1657 }16581659 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)16601661 c.VisitParents(func(parent *Command) {1662 c.parentsPflags.AddFlagSet(parent.PersistentFlags())1663 })1664}