Skip to content
Myr

command.go

This file

Path

command.go

903 lines · 22.0 KiB · Go

Last changed by

Remove specail casing in Execute()Eric Parisbefore adoption794a362

History of this file

Take it

Organize the files a bit betterspf13before adoption62fb674

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

Code commentaryAhsanul Haquebefore adoptione1e66f7

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

Organize the files a bit betterspf13before adoption62fb674

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

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 22why, one step back
22 "os"

Organize the files a bit betterspf13before adoption62fb674

line 23why, one step back
23 "strings"

Print root usage when help called with no args.Kevin Darlingtonbefore adoptione174a40

lines 24–25why, one step back
24
25 flag "github.com/spf13/pflag"

Organize the files a bit betterspf13before adoption62fb674

lines 26–36why, one step back
26)
2728// Command is just that, a command for your application.29// eg. 'go run' ... 'run' is the command. Cobra requires30// you to define the usage and description as part of your command31// definition to ensure usability.32type Command struct {33 // Name is the command name, usually the executable's name.34 name string35 // The one-line usage message.36 Use string

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 37–38why, one step back
37 // An array of aliases that can be used instead of the first word in Use.
38 Aliases []string

Organize the files a bit betterspf13before adoption62fb674

lines 39–42why, one step back
39 // The short description shown in the 'help' output.
40 Short string41 // The long message shown in the 'help <this-command>' output.42 Long string

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 43–44why, one step back
43 // Examples of how to use the command
44 Example string

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 45why, one step back
45 // Full set of flags

Organize the files a bit betterspf13before adoption62fb674

line 46why, one step back
46 flags *flag.FlagSet

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 47why, one step back
47 // Set of flags childrens of this command will inherit

Organize the files a bit betterspf13before adoption62fb674

line 48why, one step back
48 pflags *flag.FlagSet

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 49–50why, one step back
49 // Flags that are declared specifically by this command (not inherited).
50 lflags *flag.FlagSet

Organize the files a bit betterspf13before adoption62fb674

lines 51–53why, one step back
51 // Run runs the command.
52 // The args are the arguments after the command name.53 Run func(cmd *Command, args []string)

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

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

Organize the files a bit betterspf13before adoption62fb674

lines 55–56why, one step back
55 commands []*Command
56 // Parent Command for this command

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 57why, one step back
57 parent *Command

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 58–60why, one step back
58 // max lengths of commands' string lengths for use in padding
59 commandsMaxUseLen int60 commandsMaxCommandPathLen int

help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24

line 61why, one step back
61 commandsMaxNameLen int

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 62why, one step back
62

Organize the files a bit betterspf13before adoption62fb674

line 63why, one step back
63 flagErrorBuf *bytes.Buffer

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b

line 64why, one step back
64 cmdErrorBuf *bytes.Buffer

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 65why, one step back
65

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 66why, one step back
66 args []string // actual args parsed from flags

Documentation updatespf13before adoption59bd285

line 67why, one step back
67 output *io.Writer // nil means stderr; use Out() method instead

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 68–72why, one step back
68 usageFunc func(*Command) error // Usage can be defined by application
69 usageTemplate string // Can be defined by Application70 helpTemplate string // Can be defined by Application71 helpFunc func(*Command, []string) // Help can be defined by application72 helpCommand *Command // The help command

Adding support for --helpspf13before adoption07be814

line 73why, one step back
73 helpFlagVal bool

Organize the files a bit betterspf13before adoption62fb674

lines 74–75why, one step back
74}
75

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 76–79why, one step back
76// os.Args[1:] by default, if desired, can be overridden
77// particularly useful when testing.78func (c *Command) SetArgs(a []string) {79 c.args = a

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 80–81why, one step back
80}
81

Default usage output to stdoutEric Parisbefore adoption6de96b8

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

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 83–89why, one step back
83 if c.output != nil {
84 return *c.output85 }8687 if c.HasParent() {88 return c.parent.Out()89 } else {

Default usage output to stdoutEric Parisbefore adoption6de96b8

line 90why, one step back
90 return def

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 91–93why, one step back
91 }
92}93

Default usage output to stdoutEric Parisbefore adoption6de96b8

