command.go
This file
Path
command.go
865 lines · 21.2 KiB · Go
Last changed by
New "example" section of commandsEric Parisbefore adoptionbf480fe
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
lines 48–51why, one step back48 pflags *flag.FlagSet49 // Run runs the command.50 // The args are the arguments after the command name.51 Run func(cmd *Command, args []string)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 52why, one step back52 // Commands is the list of commands supported by this program.Organize the files a bit betterspf13before adoption62fb674
lines 53–54why, one step back53 commands []*Command54 // Parent Command for this commandRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 55why, one step back55 parent *CommandMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 56–58why, one step back56 // max lengths of commands' string lengths for use in padding57 commandsMaxUseLen int58 commandsMaxCommandPathLen inthelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 59why, one step back59 commandsMaxNameLen intRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 60why, one step back60Organize the files a bit betterspf13before adoption62fb674
line 61why, one step back61 flagErrorBuf *bytes.BufferSubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 62why, one step back62 cmdErrorBuf *bytes.BufferRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 63why, one step back63Code commentaryAhsanul Haquebefore adoptione1e66f7
line 64why, one step back64 args []string // actual args parsed from flagsDocumentation updatespf13before adoption59bd285
line 65why, one step back65 output *io.Writer // nil means stderr; use Out() method insteadRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 66–70why, one step back66 usageFunc func(*Command) error // Usage can be defined by application67 usageTemplate string // Can be defined by Application68 helpTemplate string // Can be defined by Application69 helpFunc func(*Command, []string) // Help can be defined by application70 helpCommand *Command // The help commandAdding support for --helpspf13before adoption07be814
line 71why, one step back71 helpFlagVal boolOrganize the files a bit betterspf13before adoption62fb674
lines 72–73why, one step back72}73Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 74–77why, one step back74// os.Args[1:] by default, if desired, can be overridden75// particularly useful when testing.76func (c *Command) SetArgs(a []string) {77 c.args = aAdd ability to cast a command to a commanderspf13before adoption74ce44d
lines 78–79why, one step back78}79Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 80–146why, one step back80func (c *Command) Out() io.Writer {81 if c.output != nil {82 return *c.output83 }8485 if c.HasParent() {86 return c.parent.Out()87 } else {88 return os.Stderr89 }90}9192// SetOutput sets the destination for usage and error messages.93// If output is nil, os.Stderr is used.94func (c *Command) SetOutput(output io.Writer) {95 c.output = &output96}9798// Usage can be defined by application99func (c *Command) SetUsageFunc(f func(*Command) error) {100 c.usageFunc = f101}102103// Can be defined by Application104func (c *Command) SetUsageTemplate(s string) {105 c.usageTemplate = s106}107108// Can be defined by Application109func (c *Command) SetHelpFunc(f func(*Command, []string)) {110 c.helpFunc = f111}112113func (c *Command) SetHelpCommand(cmd *Command) {114 c.helpCommand = cmd115}116117// Can be defined by Application118func (c *Command) SetHelpTemplate(s string) {119 c.helpTemplate = s120}121122func (c *Command) UsageFunc() (f func(*Command) error) {123 if c.usageFunc != nil {124 return c.usageFunc125 }126127 if c.HasParent() {128 return c.parent.UsageFunc()129 } else {130 return func(c *Command) error {131 err := tmpl(c.Out(), c.UsageTemplate(), c)132 return err133 }134 }135}136func (c *Command) HelpFunc() func(*Command, []string) {137 if c.helpFunc != nil {138 return c.helpFunc139 }140141 if c.HasParent() {142 return c.parent.HelpFunc()143 } else {144 return func(c *Command, args []string) {145 if len(args) == 0 {146 // Help called without any topic, calling on rootPrint Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 147why, one step back147 c.Root().Help()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 148–165why, one step back148 return149 }150151 cmd, _, e := c.Root().Find(args)152 if cmd == nil || e != nil {153 c.Printf("Unknown help topic %#q.", args)154155 c.Root().Usage()156 } else {157 err := cmd.Help()158 if err != nil {159 c.Println(err)160 }161 }162 }163 }164}165Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 166–177why, one step back166var minUsagePadding int = 25167168func (c *Command) UsagePadding() int {169 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {170 return minUsagePadding171 } else {172 return c.parent.commandsMaxUseLen173 }174}175176var minCommandPathPadding int = 11177Code commentaryAhsanul Haquebefore adoptione1e66f7
line 178why, one step back178//Merge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 179–186why, one step back179func (c *Command) CommandPathPadding() int {180 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {181 return minCommandPathPadding182 } else {183 return c.parent.commandsMaxCommandPathLen184 }185}186help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 187–196why, one step back187var minNamePadding int = 11188189func (c *Command) NamePadding() int {190 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {191 return minNamePadding192 } else {193 return c.parent.commandsMaxNameLen194 }195}196Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 197–207why, one step back197func (c *Command) UsageTemplate() string {198 if c.usageTemplate != "" {199 return c.usageTemplate200 }201202 if c.HasParent() {203 return c.parent.UsageTemplate()204 } else {205 return `{{ $cmd := . }}206Usage: {{if .Runnable}}207 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 208–210why, one step back208 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}209210Aliases:New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 211–215why, one step back211 {{.NameAndAliases}}212{{end}}{{if .HasExample}}213Examples:214{{ .Example }}215{{end}}{{ if .HasSubCommands}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 216why, one step back216Available Commands: {{range .Commands}}{{if .Runnable}}help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 217why, one step back217 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 218why, one step back218{{end}}Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 219–222why, one step back219{{ if .HasLocalFlags}}Flags:220{{.LocalFlags.FlagUsages}}{{end}}221{{ if .HasAnyPersistentFlags}}Global Flags:222{{.AllPersistentFlags.FlagUsages}}{{end}}{{if .HasParent}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}Remove "::" from output. Fixed #4spf13before adoption1a6c5d1
lines 223–224why, one step back223Additional 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}}224 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{end}}Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 225why, one step back225{{end}}{{ if .HasSubCommands }}Minor English correctionKartik Singhalbefore adoptionc36f627
line 226why, one step back226Use "{{.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 227why, one step back227{{end}}`Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 228–239why, one step back228 }229}230231func (c *Command) HelpTemplate() string {232 if c.helpTemplate != "" {233 return c.helpTemplate234 }235236 if c.HasParent() {237 return c.parent.HelpTemplate()238 } else {239 return `{{.Long | trim}}Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 240why, one step back240{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 241–244why, one step back241`242 }243}244Add ability to cast a command to a commanderspf13before adoption74ce44d
lines 245–251why, one step back245// Really only used when casting a command to a commander246func (c *Command) resetChildrensParents() {247 for _, x := range c.commands {248 x.parent = c249 }250}251Support for flags before commandsspf13before adoption10a8494
lines 252–290why, one step back252func stripFlags(args []string) []string {253 if len(args) < 1 {254 return args255 }256257 commands := []string{}258259 inQuote := false260 for _, y := range args {261 if !inQuote {262 switch {263 case strings.HasPrefix(y, "\""):264 inQuote = true265 case strings.Contains(y, "=\""):266 inQuote = true267 case !strings.HasPrefix(y, "-"):268 commands = append(commands, y)269 }270 }271272 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {273 inQuote = false274 }275 }276277 return commands278}279280func argsMinusX(args []string, x string) []string {281 newargs := []string{}282283 for _, y := range args {284 if x != y {285 newargs = append(newargs, y)286 }287 }288 return newargs289}290Organize the files a bit betterspf13before adoption62fb674
line 291why, one step back291// find the target command given the args and command treeAdd support for help commandspf13before adoptionfb2146e
line 292why, one step back292// Meant to be run on the highest node. Only searches down.Finding command based on args cleaned upspf13before adoption55ff474
line 293why, one step back293func (c *Command) Find(arrs []string) (*Command, []string, error) {Organize the files a bit betterspf13before adoption62fb674
lines 294–297why, one step back294 if c == nil {295 return nil, nil, fmt.Errorf("Called find() on a nil Command")296 }297Finding command based on args cleaned upspf13before adoption55ff474
line 298why, one step back298 if len(arrs) == 0 {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 299why, one step back299 return c.Root(), arrs, nilFinding command based on args cleaned upspf13before adoption55ff474
lines 300–305why, one step back300 }301302 var innerfind func(*Command, []string) (*Command, []string)303304 innerfind = func(c *Command, args []string) (*Command, []string) {305 if len(args) > 0 && c.HasSubCommands() {Support for flags before commandsspf13before adoption10a8494
lines 306–307why, one step back306 argsWOflags := stripFlags(args)307 if len(argsWOflags) > 0 {adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
line 308why, one step back308 matches := make([]*Command, 0)Support for flags before commandsspf13before adoption10a8494
line 309why, one step back309 for _, cmd := range c.commands {Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 310–311why, one step back310 if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match311 return innerfind(cmd, argsMinusX(args, argsWOflags[0]))Making prefix matching opt in.spf13before adoptionb1e90a7
line 312why, one step back312 } else if EnablePrefixMatching {adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
lines 313–320why, one step back313 if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match314 matches = append(matches, cmd)315 }316 for _, x := range cmd.Aliases {317 if strings.HasPrefix(x, argsWOflags[0]) {318 matches = append(matches, cmd)319 }320 }Support for flags before commandsspf13before adoption10a8494
line 321why, one step back321 }adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
lines 322–326why, one step back322 }323324 // only accept a single prefix match - multiple matches would be ambiguous325 if len(matches) == 1 {326 return innerfind(matches[0], argsMinusX(args, argsWOflags[0]))Finding command based on args cleaned upspf13before adoption55ff474
line 327why, one step back327 }Organize the files a bit betterspf13before adoption62fb674
lines 328–329why, one step back328 }329 }Finding command based on args cleaned upspf13before adoption55ff474
lines 330–331why, one step back330331 return c, argsOrganize the files a bit betterspf13before adoption62fb674
line 332why, one step back332 }Finding command based on args cleaned upspf13before adoption55ff474
lines 333–335why, one step back333334 commandFound, a := innerfind(c, arrs)335Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 336–338why, one step back336 // if commander returned and the first argument (if it exists) doesn't337 // match the command name, return nil & error338 if commandFound.Name() == c.Name() && len(arrs[0]) > 0 && commandFound.Name() != arrs[0] {fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 339why, one step back339 return nil, a, fmt.Errorf("unknown command %q\nRun 'help' for usage.\n", a[0])Organize the files a bit betterspf13before adoption62fb674
lines 340–341why, one step back340 }341Finding command based on args cleaned upspf13before adoption55ff474
line 342why, one step back342 return commandFound, a, nilOrganize the files a bit betterspf13before adoption62fb674
lines 343–344why, one step back343}344Add support for help commandspf13before adoptionfb2146e
line 345why, one step back345func (c *Command) Root() *Command {Organize the files a bit betterspf13before adoption62fb674
lines 346–354why, one step back346 var findRoot func(*Command) *Command347348 findRoot = func(x *Command) *Command {349 if x.HasParent() {350 return findRoot(x.parent)351 } else {352 return x353 }354 }Add support for help commandspf13before adoptionfb2146e
lines 355–358why, one step back355356 return findRoot(c)357}358Organize the files a bit betterspf13before adoption62fb674
line 359why, one step back359// execute the command determined by args and the command treefixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 360why, one step back360func (c *Command) findAndExecute(args []string) (err error) {Organize the files a bit betterspf13before adoption62fb674
line 361why, one step back361fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 362–369why, one step back362 cmd, a, e := c.Find(args)363 if e != nil {364 return e365 }366 return cmd.execute(a)367}368369func (c *Command) execute(a []string) (err error) {Organize the files a bit betterspf13before adoption62fb674
lines 370–373why, one step back370 if c == nil {371 return fmt.Errorf("Called Execute() on a nil Command")372 }373fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 374why, one step back374 err = c.ParseFlags(a)Fixing error messaging when upstream flag library is inconsistent.spf13before adoptionfae1335
line 375why, one step back375fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 376why, one step back376 if err != nil {Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 377why, one step back377 // 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 378–380why, one step back378 r := c.Root()379 if r.cmdErrorBuf == nil {380 r.cmdErrorBuf = new(bytes.Buffer)Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
lines 381–382why, one step back381 }382 // 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 383–385why, one step back383 // since Out() returns root output, you also need to revert that on root384 out := r.Out()385 r.SetOutput(r.cmdErrorBuf)Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 386why, one step back386 c.Usage()Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
line 387why, one step back387 r.SetOutput(out)fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 388–389why, one step back388 return err389 } else {In execute(), check if command is Runnable()Anthony Fokbefore adoption4745f1f
lines 390–392why, one step back390 // If help is called, regardless of other flags, we print that.391 // Print help also if c.Run is nil.392 if c.helpFlagVal || !c.Runnable() {Adding support for --helpspf13before adoption07be814
lines 393–396why, one step back393 c.Help()394 return nil395 }396Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 397why, one step back397 c.preRun()fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
lines 398–400why, one step back398 argWoFlags := c.Flags().Args()399 c.Run(c, argWoFlags)400 return nilOrganize the files a bit betterspf13before adoption62fb674
lines 401–403why, one step back401 }402}403Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 404why, one step back404func (c *Command) preRun() {Adding "OnInitialize()" method instead of directly setting a property. Now can have multiple initializers.spf13before adoption864687a
lines 405–407why, one step back405 for _, x := range initializers {406 x()407 }Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 408–409why, one step back408}409Support for flags before commandsspf13before adoption10a8494
lines 410–421why, one step back410func (c *Command) errorMsgFromParse() string {411 s := c.flagErrorBuf.String()412413 x := strings.Split(s, "\n")414415 if len(x) > 0 {416 return x[0]417 } else {418 return ""419 }420}421Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 422–448why, one step back422// Call execute to use the args (os.Args[1:] by default)423// and run through the command tree finding appropriate matches424// for commands and then corresponding flags.425func (c *Command) Execute() (err error) {426427 // Regardless of what command execute is called on, run on Root only428 if c.HasParent() {429 return c.Root().Execute()430 }431432 // initialize help as the last point possible to allow for user433 // overriding434 c.initHelp()435436 var args []string437438 if len(c.args) == 0 {439 args = os.Args[1:]440 } else {441 args = c.args442 }443444 if len(args) == 0 {445 // Only the executable is called and the root is runnable, run it446 if c.Runnable() {447 err = c.execute([]string(nil))448 } else {Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 449why, one step back449 c.Help()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 450–456why, one step back450 }451 } else {452 err = c.findAndExecute(args)453 }454455 // Now handle the case where the root is runnable and only flags are provided456 if err != nil && c.Runnable() {Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 457–458why, one step back457 // This is pretty much a custom version of the *Command.execute method458 // 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 459–460why, one step back459 e := c.ParseFlags(args)460 if e != nil {Cobra behavior is now more consistent. Invalid flags cause Usage to be printed.spf13before adoption71bb1df
line 461why, one step back461 // Flags parsing had an error.Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 462why, one step back462 // If an error happens here, we have to report it to the userSupport for flags before commandsspf13before adoption10a8494
line 463why, one step back463 c.Println(c.errorMsgFromParse())Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
lines 464–469why, one step back464 // If an error happens search also for subcommand info about that465 if c.cmdErrorBuf != nil && c.cmdErrorBuf.Len() > 0 {466 c.Println(c.cmdErrorBuf.String())467 } else {468 c.Usage()469 }Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 470–471why, one step back470 return e471 } else {Adding support for --helpspf13before adoption07be814
lines 472–477why, one step back472 // If help is called, regardless of other flags, we print that473 if c.helpFlagVal {474 c.Help()475 return nil476 }477Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 478–479why, one step back478 argWoFlags := c.Flags().Args()479 if len(argWoFlags) > 0 {Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 480–482why, one step back480 // If there are arguments (not flags) one of the earlier481 // cases should have caught it.. It means invalid usage482 // print the usageRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 483–484why, one step back483 c.Usage()484 } else {Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
lines 485–486why, one step back485 // Only flags left... Call root.Run486 c.preRun()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 487–503why, one step back487 c.Run(c, argWoFlags)488 err = nil489 }490 }491 }492493 if err != nil {494 c.Println("Error:", err.Error())495 c.Printf("%v: invalid command %#q\n", c.Root().Name(), os.Args[1:])496 c.Printf("Run '%v help' for usage\n", c.Root().Name())497 }498499 return500}501502func (c *Command) initHelp() {503 if c.helpCommand == nil {Merge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
lines 504–507why, one step back504 if !c.HasSubCommands() {505 return506 }507Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 508–518why, one step back508 c.helpCommand = &Command{509 Use: "help [command]",510 Short: "Help about any command",511 Long: `Help provides help for any command in the application.512 Simply type ` + c.Name() + ` help [path to command] for full details.`,513 Run: c.HelpFunc(),514 }515 }516 c.AddCommand(c.helpCommand)517}518Organize the files a bit betterspf13before adoption62fb674
lines 519–521why, one step back519// Used for testing520func (c *Command) ResetCommands() {521 c.commands = nilMerge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 522why, one step back522 c.helpCommand = nilSubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
lines 523–524why, one step back523 c.cmdErrorBuf = new(bytes.Buffer)524 c.cmdErrorBuf.Reset()Organize the files a bit betterspf13before adoption62fb674
lines 525–526why, one step back525}526Code commentaryAhsanul Haquebefore adoptione1e66f7
line 527why, one step back527//Commands returns a slice of child commands.Organize the files a bit betterspf13before adoption62fb674
lines 528–531why, one step back528func (c *Command) Commands() []*Command {529 return c.commands530}531Code commentaryAhsanul Haquebefore adoptione1e66f7
line 532why, one step back532// AddCommand adds one or more commands to this parent command.Organize the files a bit betterspf13before adoption62fb674
lines 533–538why, one step back533func (c *Command) AddCommand(cmds ...*Command) {534 for i, x := range cmds {535 if cmds[i] == c {536 panic("Command can't be a child of itself")537 }538 cmds[i].parent = cMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 539–546why, one step back539 // update max lengths540 usageLen := len(x.Use)541 if usageLen > c.commandsMaxUseLen {542 c.commandsMaxUseLen = usageLen543 }544 commandPathLen := len(x.CommandPath())545 if commandPathLen > c.commandsMaxCommandPathLen {546 c.commandsMaxCommandPathLen = commandPathLenhelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 547–550why, one step back547 }548 nameLen := len(x.Name())549 if nameLen > c.commandsMaxNameLen {550 c.commandsMaxNameLen = nameLenMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
line 551why, one step back551 }Organize the files a bit betterspf13before adoption62fb674
lines 552–557why, one step back552 c.commands = append(c.commands, x)553 }554}555556// Convenience method to Print to the defined output557func (c *Command) Print(i ...interface{}) {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 558why, one step back558 fmt.Fprint(c.Out(), i...)Organize the files a bit betterspf13before adoption62fb674
lines 559–574why, one step back559}560561// Convenience method to Println to the defined output562func (c *Command) Println(i ...interface{}) {563 str := fmt.Sprintln(i...)564 c.Print(str)565}566567// Convenience method to Printf to the defined output568func (c *Command) Printf(format string, i ...interface{}) {569 str := fmt.Sprintf(format, i...)570 c.Print(str)571}572573// Output the usage for the command574// Used when a user provides invalid inputRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 575why, one step back575// Can be defined by user by overriding UsageFuncOrganize the files a bit betterspf13before adoption62fb674
line 576why, one step back576func (c *Command) Usage() error {Help improvementsspf13before adoption2d02c31
line 577why, one step back577 c.mergePersistentFlags()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 578why, one step back578 err := c.UsageFunc()(c)Help improvementsspf13before adoption2d02c31
lines 579–586why, one step back579 return err580}581582// Output the help for the command583// Used when a user calls help [command]584// by the default HelpFunc in the commander585func (c *Command) Help() error {586 c.mergePersistentFlags()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 587why, one step back587 err := tmpl(c.Out(), c.HelpTemplate(), c)Organize the files a bit betterspf13before adoption62fb674
lines 588–590why, one step back588 return err589}590fix trailing <nil> on help outputspf13before adoption3958385
line 591why, one step back591func (c *Command) UsageString() string {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 592why, one step back592 tmpOutput := c.outputfix trailing <nil> on help outputspf13before adoption3958385
line 593why, one step back593 bb := new(bytes.Buffer)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 594why, one step back594 c.SetOutput(bb)fix trailing <nil> on help outputspf13before adoption3958385
line 595why, one step back595 c.Usage()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 596why, one step back596 c.output = tmpOutputfix trailing <nil> on help outputspf13before adoption3958385
lines 597–599why, one step back597 return bb.String()598}599Code commentaryAhsanul Haquebefore adoptione1e66f7
line 600why, one step back600// CommandPath returns the full path to this command.Organize the files a bit betterspf13before adoption62fb674
lines 601–675why, one step back601func (c *Command) CommandPath() string {602 str := c.Name()603 x := c604 for x.HasParent() {605 str = x.parent.Name() + " " + str606 x = x.parent607 }608 return str609}610611//The full usage for a given command (including parents)612func (c *Command) UseLine() string {613 str := ""614 if c.HasParent() {615 str = c.parent.CommandPath() + " "616 }617 return str + c.Use618}619620// For use in determining which flags have been assigned to which commands621// and which persist622func (c *Command) DebugFlags() {623 c.Println("DebugFlags called on", c.Name())624 var debugflags func(*Command)625626 debugflags = func(x *Command) {627 if x.HasFlags() || x.HasPersistentFlags() {628 c.Println(x.Name())629 }630 if x.HasFlags() {631 x.flags.VisitAll(func(f *flag.Flag) {632 if x.HasPersistentFlags() {633 if x.persistentFlag(f.Name) == nil {634 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")635 } else {636 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")637 }638 } else {639 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")640 }641 })642 }643 if x.HasPersistentFlags() {644 x.pflags.VisitAll(func(f *flag.Flag) {645 if x.HasFlags() {646 if x.flags.Lookup(f.Name) == nil {647 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")648 }649 } else {650 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")651 }652 })653 }654 c.Println(x.flagErrorBuf)655 if x.HasSubCommands() {656 for _, y := range x.commands {657 debugflags(y)658 }659 }660 }661662 debugflags(c)663}664665// Name returns the command's name: the first word in the use line.666func (c *Command) Name() string {667 if c.name != "" {668 return c.name669 }670 name := c.Use671 i := strings.Index(name, " ")672 if i >= 0 {673 name = name[:i]674 }675 return nameReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 676–689why, one step back676}677678// Determine if a given string is an alias of the command.679func (c *Command) HasAlias(s string) bool {680 for _, a := range c.Aliases {681 if a == s {682 return true683 }684 }685 return false686}687688func (c *Command) NameAndAliases() string {689 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 690–693why, one step back690}691692func (c *Command) HasExample() bool {693 return len(c.Example) > 0Organize the files a bit betterspf13before adoption62fb674
lines 694–710why, one step back694}695696// Determine if the command is itself runnable697func (c *Command) Runnable() bool {698 return c.Run != nil699}700701// Determine if the command has children commands702func (c *Command) HasSubCommands() bool {703 return len(c.commands) > 0704}705706// Determine if the command is a child command707func (c *Command) HasParent() bool {708 return c.parent != nil709}710Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 711why, one step back711// 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 712–718why, one step back712func (c *Command) Flags() *flag.FlagSet {713 if c.flags == nil {714 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)715 if c.flagErrorBuf == nil {716 c.flagErrorBuf = new(bytes.Buffer)717 }718 c.flags.SetOutput(c.flagErrorBuf)changed help flag setup to use PersistenFlags so -h will be supportedJoel Scoblebefore adoption83b58a2
line 719why, one step back719 c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name())Organize the files a bit betterspf13before adoption62fb674
lines 720–723why, one step back720 }721 return c.flags722}723Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 724–740why, one step back724// Get the local FlagSet specifically set in the current command725func (c *Command) LocalFlags() *flag.FlagSet {726 c.mergePersistentFlags()727728 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)729 allPersistent := c.AllPersistentFlags()730731 c.Flags().VisitAll(func(f *flag.Flag) {732 if allPersistent.Lookup(f.Name) == nil {733 local.AddFlag(f)734 }735 })736737 return local738}739740// Get the Persistent FlagSet specifically set in the current commandOrganize the files a bit betterspf13before adoption62fb674
lines 741–751why, one step back741func (c *Command) PersistentFlags() *flag.FlagSet {742 if c.pflags == nil {743 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)744 if c.flagErrorBuf == nil {745 c.flagErrorBuf = new(bytes.Buffer)746 }747 c.pflags.SetOutput(c.flagErrorBuf)748 }749 return c.pflags750}751Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 752–774why, one step back752// Get the Persistent FlagSet traversing the Command hierarchy753func (c *Command) AllPersistentFlags() *flag.FlagSet {754 allPersistent := flag.NewFlagSet(c.Name(), flag.ContinueOnError)755756 var visit func(x *Command)757 visit = func(x *Command) {758 if x.HasPersistentFlags() {759 x.PersistentFlags().VisitAll(func(f *flag.Flag) {760 if allPersistent.Lookup(f.Name) == nil {761 allPersistent.AddFlag(f)762 }763 })764 }765 if x.HasParent() {766 visit(x.parent)767 }768 }769770 visit(c)771772 return allPersistent773}774Organize the files a bit betterspf13before adoption62fb674
lines 775–784why, one step back775// For use in testing776func (c *Command) ResetFlags() {777 c.flagErrorBuf = new(bytes.Buffer)778 c.flagErrorBuf.Reset()779 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)780 c.flags.SetOutput(c.flagErrorBuf)781 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)782 c.pflags.SetOutput(c.flagErrorBuf)783}784Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 785why, one step back785// Does the command contain any flags (local plus persistent from the entire structure)Organize the files a bit betterspf13before adoption62fb674
lines 786–794why, one step back786func (c *Command) HasFlags() bool {787 return c.Flags().HasFlags()788}789790// Does the command contain persistent flags791func (c *Command) HasPersistentFlags() bool {792 return c.PersistentFlags().HasFlags()793}794Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 795–804why, one step back795// Does the command hierarchy contain persistent flags796func (c *Command) HasAnyPersistentFlags() bool {797 return c.AllPersistentFlags().HasFlags()798}799800// Does the command has flags specifically declared locally801func (c *Command) HasLocalFlags() bool {802 return c.LocalFlags().HasFlags()803}804Organize the files a bit betterspf13before adoption62fb674
lines 805–831why, one step back805// Climbs up the command tree looking for matching flag806func (c *Command) Flag(name string) (flag *flag.Flag) {807 flag = c.Flags().Lookup(name)808809 if flag == nil {810 flag = c.persistentFlag(name)811 }812813 return814}815816// recursively find matching persistent flag817func (c *Command) persistentFlag(name string) (flag *flag.Flag) {818 if c.HasPersistentFlags() {819 flag = c.PersistentFlags().Lookup(name)820 }821822 if flag == nil && c.HasParent() {823 flag = c.parent.persistentFlag(name)824 }825 return826}827828// Parses persistent flag tree & local flags829func (c *Command) ParseFlags(args []string) (err error) {830 c.mergePersistentFlags()831 err = c.Flags().Parse(args)Fixing error messaging when upstream flag library is inconsistent.spf13before adoptionfae1335
line 832why, one step back832Proper handling of flag error messages. Fixing test that wasn't passing.spf13before adoption68f3c66
lines 833–837why, one step back833 // The upstream library adds spaces to the error834 // response regardless of success.835 // Handling it here until fixing upstream836 if len(strings.TrimSpace(c.flagErrorBuf.String())) > 1 {837 return fmt.Errorf("%s", c.flagErrorBuf.String())Organize the files a bit betterspf13before adoption62fb674
line 838why, one step back838 }Fixing error messaging when upstream flag library is inconsistent.spf13before adoptionfae1335
lines 839–840why, one step back839840 //always return nil because upstream library is inconsistent & we always check the error buffer anywayOrganize the files a bit betterspf13before adoption62fb674
lines 841–843why, one step back841 return nil842}843Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 844–847why, one step back844func (c *Command) Parent() *Command {845 return c.parent846}847Organize the files a bit betterspf13before adoption62fb674
lines 848–865why, one step back848func (c *Command) mergePersistentFlags() {849 var rmerge func(x *Command)850851 rmerge = func(x *Command) {852 if x.HasPersistentFlags() {853 x.PersistentFlags().VisitAll(func(f *flag.Flag) {854 if c.Flags().Lookup(f.Name) == nil {855 c.Flags().AddFlag(f)856 }857 })858 }859 if x.HasParent() {860 rmerge(x.parent)861 }862 }863864 rmerge(c)865}