command.go
This file
Path
command.go
956 lines · 23.4 KiB · Go
Last changed by
Default usage output to stdoutEric Parisbefore adoption6de96b8
History of this fileTake it
Organize the files a bit betterspf13before adoption62fb674
lines 1–13why, one step back1// 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.13Code commentaryAhsanul Haquebefore adoptione1e66f7
lines 14–15why, one step back14//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 back16package cobra1718import (19 "bytes"20 "fmt"21 "io"Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 22why, one step back22 "os"Organize the files a bit betterspf13before adoption62fb674
line 23why, one step back23 "strings"Print root usage when help called with no args.Kevin Darlingtonbefore adoptione174a40
lines 24–25why, one step back2425 flag "github.com/spf13/pflag"Organize the files a bit betterspf13before adoption62fb674
lines 26–36why, one step back26)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 stringReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 37–38why, one step back37 // An array of aliases that can be used instead of the first word in Use.38 Aliases []stringOrganize the files a bit betterspf13before adoption62fb674
lines 39–42why, one step back39 // The short description shown in the 'help' output.40 Short string41 // The long message shown in the 'help <this-command>' output.42 Long stringNew "example" section of commandsEric Parisbefore adoptionbf480fe
lines 43–44why, one step back43 // Examples of how to use the command44 Example stringRestores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 45why, one step back45 // Full set of flagsOrganize the files a bit betterspf13before adoption62fb674
line 46why, one step back46 flags *flag.FlagSetRestores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 47why, one step back47 // Set of flags childrens of this command will inheritOrganize the files a bit betterspf13before adoption62fb674
line 48why, one step back48 pflags *flag.FlagSetExplicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 49–50why, one step back49 // Flags that are declared specifically by this command (not inherited).50 lflags *flag.FlagSetOrganize the files a bit betterspf13before adoption62fb674
lines 51–53why, one step back51 // 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 back54 // Commands is the list of commands supported by this program.Organize the files a bit betterspf13before adoption62fb674
lines 55–56why, one step back55 commands []*Command56 // Parent Command for this commandRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 57why, one step back57 parent *CommandMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 58–60why, one step back58 // max lengths of commands' string lengths for use in padding59 commandsMaxUseLen int60 commandsMaxCommandPathLen inthelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 61why, one step back61 commandsMaxNameLen intRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 62why, one step back62Organize the files a bit betterspf13before adoption62fb674
line 63why, one step back63 flagErrorBuf *bytes.BufferSubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 64why, one step back64 cmdErrorBuf *bytes.BufferRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 65why, one step back65Code commentaryAhsanul Haquebefore adoptione1e66f7
line 66why, one step back66 args []string // actual args parsed from flagsDocumentation updatespf13before adoption59bd285
line 67why, one step back67 output *io.Writer // nil means stderr; use Out() method insteadRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 68–72why, one step back68 usageFunc func(*Command) error // Usage can be defined by application69 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 commandAdding support for --helpspf13before adoption07be814
line 73why, one step back73 helpFlagVal boolOrganize the files a bit betterspf13before adoption62fb674
lines 74–75why, one step back74}75Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 76–79why, one step back76// os.Args[1:] by default, if desired, can be overridden77// particularly useful when testing.78func (c *Command) SetArgs(a []string) {79 c.args = aAdd ability to cast a command to a commanderspf13before adoption74ce44d
lines 80–81why, one step back80}81Default usage output to stdoutEric Parisbefore adoption6de96b8
line 82why, one step back82func (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 back83 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 back90 return defRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 91–93why, one step back91 }92}93Default usage output to stdoutEric Parisbefore adoption6de96b8
lines 94–101why, one step back94func (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}101Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 102–156why, one step back102// 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 rootPrint Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 157why, one step back157 c.Root().Help()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 158–175why, one step back158 return159 }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}175Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 176–187why, one step back176var minUsagePadding int = 25177178func (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 = 11187Code commentaryAhsanul Haquebefore adoptione1e66f7
line 188why, one step back188//Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 189–196why, one step back189func (c *Command) CommandPathPadding() int {190 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {191 return minCommandPathPadding192 } else {193 return c.parent.commandsMaxCommandPathLen194 }195}196help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 197–206why, one step back197var minNamePadding int = 11198199func (c *Command) NamePadding() int {200 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {201 return minNamePadding202 } else {203 return c.parent.commandsMaxNameLen204 }205}206Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 207–217why, one step back207func (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 back218 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}219220Aliases:New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 221–225why, one step back221 {{.NameAndAliases}}222{{end}}{{if .HasExample}}223Examples:224{{ .Example }}225{{end}}{{ if .HasSubCommands}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 226why, one step back226Available Commands: {{range .Commands}}{{if .Runnable}}help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 227why, one step back227 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 228why, one step back228{{end}}Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 229–230why, one step back229{{ if .HasLocalFlags}}Flags:230{{.LocalFlags.FlagUsages}}{{end}}Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 231–232why, one step back231{{ if .HasInheritedFlags}}Global Flags:232{{.InheritedFlags.FlagUsages}}{{end}}{{if .HasParent}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}Remove "::" from output. Fixed #4spf13before adoption1a6c5d1
lines 233–234why, one step back233Additional 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}}234 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{end}}Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 235why, one step back235{{end}}{{ if .HasSubCommands }}Minor English correctionKartik Singhalbefore adoptionc36f627
line 236why, one step back236Use "{{.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 237why, one step back237{{end}}`Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 238–249why, one step back238 }239}240241func (c *Command) HelpTemplate() string {242 if c.helpTemplate != "" {243 return c.helpTemplate244 }245246 if c.HasParent() {247 return c.parent.HelpTemplate()248 } else {249 return `{{.Long | trim}}Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 250why, one step back250{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 251–254why, one step back251`252 }253}254Add ability to cast a command to a commanderspf13before adoption74ce44d
lines 255–261why, one step back255// Really only used when casting a command to a commander256func (c *Command) resetChildrensParents() {257 for _, x := range c.commands {258 x.parent = c259 }260}261Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 262–272why, one step back262// Test if the named flag is a boolean flag.263func isBooleanFlag(name string, f *flag.FlagSet) bool {264 flag := f.Lookup(name)265 if flag == nil {266 return false267 }268 return flag.Value.Type() == "bool"269}270271// Test if the named flag is a boolean flag.272func isBooleanShortFlag(name string, f *flag.FlagSet) bool {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 273–278why, one step back273 result := false274 f.VisitAll(func(f *flag.Flag) {275 if f.Shorthand == name && f.Value.Type() == "bool" {276 result = true277 }278 })Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 279–282why, one step back279 return result280}281282func stripFlags(args []string, c *Command) []string {Support for flags before commandsspf13before adoption10a8494
lines 283–285why, one step back283 if len(args) < 1 {284 return args285 }Merge pull request #70 from brendandburns/masterBjørn Erik Pedersenbefore adoption6264dc6
line 286why, one step back286 c.mergePersistentFlags()Support for flags before commandsspf13before adoption10a8494
lines 287–290why, one step back287288 commands := []string{}289290 inQuote := falseFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 291why, one step back291 inFlag := falseSupport for flags before commandsspf13before adoption10a8494
lines 292–298why, one step back292 for _, y := range args {293 if !inQuote {294 switch {295 case strings.HasPrefix(y, "\""):296 inQuote = true297 case strings.Contains(y, "=\""):298 inQuote = trueFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 299–305why, one step back299 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):300 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'301 inFlag = !isBooleanFlag(y[2:], c.Flags())302 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):303 inFlag = true304 case inFlag:305 inFlag = falseSupport for flags before commandsspf13before adoption10a8494
lines 306–307why, one step back306 case !strings.HasPrefix(y, "-"):307 commands = append(commands, y)Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 308why, one step back308 inFlag = falseSupport for flags before commandsspf13before adoption10a8494
lines 309–330why, one step back309 }310 }311312 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {313 inQuote = false314 }315 }316317 return commands318}319320func argsMinusX(args []string, x string) []string {321 newargs := []string{}322323 for _, y := range args {324 if x != y {325 newargs = append(newargs, y)326 }327 }328 return newargs329}330Organize the files a bit betterspf13before adoption62fb674
line 331why, one step back331// find the target command given the args and command treeAdd support for help commandspf13before adoptionfb2146e
line 332why, one step back332// Meant to be run on the highest node. Only searches down.Finding command based on args cleaned upspf13before adoption55ff474
line 333why, one step back333func (c *Command) Find(arrs []string) (*Command, []string, error) {Organize the files a bit betterspf13before adoption62fb674
lines 334–337why, one step back334 if c == nil {335 return nil, nil, fmt.Errorf("Called find() on a nil Command")336 }337Finding command based on args cleaned upspf13before adoption55ff474
line 338why, one step back338 if len(arrs) == 0 {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 339why, one step back339 return c.Root(), arrs, nilFinding command based on args cleaned upspf13before adoption55ff474
lines 340–345why, one step back340 }341342 var innerfind func(*Command, []string) (*Command, []string)343344 innerfind = func(c *Command, args []string) (*Command, []string) {345 if len(args) > 0 && c.HasSubCommands() {Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 346why, one step back346 argsWOflags := stripFlags(args, c)Support for flags before commandsspf13before adoption10a8494
line 347why, one step back347 if len(argsWOflags) > 0 {adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
line 348why, one step back348 matches := make([]*Command, 0)Support for flags before commandsspf13before adoption10a8494
line 349why, one step back349 for _, cmd := range c.commands {Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 350–351why, one step back350 if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match351 return innerfind(cmd, argsMinusX(args, argsWOflags[0]))Making prefix matching opt in.spf13before adoptionb1e90a7
line 352why, one step back352 } else if EnablePrefixMatching {adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
lines 353–360why, one step back353 if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match354 matches = append(matches, cmd)355 }356 for _, x := range cmd.Aliases {357 if strings.HasPrefix(x, argsWOflags[0]) {358 matches = append(matches, cmd)359 }360 }Support for flags before commandsspf13before adoption10a8494
line 361why, one step back361 }adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
lines 362–366why, one step back362 }363364 // only accept a single prefix match - multiple matches would be ambiguous365 if len(matches) == 1 {366 return innerfind(matches[0], argsMinusX(args, argsWOflags[0]))Finding command based on args cleaned upspf13before adoption55ff474
line 367why, one step back367 }Organize the files a bit betterspf13before adoption62fb674
lines 368–369why, one step back368 }369 }Finding command based on args cleaned upspf13before adoption55ff474
lines 370–371why, one step back370371 return c, argsOrganize the files a bit betterspf13before adoption62fb674
line 372why, one step back372 }Finding command based on args cleaned upspf13before adoption55ff474
lines 373–375why, one step back373374 commandFound, a := innerfind(c, arrs)375Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 376–378why, one step back376 // if commander returned and the first argument (if it exists) doesn't377 // match the command name, return nil & error378 if commandFound.Name() == c.Name() && len(arrs[0]) > 0 && commandFound.Name() != arrs[0] {fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 379why, one step back379 return nil, a, fmt.Errorf("unknown command %q\nRun 'help' for usage.\n", a[0])Organize the files a bit betterspf13before adoption62fb674
lines 380–381why, one step back380 }381Finding command based on args cleaned upspf13before adoption55ff474
line 382why, one step back382 return commandFound, a, nilOrganize the files a bit betterspf13before adoption62fb674
lines 383–384why, one step back383}384Add support for help commandspf13before adoptionfb2146e
line 385why, one step back385func (c *Command) Root() *Command {Organize the files a bit betterspf13before adoption62fb674
lines 386–394why, one step back386 var findRoot func(*Command) *Command387388 findRoot = func(x *Command) *Command {389 if x.HasParent() {390 return findRoot(x.parent)391 } else {392 return x393 }394 }Add support for help commandspf13before adoptionfb2146e
lines 395–398why, one step back395396 return findRoot(c)397}398Organize the files a bit betterspf13before adoption62fb674
line 399why, one step back399// execute the command determined by args and the command treefixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 400why, one step back400func (c *Command) findAndExecute(args []string) (err error) {Organize the files a bit betterspf13before adoption62fb674
line 401why, one step back401fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 402–409why, one step back402 cmd, a, e := c.Find(args)403 if e != nil {404 return e405 }406 return cmd.execute(a)407}408409func (c *Command) execute(a []string) (err error) {Organize the files a bit betterspf13before adoption62fb674
lines 410–413why, one step back410 if c == nil {411 return fmt.Errorf("Called Execute() on a nil Command")412 }413fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 414why, one step back414 err = c.ParseFlags(a)Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 415–418why, one step back415 if err == flag.ErrHelp {416 c.Help()417 return nil418 }fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 419why, one step back419 if err != nil {Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 420why, one step back420 // We're writing subcommand usage to root command's error buffer to have it displayed to the userSubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
lines 421–423why, one step back421 r := c.Root()422 if r.cmdErrorBuf == nil {423 r.cmdErrorBuf = new(bytes.Buffer)Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
lines 424–425why, one step back424 }425 // for writing the usage to the buffer we need to switch the output temporarilySubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
lines 426–428why, one step back426 // since Out() returns root output, you also need to revert that on root427 out := r.Out()428 r.SetOutput(r.cmdErrorBuf)Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 429why, one step back429 c.Usage()Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
line 430why, one step back430 r.SetOutput(out)fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 431–432why, one step back431 return err432 } else {In execute(), check if command is Runnable()Anthony Fokbefore adoption4745f1f
lines 433–435why, one step back433 // If help is called, regardless of other flags, we print that.434 // Print help also if c.Run is nil.435 if c.helpFlagVal || !c.Runnable() {Adding support for --helpspf13before adoption07be814
lines 436–439why, one step back436 c.Help()437 return nil438 }439Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 440why, one step back440 c.preRun()fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 441–443why, one step back441 argWoFlags := c.Flags().Args()442 c.Run(c, argWoFlags)443 return nilOrganize the files a bit betterspf13before adoption62fb674
lines 444–446why, one step back444 }445}446Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 447why, one step back447func (c *Command) preRun() {Adding "OnInitialize()" method instead of directly setting a property. Now can have multiple initializers.spf13before adoption864687a
lines 448–450why, one step back448 for _, x := range initializers {449 x()450 }Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 451–452why, one step back451}452Support for flags before commandsspf13before adoption10a8494
lines 453–464why, one step back453func (c *Command) errorMsgFromParse() string {454 s := c.flagErrorBuf.String()455456 x := strings.Split(s, "\n")457458 if len(x) > 0 {459 return x[0]460 } else {461 return ""462 }463}464Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 465–491why, one step back465// Call execute to use the args (os.Args[1:] by default)466// and run through the command tree finding appropriate matches467// for commands and then corresponding flags.468func (c *Command) Execute() (err error) {469470 // Regardless of what command execute is called on, run on Root only471 if c.HasParent() {472 return c.Root().Execute()473 }474475 // initialize help as the last point possible to allow for user476 // overriding477 c.initHelp()478479 var args []string480481 if len(c.args) == 0 {482 args = os.Args[1:]483 } else {484 args = c.args485 }486487 if len(args) == 0 {488 // Only the executable is called and the root is runnable, run it489 if c.Runnable() {490 err = c.execute([]string(nil))491 } else {Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 492why, one step back492 c.Help()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 493–499why, one step back493 }494 } else {495 err = c.findAndExecute(args)496 }497498 // Now handle the case where the root is runnable and only flags are provided499 if err != nil && c.Runnable() {Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 500–501why, one step back500 // This is pretty much a custom version of the *Command.execute method501 // with a few differences because it's the final command (no fall back)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 502–503why, one step back502 e := c.ParseFlags(args)503 if e != nil {Cobra behavior is now more consistent. Invalid flags cause Usage to be printed.spf13before adoption71bb1df
line 504why, one step back504 // Flags parsing had an error.Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 505why, one step back505 // If an error happens here, we have to report it to the userRemove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e
line 506why, one step back506 c.Println(e.Error())Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
lines 507–512why, one step back507 // If an error happens search also for subcommand info about that508 if c.cmdErrorBuf != nil && c.cmdErrorBuf.Len() > 0 {509 c.Println(c.cmdErrorBuf.String())510 } else {511 c.Usage()512 }Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e
lines 513–514why, one step back513 err = e514 returnRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 515why, one step back515 } else {Adding support for --helpspf13before adoption07be814
lines 516–521why, one step back516 // If help is called, regardless of other flags, we print that517 if c.helpFlagVal {518 c.Help()519 return nil520 }521Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 522–523why, one step back522 argWoFlags := c.Flags().Args()523 if len(argWoFlags) > 0 {Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 524–526why, one step back524 // If there are arguments (not flags) one of the earlier525 // cases should have caught it.. It means invalid usage526 // print the usageRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 527–528why, one step back527 c.Usage()528 } else {Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 529–530why, one step back529 // Only flags left... Call root.Run530 c.preRun()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 531–537why, one step back531 c.Run(c, argWoFlags)532 err = nil533 }534 }535 }536537 if err != nil {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 538–544why, one step back538 if err == flag.ErrHelp {539 c.Help()540 } else {541 c.Println("Error:", err.Error())542 c.Printf("%v: invalid command %#q\n", c.Root().Name(), os.Args[1:])543 c.Printf("Run '%v help' for usage\n", c.Root().Name())544 }Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 545–551why, one step back545 }546547 return548}549550func (c *Command) initHelp() {551 if c.helpCommand == nil {Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
lines 552–555why, one step back552 if !c.HasSubCommands() {553 return554 }555Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 556–566why, one step back556 c.helpCommand = &Command{557 Use: "help [command]",558 Short: "Help about any command",559 Long: `Help provides help for any command in the application.560 Simply type ` + c.Name() + ` help [path to command] for full details.`,561 Run: c.HelpFunc(),562 }563 }564 c.AddCommand(c.helpCommand)565}566Organize the files a bit betterspf13before adoption62fb674
lines 567–569why, one step back567// Used for testing568func (c *Command) ResetCommands() {569 c.commands = nilMerge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 570why, one step back570 c.helpCommand = nilSubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
lines 571–572why, one step back571 c.cmdErrorBuf = new(bytes.Buffer)572 c.cmdErrorBuf.Reset()Organize the files a bit betterspf13before adoption62fb674
lines 573–574why, one step back573}574Code commentaryAhsanul Haquebefore adoptione1e66f7
line 575why, one step back575//Commands returns a slice of child commands.Organize the files a bit betterspf13before adoption62fb674
lines 576–579why, one step back576func (c *Command) Commands() []*Command {577 return c.commands578}579Code commentaryAhsanul Haquebefore adoptione1e66f7
line 580why, one step back580// AddCommand adds one or more commands to this parent command.Organize the files a bit betterspf13before adoption62fb674
lines 581–586why, one step back581func (c *Command) AddCommand(cmds ...*Command) {582 for i, x := range cmds {583 if cmds[i] == c {584 panic("Command can't be a child of itself")585 }586 cmds[i].parent = cMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 587–594why, one step back587 // update max lengths588 usageLen := len(x.Use)589 if usageLen > c.commandsMaxUseLen {590 c.commandsMaxUseLen = usageLen591 }592 commandPathLen := len(x.CommandPath())593 if commandPathLen > c.commandsMaxCommandPathLen {594 c.commandsMaxCommandPathLen = commandPathLenhelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 595–598why, one step back595 }596 nameLen := len(x.Name())597 if nameLen > c.commandsMaxNameLen {598 c.commandsMaxNameLen = nameLenMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
line 599why, one step back599 }Organize the files a bit betterspf13before adoption62fb674
lines 600–603why, one step back600 c.commands = append(c.commands, x)601 }602}603Add Command's RemoveCommand methodÉtienne Vallette d'Osiabefore adoptionf479c92
lines 604–637why, one step back604// AddCommand removes one or more commands from a parent command.605func (c *Command) RemoveCommand(cmds ...*Command) {606 commands := []*Command{}607main:608 for _, command := range c.commands {609 for _, cmd := range cmds {610 if command == cmd {611 command.parent = nil612 continue main613 }614 }615 commands = append(commands, command)616 }617 c.commands = commands618 // recompute all lengths619 c.commandsMaxUseLen = 0620 c.commandsMaxCommandPathLen = 0621 c.commandsMaxNameLen = 0622 for _, command := range c.commands {623 usageLen := len(command.Use)624 if usageLen > c.commandsMaxUseLen {625 c.commandsMaxUseLen = usageLen626 }627 commandPathLen := len(command.CommandPath())628 if commandPathLen > c.commandsMaxCommandPathLen {629 c.commandsMaxCommandPathLen = commandPathLen630 }631 nameLen := len(command.Name())632 if nameLen > c.commandsMaxNameLen {633 c.commandsMaxNameLen = nameLen634 }635 }636}637Organize the files a bit betterspf13before adoption62fb674
lines 638–639why, one step back638// Convenience method to Print to the defined output639func (c *Command) Print(i ...interface{}) {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 640why, one step back640 fmt.Fprint(c.Out(), i...)Organize the files a bit betterspf13before adoption62fb674
lines 641–656why, one step back641}642643// Convenience method to Println to the defined output644func (c *Command) Println(i ...interface{}) {645 str := fmt.Sprintln(i...)646 c.Print(str)647}648649// Convenience method to Printf to the defined output650func (c *Command) Printf(format string, i ...interface{}) {651 str := fmt.Sprintf(format, i...)652 c.Print(str)653}654655// Output the usage for the command656// Used when a user provides invalid inputRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 657why, one step back657// Can be defined by user by overriding UsageFuncOrganize the files a bit betterspf13before adoption62fb674
line 658why, one step back658func (c *Command) Usage() error {Help improvementsspf13before adoption2d02c31
line 659why, one step back659 c.mergePersistentFlags()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 660why, one step back660 err := c.UsageFunc()(c)Help improvementsspf13before adoption2d02c31
lines 661–668why, one step back661 return err662}663664// Output the help for the command665// Used when a user calls help [command]666// by the default HelpFunc in the commander667func (c *Command) Help() error {668 c.mergePersistentFlags()Default usage output to stdoutEric Parisbefore adoption6de96b8
line 669why, one step back669 err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)Organize the files a bit betterspf13before adoption62fb674
lines 670–672why, one step back670 return err671}672fix trailing <nil> on help outputspf13before adoption3958385
line 673why, one step back673func (c *Command) UsageString() string {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 674why, one step back674 tmpOutput := c.outputfix trailing <nil> on help outputspf13before adoption3958385
line 675why, one step back675 bb := new(bytes.Buffer)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 676why, one step back676 c.SetOutput(bb)fix trailing <nil> on help outputspf13before adoption3958385
line 677why, one step back677 c.Usage()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 678why, one step back678 c.output = tmpOutputfix trailing <nil> on help outputspf13before adoption3958385
lines 679–681why, one step back679 return bb.String()680}681Code commentaryAhsanul Haquebefore adoptione1e66f7
line 682why, one step back682// CommandPath returns the full path to this command.Organize the files a bit betterspf13before adoption62fb674
lines 683–757why, one step back683func (c *Command) CommandPath() string {684 str := c.Name()685 x := c686 for x.HasParent() {687 str = x.parent.Name() + " " + str688 x = x.parent689 }690 return str691}692693//The full usage for a given command (including parents)694func (c *Command) UseLine() string {695 str := ""696 if c.HasParent() {697 str = c.parent.CommandPath() + " "698 }699 return str + c.Use700}701702// For use in determining which flags have been assigned to which commands703// and which persist704func (c *Command) DebugFlags() {705 c.Println("DebugFlags called on", c.Name())706 var debugflags func(*Command)707708 debugflags = func(x *Command) {709 if x.HasFlags() || x.HasPersistentFlags() {710 c.Println(x.Name())711 }712 if x.HasFlags() {713 x.flags.VisitAll(func(f *flag.Flag) {714 if x.HasPersistentFlags() {715 if x.persistentFlag(f.Name) == nil {716 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")717 } else {718 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")719 }720 } else {721 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")722 }723 })724 }725 if x.HasPersistentFlags() {726 x.pflags.VisitAll(func(f *flag.Flag) {727 if x.HasFlags() {728 if x.flags.Lookup(f.Name) == nil {729 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")730 }731 } else {732 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")733 }734 })735 }736 c.Println(x.flagErrorBuf)737 if x.HasSubCommands() {738 for _, y := range x.commands {739 debugflags(y)740 }741 }742 }743744 debugflags(c)745}746747// Name returns the command's name: the first word in the use line.748func (c *Command) Name() string {749 if c.name != "" {750 return c.name751 }752 name := c.Use753 i := strings.Index(name, " ")754 if i >= 0 {755 name = name[:i]756 }757 return nameReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 758–771why, one step back758}759760// Determine if a given string is an alias of the command.761func (c *Command) HasAlias(s string) bool {762 for _, a := range c.Aliases {763 if a == s {764 return true765 }766 }767 return false768}769770func (c *Command) NameAndAliases() string {771 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 772–775why, one step back772}773774func (c *Command) HasExample() bool {775 return len(c.Example) > 0Organize the files a bit betterspf13before adoption62fb674
lines 776–792why, one step back776}777778// Determine if the command is itself runnable779func (c *Command) Runnable() bool {780 return c.Run != nil781}782783// Determine if the command has children commands784func (c *Command) HasSubCommands() bool {785 return len(c.commands) > 0786}787788// Determine if the command is a child command789func (c *Command) HasParent() bool {790 return c.parent != nil791}792Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 793why, one step back793// 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 794–800why, one step back794func (c *Command) Flags() *flag.FlagSet {795 if c.flags == nil {796 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)797 if c.flagErrorBuf == nil {798 c.flagErrorBuf = new(bytes.Buffer)799 }800 c.flags.SetOutput(c.flagErrorBuf)changed help flag setup to use PersistenFlags so -h will be supportedJoel Scoblebefore adoption83b58a2
line 801why, one step back801 c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name())Organize the files a bit betterspf13before adoption62fb674
lines 802–805why, one step back802 }803 return c.flags804}805Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 806–810why, one step back806// Get the local FlagSet specifically set in the current command807func (c *Command) LocalFlags() *flag.FlagSet {808 c.mergePersistentFlags()809810 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 811–812why, one step back811 c.lflags.VisitAll(func(f *flag.Flag) {812 local.AddFlag(f)Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 813–816why, one step back813 })814 return local815}816new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 817–820why, one step back817// All Flags which were inherited from parents commands818func (c *Command) InheritedFlags() *flag.FlagSet {819 c.mergePersistentFlags()820Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 821–822why, one step back821 inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)822 local := c.LocalFlags()new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 823why, one step back823Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 824why, one step back824 var rmerge func(x *Command)new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 825why, one step back825Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 826–837why, one step back826 rmerge = func(x *Command) {827 if x.HasPersistentFlags() {828 x.PersistentFlags().VisitAll(func(f *flag.Flag) {829 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {830 inherited.AddFlag(f)831 }832 })833 }834 if x.HasParent() {835 rmerge(x.parent)836 }837 }new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 838–842why, one step back838839 if c.HasParent() {840 rmerge(c.parent)841 }842Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 843why, one step back843 return inheritednew InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 844–845why, one step back844}845new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 846–847why, one step back846// All Flags which were not inherited from parent commands847func (c *Command) NonInheritedFlags() *flag.FlagSet {Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 848why, one step back848 return c.LocalFlags()new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 849–850why, one step back849}850Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 851why, one step back851// Get the Persistent FlagSet specifically set in the current commandOrganize the files a bit betterspf13before adoption62fb674
lines 852–872why, one step back852func (c *Command) PersistentFlags() *flag.FlagSet {853 if c.pflags == nil {854 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)855 if c.flagErrorBuf == nil {856 c.flagErrorBuf = new(bytes.Buffer)857 }858 c.pflags.SetOutput(c.flagErrorBuf)859 }860 return c.pflags861}862863// For use in testing864func (c *Command) ResetFlags() {865 c.flagErrorBuf = new(bytes.Buffer)866 c.flagErrorBuf.Reset()867 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)868 c.flags.SetOutput(c.flagErrorBuf)869 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)870 c.pflags.SetOutput(c.flagErrorBuf)871}872Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 873why, one step back873// Does the command contain any flags (local plus persistent from the entire structure)Organize the files a bit betterspf13before adoption62fb674
lines 874–882why, one step back874func (c *Command) HasFlags() bool {875 return c.Flags().HasFlags()876}877878// Does the command contain persistent flags879func (c *Command) HasPersistentFlags() bool {880 return c.PersistentFlags().HasFlags()881}882Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 883–887why, one step back883// Does the command has flags specifically declared locally884func (c *Command) HasLocalFlags() bool {885 return c.LocalFlags().HasFlags()886}887Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 888–891why, one step back888func (c *Command) HasInheritedFlags() bool {889 return c.InheritedFlags().HasFlags()890}891Organize the files a bit betterspf13before adoption62fb674
lines 892–918why, one step back892// Climbs up the command tree looking for matching flag893func (c *Command) Flag(name string) (flag *flag.Flag) {894 flag = c.Flags().Lookup(name)895896 if flag == nil {897 flag = c.persistentFlag(name)898 }899900 return901}902903// recursively find matching persistent flag904func (c *Command) persistentFlag(name string) (flag *flag.Flag) {905 if c.HasPersistentFlags() {906 flag = c.PersistentFlags().Lookup(name)907 }908909 if flag == nil && c.HasParent() {910 flag = c.parent.persistentFlag(name)911 }912 return913}914915// Parses persistent flag tree & local flags916func (c *Command) ParseFlags(args []string) (err error) {917 c.mergePersistentFlags()918 err = c.Flags().Parse(args)Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption2cb625e
line 919why, one step back919 returnOrganize the files a bit betterspf13before adoption62fb674
lines 920–921why, one step back920}921Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 922–925why, one step back922func (c *Command) Parent() *Command {923 return c.parent924}925Organize the files a bit betterspf13before adoption62fb674
lines 926–928why, one step back926func (c *Command) mergePersistentFlags() {927 var rmerge func(x *Command)928Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 929–941why, one step back929 // Save the set of local flags930 if c.lflags == nil {931 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)932 if c.flagErrorBuf == nil {933 c.flagErrorBuf = new(bytes.Buffer)934 }935 c.lflags.SetOutput(c.flagErrorBuf)936 addtolocal := func(f *flag.Flag) {937 c.lflags.AddFlag(f)938 }939 c.Flags().VisitAll(addtolocal)940 c.PersistentFlags().VisitAll(addtolocal)941 }Organize the files a bit betterspf13before adoption62fb674
lines 942–956why, one step back942 rmerge = func(x *Command) {943 if x.HasPersistentFlags() {944 x.PersistentFlags().VisitAll(func(f *flag.Flag) {945 if c.Flags().Lookup(f.Name) == nil {946 c.Flags().AddFlag(f)947 }948 })949 }950 if x.HasParent() {951 rmerge(x.parent)952 }953 }954955 rmerge(c)956}