lines 94–101why, one step back
94func (c *Command) Out() io.Writer {
95 return c.getOut(os.Stderr)96}9798func (c *Command) getOutOrStdout() io.Writer {99 return c.getOut(os.Stdout)100}101

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 102–156why, one step back
102// SetOutput sets the destination for usage and error messages.
103// If output is nil, os.Stderr is used.104func (c *Command) SetOutput(output io.Writer) {105 c.output = &output106}107108// Usage can be defined by application109func (c *Command) SetUsageFunc(f func(*Command) error) {110 c.usageFunc = f111}112113// Can be defined by Application114func (c *Command) SetUsageTemplate(s string) {115 c.usageTemplate = s116}117118// Can be defined by Application119func (c *Command) SetHelpFunc(f func(*Command, []string)) {120 c.helpFunc = f121}122123func (c *Command) SetHelpCommand(cmd *Command) {124 c.helpCommand = cmd125}126127// Can be defined by Application128func (c *Command) SetHelpTemplate(s string) {129 c.helpTemplate = s130}131132func (c *Command) UsageFunc() (f func(*Command) error) {133 if c.usageFunc != nil {134 return c.usageFunc135 }136137 if c.HasParent() {138 return c.parent.UsageFunc()139 } else {140 return func(c *Command) error {141 err := tmpl(c.Out(), c.UsageTemplate(), c)142 return err143 }144 }145}146func (c *Command) HelpFunc() func(*Command, []string) {147 if c.helpFunc != nil {148 return c.helpFunc149 }150151 if c.HasParent() {152 return c.parent.HelpFunc()153 } else {154 return func(c *Command, args []string) {155 if len(args) == 0 {156 // Help called without any topic, calling on root

Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f

line 157why, one step back
157 c.Root().Help()

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 158–175why, one step back
158 return
159 }160161 cmd, _, e := c.Root().Find(args)162 if cmd == nil || e != nil {163 c.Printf("Unknown help topic %#q.", args)164165 c.Root().Usage()166 } else {167 err := cmd.Help()168 if err != nil {169 c.Println(err)170 }171 }172 }173 }174}175

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 176–187why, one step back
176var minUsagePadding int = 25
177178func (c *Command) UsagePadding() int {179 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {180 return minUsagePadding181 } else {182 return c.parent.commandsMaxUseLen183 }184}185186var minCommandPathPadding int = 11187

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 188why, one step back
188//

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 189–196why, one step back
189func (c *Command) CommandPathPadding() int {
190 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {191 return minCommandPathPadding192 } else {193 return c.parent.commandsMaxCommandPathLen194 }195}196

help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24

lines 197–206why, one step back
197var minNamePadding int = 11
198199func (c *Command) NamePadding() int {200 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {201 return minNamePadding202 } else {203 return c.parent.commandsMaxNameLen204 }205}206

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 207–217why, one step back
207func (c *Command) UsageTemplate() string {
208 if c.usageTemplate != "" {209 return c.usageTemplate210 }211212 if c.HasParent() {213 return c.parent.UsageTemplate()214 } else {215 return `{{ $cmd := . }}216Usage: {{if .Runnable}}217 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 218–220why, one step back
218 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
219220Aliases:

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 221–222why, one step back
221 {{.NameAndAliases}}
222{{end}}{{if .HasExample}}

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 223why, one step back
223

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 224–226why, one step back
224Examples:
225{{ .Example }}226{{end}}{{ if .HasSubCommands}}

fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59

line 227why, one step back
227

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 228why, one step back
228Available Commands: {{range .Commands}}{{if .Runnable}}

help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24

line 229why, one step back
229 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 230why, one step back
230{{end}}

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 231–232why, one step back
231{{ if .HasLocalFlags}}Flags:
232{{.LocalFlags.FlagUsages}}{{end}}

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 233–234why, one step back
233{{ if .HasInheritedFlags}}Global Flags:
234{{.InheritedFlags.FlagUsages}}{{end}}{{if .HasParent}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}

Remove "::" from output. Fixed #4spf13before adoption1a6c5d1

lines 235–236why, one step back
235Additional help topics: {{if gt .Commands 0 }}{{range .Commands}}{{if not .Runnable}} {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if gt .Parent.Commands 1 }}{{range .Parent.Commands}}{{if .Runnable}}{{if not (eq .Name $cmd.Name) }}{{end}}
236 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{end}}

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

line 237why, one step back
237{{end}}{{ if .HasSubCommands }}

Minor English correctionKartik Singhalbefore adoptionc36f627

line 238why, one step back
238Use "{{.Root.Name}} help [command]" for more information about a command.

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

line 239why, one step back
239{{end}}`

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 240–250why, one step back
240 }
241}242243func (c *Command) HelpTemplate() string {244 if c.helpTemplate != "" {245 return c.helpTemplate246 }247248 if c.HasParent() {249 return c.parent.HelpTemplate()250 } else {

Help uses Short message if Long is not availableEdgard Castrobefore adoption384c059

line 251why, one step back
251 return `{{with or .Long .Short }}{{. | trim}}{{end}}

Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f

line 252why, one step back
252{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 253–256why, one step back
253`
254 }255}256

Add ability to cast a command to a commanderspf13before adoption74ce44d

lines 257–263why, one step back
257// Really only used when casting a command to a commander
258func (c *Command) resetChildrensParents() {259 for _, x := range c.commands {260 x.parent = c261 }262}263

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

lines 264–274why, one step back
264// Test if the named flag is a boolean flag.
265func isBooleanFlag(name string, f *flag.FlagSet) bool {266 flag := f.Lookup(name)267 if flag == nil {268 return false269 }270 return flag.Value.Type() == "bool"271}272273// Test if the named flag is a boolean flag.274func isBooleanShortFlag(name string, f *flag.FlagSet) bool {

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

lines 275–280why, one step back
275 result := false
276 f.VisitAll(func(f *flag.Flag) {277 if f.Shorthand == name && f.Value.Type() == "bool" {278 result = true279 }280 })

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

lines 281–284why, one step back
281 return result
282}283284func stripFlags(args []string, c *Command) []string {

Support for flags before commandsspf13before adoption10a8494

lines 285–287why, one step back
285 if len(args) < 1 {
286 return args287 }

Merge pull request #70 from brendandburns/masterBjørn Erik Pedersenbefore adoption6264dc6

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

Support for flags before commandsspf13before adoption10a8494

lines 289–292why, one step back
289
290 commands := []string{}291292 inQuote := false

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

line 293why, one step back
293 inFlag := false

Support for flags before commandsspf13before adoption10a8494

lines 294–300why, one step back
294 for _, y := range args {
295 if !inQuote {296 switch {297 case strings.HasPrefix(y, "\""):298 inQuote = true299 case strings.Contains(y, "=\""):300 inQuote = true

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

lines 301–307why, one step back
301 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
302 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'303 inFlag = !isBooleanFlag(y[2:], c.Flags())304 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):305 inFlag = true306 case inFlag:307 inFlag = false

Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1

lines 308–309why, one step back
308 case y == "":
309 // strip empty commands, as the go tests expect this to be ok....

Support for flags before commandsspf13before adoption10a8494

lines 310–311why, one step back
310 case !strings.HasPrefix(y, "-"):
311 commands = append(commands, y)

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

line 312why, one step back
312 inFlag = false

Support for flags before commandsspf13before adoption10a8494

lines 313–334why, one step back
313 }
314 }315316 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {317 inQuote = false318 }319 }320321 return commands322}323324func argsMinusX(args []string, x string) []string {325 newargs := []string{}326327 for _, y := range args {328 if x != y {329 newargs = append(newargs, y)330 }331 }332 return newargs333}334

Organize the files a bit betterspf13before adoption62fb674

line 335why, one step back
335// find the target command given the args and command tree

Add support for help commandspf13before adoptionfb2146e

line 336why, one step back
336// Meant to be run on the highest node. Only searches down.

Finding command based on args cleaned upspf13before adoption55ff474

line 337why, one step back
337func (c *Command) Find(arrs []string) (*Command, []string, error) {

Organize the files a bit betterspf13before adoption62fb674

lines 338–341why, one step back
338 if c == nil {
339 return nil, nil, fmt.Errorf("Called find() on a nil Command")340 }341

Finding command based on args cleaned upspf13before adoption55ff474

line 342why, one step back
342 if len(arrs) == 0 {

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 343why, one step back
343 return c.Root(), arrs, nil

Finding command based on args cleaned upspf13before adoption55ff474

lines 344–349why, one step back
344 }
345346 var innerfind func(*Command, []string) (*Command, []string)347348 innerfind = func(c *Command, args []string) (*Command, []string) {349 if len(args) > 0 && c.HasSubCommands() {

Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35

line 350why, one step back
350 argsWOflags := stripFlags(args, c)

Support for flags before commandsspf13before adoption10a8494

line 351why, one step back
351 if len(argsWOflags) > 0 {

adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac

line 352why, one step back
352 matches := make([]*Command, 0)

Support for flags before commandsspf13before adoption10a8494

line 353why, one step back
353 for _, cmd := range c.commands {

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 354–355why, one step back
354 if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match
355 return innerfind(cmd, argsMinusX(args, argsWOflags[0]))

Making prefix matching opt in.spf13before adoptionb1e90a7

line 356why, one step back
356 } else if EnablePrefixMatching {

adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac

lines 357–364why, one step back
357 if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match
358 matches = append(matches, cmd)359 }360 for _, x := range cmd.Aliases {361 if strings.HasPrefix(x, argsWOflags[0]) {362 matches = append(matches, cmd)363 }364 }

Support for flags before commandsspf13before adoption10a8494

line 365why, one step back
365 }

adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac

lines 366–370why, one step back
366 }
367368 // only accept a single prefix match - multiple matches would be ambiguous369 if len(matches) == 1 {370 return innerfind(matches[0], argsMinusX(args, argsWOflags[0]))

Finding command based on args cleaned upspf13before adoption55ff474

line 371why, one step back
371 }

Organize the files a bit betterspf13before adoption62fb674

lines 372–373why, one step back
372 }
373 }

Finding command based on args cleaned upspf13before adoption55ff474

lines 374–375why, one step back
374
375 return c, args

Organize the files a bit betterspf13before adoption62fb674

line 376why, one step back
376 }

Finding command based on args cleaned upspf13before adoption55ff474

lines 377–379why, one step back
377
378 commandFound, a := innerfind(c, arrs)379

Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1

lines 380–381why, one step back
380 // If we matched on the root, but we asked for a subcommand, return an error
381 if commandFound.Name() == c.Name() && len(stripFlags(arrs, c)) > 0 && commandFound.Name() != arrs[0] {

Merge pull request #83 from adammck/fix_double_output_on_unknown_commandEric Parisbefore adoption09b49c3

line 382why, one step back
382 return nil, a, fmt.Errorf("unknown command %q", a[0])

Organize the files a bit betterspf13before adoption62fb674

lines 383–384why, one step back
383 }
384

Finding command based on args cleaned upspf13before adoption55ff474

line 385why, one step back
385 return commandFound, a, nil

Organize the files a bit betterspf13before adoption62fb674

lines 386–387why, one step back
386}
387

Add support for help commandspf13before adoptionfb2146e

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

Organize the files a bit betterspf13before adoption62fb674

lines 389–397why, one step back
389 var findRoot func(*Command) *Command
390391 findRoot = func(x *Command) *Command {392 if x.HasParent() {393 return findRoot(x.parent)394 } else {395 return x396 }397 }

Add support for help commandspf13before adoptionfb2146e

lines 398–401why, one step back
398
399 return findRoot(c)400}401

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

line 402why, one step back
402func (c *Command) execute(a []string) (err error) {

Organize the files a bit betterspf13before adoption62fb674

lines 403–406why, one step back
403 if c == nil {
404 return fmt.Errorf("Called Execute() on a nil Command")405 }406

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

line 407why, one step back
407 err = c.ParseFlags(a)

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

lines 408–411why, one step back
408 if err == flag.ErrHelp {
409 c.Help()410 return nil411 }

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

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

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b

line 413why, one step back
413 // We're writing subcommand usage to root command's error buffer to have it displayed to the user

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9

lines 414–416why, one step back
414 r := c.Root()
415 if r.cmdErrorBuf == nil {416 r.cmdErrorBuf = new(bytes.Buffer)

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b

lines 417–418why, one step back
417 }
418 // for writing the usage to the buffer we need to switch the output temporarily

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9

lines 419–421why, one step back
419 // since Out() returns root output, you also need to revert that on root
420 out := r.Out()421 r.SetOutput(r.cmdErrorBuf)

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b

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

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9

line 423why, one step back
423 r.SetOutput(out)

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

line 424why, one step back
424 return err

Slight formatting change, to make next commit more readableEric Parisbefore adoptionb9e25fa

lines 425–429why, one step back
425 }
426 // If help is called, regardless of other flags, we print that.427 // Print help also if c.Run is nil.428 if c.helpFlagVal || !c.Runnable() {429 c.Help()

fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7

line 430why, one step back
430 return nil

Organize the files a bit betterspf13before adoption62fb674

line 431why, one step back
431 }

Slight formatting change, to make next commit more readableEric Parisbefore adoptionb9e25fa

lines 432–436why, one step back
432
433 c.preRun()434 argWoFlags := c.Flags().Args()435 c.Run(c, argWoFlags)436 return nil

Organize the files a bit betterspf13before adoption62fb674

lines 437–438why, one step back
437}
438

Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3

line 439why, one step back
439func (c *Command) preRun() {

Adding "OnInitialize()" method instead of directly setting a property. Now can have multiple initializers.spf13before adoption864687a

lines 440–442why, one step back
440 for _, x := range initializers {
441 x()442 }

Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3

lines 443–444why, one step back
443}
444

Support for flags before commandsspf13before adoption10a8494

lines 445–456why, one step back
445func (c *Command) errorMsgFromParse() string {
446 s := c.flagErrorBuf.String()447448 x := strings.Split(s, "\n")449450 if len(x) > 0 {451 return x[0]452 } else {453 return ""454 }455}456

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 457–478why, one step back
457// Call execute to use the args (os.Args[1:] by default)
458// and run through the command tree finding appropriate matches459// for commands and then corresponding flags.460func (c *Command) Execute() (err error) {461462 // Regardless of what command execute is called on, run on Root only463 if c.HasParent() {464 return c.Root().Execute()465 }466467 // initialize help as the last point possible to allow for user468 // overriding469 c.initHelp()470471 var args []string472473 if len(c.args) == 0 {474 args = os.Args[1:]475 } else {476 args = c.args477 }478

Remove specail casing in Execute()Eric Parisbefore adoption794a362

lines 479–481why, one step back
479 cmd, flags, err := c.Find(args)
480 if err == nil {481 err = cmd.execute(flags)

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 482–484why, one step back
482 }
483484 if err != nil {

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

lines 485–486why, one step back
485 if err == flag.ErrHelp {
486 c.Help()

Merge pull request #83 from adammck/fix_double_output_on_unknown_commandEric Parisbefore adoption09b49c3

line 487why, one step back
487

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

lines 488–489why, one step back
488 } else {
489 c.Println("Error:", err.Error())

Merge pull request #83 from adammck/fix_double_output_on_unknown_commandEric Parisbefore adoption09b49c3

line 490why, one step back
490 c.Printf("Run '%v help' for usage.\n", c.Root().Name())

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d

line 491why, one step back
491 }

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 492–498why, one step back
492 }
493494 return495}496497func (c *Command) initHelp() {498 if c.helpCommand == nil {

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

lines 499–502why, one step back
499 if !c.HasSubCommands() {
500 return501 }502

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

lines 503–513why, one step back
503 c.helpCommand = &Command{
504 Use: "help [command]",505 Short: "Help about any command",506 Long: `Help provides help for any command in the application.507 Simply type ` + c.Name() + ` help [path to command] for full details.`,508 Run: c.HelpFunc(),509 }510 }511 c.AddCommand(c.helpCommand)512}513

Organize the files a bit betterspf13before adoption62fb674

lines 514–516why, one step back
514// Used for testing
515func (c *Command) ResetCommands() {516 c.commands = nil

Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817

line 517why, one step back
517 c.helpCommand = nil

Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9

lines 518–519why, one step back
518 c.cmdErrorBuf = new(bytes.Buffer)
519 c.cmdErrorBuf.Reset()

Organize the files a bit betterspf13before adoption62fb674

lines 520–521why, one step back
520}
521

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 522why, one step back
522//Commands returns a slice of child commands.

Organize the files a bit betterspf13before adoption62fb674

lines 523–526why, one step back
523func (c *Command) Commands() []*Command {
524 return c.commands525}526

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 527why, one step back
527// AddCommand adds one or more commands to this parent command.

Organize the files a bit betterspf13before adoption62fb674

lines 528–533why, one step back
528func (c *Command) AddCommand(cmds ...*Command) {
529 for i, x := range cmds {530 if cmds[i] == c {531 panic("Command can't be a child of itself")532 }533 cmds[i].parent = c

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

lines 534–541why, one step back
534 // update max lengths
535 usageLen := len(x.Use)536 if usageLen > c.commandsMaxUseLen {537 c.commandsMaxUseLen = usageLen538 }539 commandPathLen := len(x.CommandPath())540 if commandPathLen > c.commandsMaxCommandPathLen {541 c.commandsMaxCommandPathLen = commandPathLen

help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24

lines 542–545why, one step back
542 }
543 nameLen := len(x.Name())544 if nameLen > c.commandsMaxNameLen {545 c.commandsMaxNameLen = nameLen

Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e

line 546why, one step back
546 }

Organize the files a bit betterspf13before adoption62fb674

lines 547–550why, one step back
547 c.commands = append(c.commands, x)
548 }549}550

Add Command's RemoveCommand methodÉtienne Vallette d'Osiabefore adoptionf479c92

lines 551–584why, one step back
551// AddCommand removes one or more commands from a parent command.
552func (c *Command) RemoveCommand(cmds ...*Command) {553 commands := []*Command{}554main:555 for _, command := range c.commands {556 for _, cmd := range cmds {557 if command == cmd {558 command.parent = nil559 continue main560 }561 }562 commands = append(commands, command)563 }564 c.commands = commands565 // recompute all lengths566 c.commandsMaxUseLen = 0567 c.commandsMaxCommandPathLen = 0568 c.commandsMaxNameLen = 0569 for _, command := range c.commands {570 usageLen := len(command.Use)571 if usageLen > c.commandsMaxUseLen {572 c.commandsMaxUseLen = usageLen573 }574 commandPathLen := len(command.CommandPath())575 if commandPathLen > c.commandsMaxCommandPathLen {576 c.commandsMaxCommandPathLen = commandPathLen577 }578 nameLen := len(command.Name())579 if nameLen > c.commandsMaxNameLen {580 c.commandsMaxNameLen = nameLen581 }582 }583}584

Organize the files a bit betterspf13before adoption62fb674

lines 585–586why, one step back
585// Convenience method to Print to the defined output
586func (c *Command) Print(i ...interface{}) {

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 587why, one step back
587 fmt.Fprint(c.Out(), i...)

Organize the files a bit betterspf13before adoption62fb674

lines 588–603why, one step back
588}
589590// Convenience method to Println to the defined output591func (c *Command) Println(i ...interface{}) {592 str := fmt.Sprintln(i...)593 c.Print(str)594}595596// Convenience method to Printf to the defined output597func (c *Command) Printf(format string, i ...interface{}) {598 str := fmt.Sprintf(format, i...)599 c.Print(str)600}601602// Output the usage for the command603// Used when a user provides invalid input

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 604why, one step back
604// Can be defined by user by overriding UsageFunc

Organize the files a bit betterspf13before adoption62fb674

line 605why, one step back
605func (c *Command) Usage() error {

Help improvementsspf13before adoption2d02c31

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

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 607why, one step back
607 err := c.UsageFunc()(c)

Help improvementsspf13before adoption2d02c31

lines 608–615why, one step back
608 return err
609}610611// Output the help for the command612// Used when a user calls help [command]613// by the default HelpFunc in the commander614func (c *Command) Help() error {615 c.mergePersistentFlags()

Default usage output to stdoutEric Parisbefore adoption6de96b8

line 616why, one step back
616 err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)

Organize the files a bit betterspf13before adoption62fb674

lines 617–619why, one step back
617 return err
618}619

fix trailing <nil> on help outputspf13before adoption3958385

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

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 621why, one step back
621 tmpOutput := c.output

fix trailing <nil> on help outputspf13before adoption3958385

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

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 623why, one step back
623 c.SetOutput(bb)

fix trailing <nil> on help outputspf13before adoption3958385

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

Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5

line 625why, one step back
625 c.output = tmpOutput

fix trailing <nil> on help outputspf13before adoption3958385

lines 626–628why, one step back
626 return bb.String()
627}628

Code commentaryAhsanul Haquebefore adoptione1e66f7

line 629why, one step back
629// CommandPath returns the full path to this command.

Organize the files a bit betterspf13before adoption62fb674

lines 630–704why, one step back
630func (c *Command) CommandPath() string {
631 str := c.Name()632 x := c633 for x.HasParent() {634 str = x.parent.Name() + " " + str635 x = x.parent636 }637 return str638}639640//The full usage for a given command (including parents)641func (c *Command) UseLine() string {642 str := ""643 if c.HasParent() {644 str = c.parent.CommandPath() + " "645 }646 return str + c.Use647}648649// For use in determining which flags have been assigned to which commands650// and which persist651func (c *Command) DebugFlags() {652 c.Println("DebugFlags called on", c.Name())653 var debugflags func(*Command)654655 debugflags = func(x *Command) {656 if x.HasFlags() || x.HasPersistentFlags() {657 c.Println(x.Name())658 }659 if x.HasFlags() {660 x.flags.VisitAll(func(f *flag.Flag) {661 if x.HasPersistentFlags() {662 if x.persistentFlag(f.Name) == nil {663 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")664 } else {665 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")666 }667 } else {668 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")669 }670 })671 }672 if x.HasPersistentFlags() {673 x.pflags.VisitAll(func(f *flag.Flag) {674 if x.HasFlags() {675 if x.flags.Lookup(f.Name) == nil {676 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")677 }678 } else {679 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")680 }681 })682 }683 c.Println(x.flagErrorBuf)684 if x.HasSubCommands() {685 for _, y := range x.commands {686 debugflags(y)687 }688 }689 }690691 debugflags(c)692}693694// Name returns the command's name: the first word in the use line.695func (c *Command) Name() string {696 if c.name != "" {697 return c.name698 }699 name := c.Use700 i := strings.Index(name, " ")701 if i >= 0 {702 name = name[:i]703 }704 return name

Replace prefix matching with aliasesSam Ghodsbefore adoption8816572

lines 705–718why, one step back
705}
706707// Determine if a given string is an alias of the command.708func (c *Command) HasAlias(s string) bool {709 for _, a := range c.Aliases {710 if a == s {711 return true712 }713 }714 return false715}716717func (c *Command) NameAndAliases() string {718 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")

New "example" section of commandsEric Parisbefore adoptionbf480fe

lines 719–722why, one step back
719}
720721func (c *Command) HasExample() bool {722 return len(c.Example) > 0

Organize the files a bit betterspf13before adoption62fb674

lines 723–739why, one step back
723}
724725// Determine if the command is itself runnable726func (c *Command) Runnable() bool {727 return c.Run != nil728}729730// Determine if the command has children commands731func (c *Command) HasSubCommands() bool {732 return len(c.commands) > 0733}734735// Determine if the command is a child command736func (c *Command) HasParent() bool {737 return c.parent != nil738}739

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 740why, one step back
740// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)

Organize the files a bit betterspf13before adoption62fb674

lines 741–747why, one step back
741func (c *Command) Flags() *flag.FlagSet {
742 if c.flags == nil {743 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)744 if c.flagErrorBuf == nil {745 c.flagErrorBuf = new(bytes.Buffer)746 }747 c.flags.SetOutput(c.flagErrorBuf)

changed help flag setup to use PersistenFlags so -h will be supportedJoel Scoblebefore adoption83b58a2

line 748why, one step back
748 c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name())

Organize the files a bit betterspf13before adoption62fb674

lines 749–752why, one step back
749 }
750 return c.flags751}752

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 753–757why, one step back
753// Get the local FlagSet specifically set in the current command
754func (c *Command) LocalFlags() *flag.FlagSet {755 c.mergePersistentFlags()756757 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 758–759why, one step back
758 c.lflags.VisitAll(func(f *flag.Flag) {
759 local.AddFlag(f)

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 760–763why, one step back
760 })
761 return local762}763

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

lines 764–767why, one step back
764// All Flags which were inherited from parents commands
765func (c *Command) InheritedFlags() *flag.FlagSet {766 c.mergePersistentFlags()767

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 768–769why, one step back
768 inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
769 local := c.LocalFlags()

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

line 770why, one step back
770

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 771why, one step back
771 var rmerge func(x *Command)

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

line 772why, one step back
772

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 773–784why, one step back
773 rmerge = func(x *Command) {
774 if x.HasPersistentFlags() {775 x.PersistentFlags().VisitAll(func(f *flag.Flag) {776 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {777 inherited.AddFlag(f)778 }779 })780 }781 if x.HasParent() {782 rmerge(x.parent)783 }784 }

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

lines 785–789why, one step back
785
786 if c.HasParent() {787 rmerge(c.parent)788 }789

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 790why, one step back
790 return inherited

new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75

lines 791–792why, one step back
791}
792

new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5

lines 793–794why, one step back
793// All Flags which were not inherited from parent commands
794func (c *Command) NonInheritedFlags() *flag.FlagSet {

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

line 795why, one step back
795 return c.LocalFlags()

new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5

lines 796–797why, one step back
796}
797

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 798why, one step back
798// Get the Persistent FlagSet specifically set in the current command

Organize the files a bit betterspf13before adoption62fb674

lines 799–819why, one step back
799func (c *Command) PersistentFlags() *flag.FlagSet {
800 if c.pflags == nil {801 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)802 if c.flagErrorBuf == nil {803 c.flagErrorBuf = new(bytes.Buffer)804 }805 c.pflags.SetOutput(c.flagErrorBuf)806 }807 return c.pflags808}809810// For use in testing811func (c *Command) ResetFlags() {812 c.flagErrorBuf = new(bytes.Buffer)813 c.flagErrorBuf.Reset()814 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)815 c.flags.SetOutput(c.flagErrorBuf)816 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)817 c.pflags.SetOutput(c.flagErrorBuf)818}819

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

line 820why, one step back
820// Does the command contain any flags (local plus persistent from the entire structure)

Organize the files a bit betterspf13before adoption62fb674

lines 821–829why, one step back
821func (c *Command) HasFlags() bool {
822 return c.Flags().HasFlags()823}824825// Does the command contain persistent flags826func (c *Command) HasPersistentFlags() bool {827 return c.PersistentFlags().HasFlags()828}829

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 830–834why, one step back
830// Does the command has flags specifically declared locally
831func (c *Command) HasLocalFlags() bool {832 return c.LocalFlags().HasFlags()833}834

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 835–838why, one step back
835func (c *Command) HasInheritedFlags() bool {
836 return c.InheritedFlags().HasFlags()837}838

Organize the files a bit betterspf13before adoption62fb674

lines 839–865why, one step back
839// Climbs up the command tree looking for matching flag
840func (c *Command) Flag(name string) (flag *flag.Flag) {841 flag = c.Flags().Lookup(name)842843 if flag == nil {844 flag = c.persistentFlag(name)845 }846847 return848}849850// recursively find matching persistent flag851func (c *Command) persistentFlag(name string) (flag *flag.Flag) {852 if c.HasPersistentFlags() {853 flag = c.PersistentFlags().Lookup(name)854 }855856 if flag == nil && c.HasParent() {857 flag = c.parent.persistentFlag(name)858 }859 return860}861862// Parses persistent flag tree & local flags863func (c *Command) ParseFlags(args []string) (err error) {864 c.mergePersistentFlags()865 err = c.Flags().Parse(args)

Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e

line 866why, one step back
866 return

Organize the files a bit betterspf13before adoption62fb674

lines 867–868why, one step back
867}
868

Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e

lines 869–872why, one step back
869func (c *Command) Parent() *Command {
870 return c.parent871}872

Organize the files a bit betterspf13before adoption62fb674

lines 873–875why, one step back
873func (c *Command) mergePersistentFlags() {
874 var rmerge func(x *Command)875

Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469

lines 876–888why, one step back
876 // Save the set of local flags
877 if c.lflags == nil {878 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)879 if c.flagErrorBuf == nil {880 c.flagErrorBuf = new(bytes.Buffer)881 }882 c.lflags.SetOutput(c.flagErrorBuf)883 addtolocal := func(f *flag.Flag) {884 c.lflags.AddFlag(f)885 }886 c.Flags().VisitAll(addtolocal)887 c.PersistentFlags().VisitAll(addtolocal)888 }

Organize the files a bit betterspf13before adoption62fb674

lines 889–903why, one step back
889 rmerge = func(x *Command) {
890 if x.HasPersistentFlags() {891 x.PersistentFlags().VisitAll(func(f *flag.Flag) {892 if c.Flags().Lookup(f.Name) == nil {893 c.Flags().AddFlag(f)894 }895 })896 }897 if x.HasParent() {898 rmerge(x.parent)899 }900 }901902 rmerge(c)903}