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 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–222why, one step back221 {{.NameAndAliases}}222{{end}}{{if .HasExample}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 223why, one step back223New "example" section of commandsEric Parisbefore adoptionbf480fe
lines 224–226why, one step back224Examples:225{{ .Example }}226{{end}}{{ if .HasSubCommands}}fix missing newline in help output introduced in bf480fe628Jason Moironbefore adoptione784a59
line 227why, one step back227Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 228why, one step back228Available Commands: {{range .Commands}}{{if .Runnable}}help displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
line 229why, one step back229 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 230why, one step back230{{end}}Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 231–232why, one step back231{{ if .HasLocalFlags}}Flags:232{{.LocalFlags.FlagUsages}}{{end}}Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 233–234why, one step back233{{ 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 back235Additional 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 back237{{end}}{{ if .HasSubCommands }}Minor English correctionKartik Singhalbefore adoptionc36f627
line 238why, one step back238Use "{{.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 back239{{end}}`Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 240–250why, one step back240 }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 back251 return `{{with or .Long .Short }}{{. | trim}}{{end}}Print Long description when printing Help, fixes #20Sam Ghodsbefore adoptioncdafa9f
line 252why, one step back252{{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 back253`254 }255}256Add ability to cast a command to a commanderspf13before adoption74ce44d
lines 257–263why, one step back257// Really only used when casting a command to a commander258func (c *Command) resetChildrensParents() {259 for _, x := range c.commands {260 x.parent = c261 }262}263Fix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 264–274why, one step back264// 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 back275 result := false276 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 back281 return result282}283284func stripFlags(args []string, c *Command) []string {Support for flags before commandsspf13before adoption10a8494
lines 285–287why, one step back285 if len(args) < 1 {286 return args287 }Merge pull request #70 from brendandburns/masterBjørn Erik Pedersenbefore adoption6264dc6
line 288why, one step back288 c.mergePersistentFlags()Support for flags before commandsspf13before adoption10a8494
lines 289–292why, one step back289290 commands := []string{}291292 inQuote := falseFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
line 293why, one step back293 inFlag := falseSupport for flags before commandsspf13before adoption10a8494
lines 294–300why, one step back294 for _, y := range args {295 if !inQuote {296 switch {297 case strings.HasPrefix(y, "\""):298 inQuote = true299 case strings.Contains(y, "=\""):300 inQuote = trueFix stripFlags to be more intelligent about what it parses.Brendan Burnsbefore adoptionbbdea35
lines 301–307why, one step back301 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 = falseMerge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1
lines 308–309why, one step back308 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 back310 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 back312 inFlag = falseSupport for flags before commandsspf13before adoption10a8494
lines 313–334why, one step back313 }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}334Organize the files a bit betterspf13before adoption62fb674
line 335why, one step back335// find the target command given the args and command treeAdd support for help commandspf13before adoptionfb2146e
line 336why, one step back336// Meant to be run on the highest node. Only searches down.Finding command based on args cleaned upspf13before adoption55ff474
line 337why, one step back337func (c *Command) Find(arrs []string) (*Command, []string, error) {Organize the files a bit betterspf13before adoption62fb674
lines 338–341why, one step back338 if c == nil {339 return nil, nil, fmt.Errorf("Called find() on a nil Command")340 }341Finding command based on args cleaned upspf13before adoption55ff474
line 342why, one step back342 if len(arrs) == 0 {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 343why, one step back343 return c.Root(), arrs, nilFinding command based on args cleaned upspf13before adoption55ff474
lines 344–349why, one step back344 }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 back350 argsWOflags := stripFlags(args, c)Support for flags before commandsspf13before adoption10a8494
line 351why, one step back351 if len(argsWOflags) > 0 {adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
line 352why, one step back352 matches := make([]*Command, 0)Support for flags before commandsspf13before adoption10a8494
line 353why, one step back353 for _, cmd := range c.commands {Replace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 354–355why, one step back354 if cmd.Name() == argsWOflags[0] || cmd.HasAlias(argsWOflags[0]) { // exact name or alias match355 return innerfind(cmd, argsMinusX(args, argsWOflags[0]))Making prefix matching opt in.spf13before adoptionb1e90a7
line 356why, one step back356 } else if EnablePrefixMatching {adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
lines 357–364why, one step back357 if strings.HasPrefix(cmd.Name(), argsWOflags[0]) { // prefix match358 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 back365 }adding support for prefix matching against aliases & namesspf13before adoptionc2c23ac
lines 366–370why, one step back366 }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 back371 }Organize the files a bit betterspf13before adoption62fb674
lines 372–373why, one step back372 }373 }Finding command based on args cleaned upspf13before adoption55ff474
lines 374–375why, one step back374375 return c, argsOrganize the files a bit betterspf13before adoption62fb674
line 376why, one step back376 }Finding command based on args cleaned upspf13before adoption55ff474
lines 377–379why, one step back377378 commandFound, a := innerfind(c, arrs)379Merge pull request #84 from eparis/subcommand-invalid-flagEric Parisbefore adoption29e27b1
lines 380–381why, one step back380 // If we matched on the root, but we asked for a subcommand, return an error381 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 back382 return nil, a, fmt.Errorf("unknown command %q", a[0])Organize the files a bit betterspf13before adoption62fb674
lines 383–384why, one step back383 }384Finding command based on args cleaned upspf13before adoption55ff474
line 385why, one step back385 return commandFound, a, nilOrganize the files a bit betterspf13before adoption62fb674
lines 386–387why, one step back386}387Add support for help commandspf13before adoptionfb2146e
line 388why, one step back388func (c *Command) Root() *Command {Organize the files a bit betterspf13before adoption62fb674
lines 389–397why, one step back389 var findRoot func(*Command) *Command390391 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 back398399 return findRoot(c)400}401fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 402why, one step back402func (c *Command) execute(a []string) (err error) {Organize the files a bit betterspf13before adoption62fb674
lines 403–406why, one step back403 if c == nil {404 return fmt.Errorf("Called Execute() on a nil Command")405 }406fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 407why, one step back407 err = c.ParseFlags(a)Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 408–411why, one step back408 if err == flag.ErrHelp {409 c.Help()410 return nil411 }fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 412why, one step back412 if err != nil {Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption033c83b
line 413why, one step back413 // 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 414–416why, one step back414 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 back417 }418 // 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 419–421why, one step back419 // since Out() returns root output, you also need to revert that on root420 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 back422 c.Usage()Subcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
line 423why, one step back423 r.SetOutput(out)fixed spf13/cobra#1 spf13/hugo#88spf13before adoptiona2845e7
line 424why, one step back424 return errSlight formatting change, to make next commit more readableEric Parisbefore adoptionb9e25fa
lines 425–429why, one step back425 }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 back430 return nilOrganize the files a bit betterspf13before adoption62fb674
line 431why, one step back431 }Slight formatting change, to make next commit more readableEric Parisbefore adoptionb9e25fa
lines 432–436why, one step back432433 c.preRun()434 argWoFlags := c.Flags().Args()435 c.Run(c, argWoFlags)436 return nilOrganize the files a bit betterspf13before adoption62fb674
lines 437–438why, one step back437}438Add support for an InitializeConfig method as defined on Cobra by the userspf13before adoption7cebca3
line 439why, one step back439func (c *Command) preRun() {Adding "OnInitialize()" method instead of directly setting a property. Now can have multiple initializers.spf13before adoption864687a
lines 440–442why, one step back440 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 back443}444Support for flags before commandsspf13before adoption10a8494
lines 445–456why, one step back445func (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}456Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 457–478why, one step back457// 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 }478Remove specail casing in Execute()Eric Parisbefore adoption794a362
lines 479–481why, one step back479 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 back482 }483484 if err != nil {Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 485–486why, one step back485 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 back487Remove some wonky error handling, as upstream seems correct now.Brendan Burnsbefore adoption9e7273d
lines 488–489why, one step back488 } 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 back490 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 back491 }Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 492–498why, one step back492 }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 back499 if !c.HasSubCommands() {500 return501 }502Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
lines 503–513why, one step back503 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}513Organize the files a bit betterspf13before adoption62fb674
lines 514–516why, one step back514// Used for testing515func (c *Command) ResetCommands() {516 c.commands = nilMerge pull request #32 from smarterclayton/hide_subcommand_help_for_root_only_commandSteve Franciabefore adoptionb825817
line 517why, one step back517 c.helpCommand = nilSubcommands flag parsing errors print subcommand usage and not root's command usageMaciej Szulikbefore adoption6e6b6a9
lines 518–519why, one step back518 c.cmdErrorBuf = new(bytes.Buffer)519 c.cmdErrorBuf.Reset()Organize the files a bit betterspf13before adoption62fb674
lines 520–521why, one step back520}521Code commentaryAhsanul Haquebefore adoptione1e66f7
line 522why, one step back522//Commands returns a slice of child commands.Organize the files a bit betterspf13before adoption62fb674
lines 523–526why, one step back523func (c *Command) Commands() []*Command {524 return c.commands525}526Code commentaryAhsanul Haquebefore adoptione1e66f7
line 527why, one step back527// AddCommand adds one or more commands to this parent command.Organize the files a bit betterspf13before adoption62fb674
lines 528–533why, one step back528func (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 = cMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
lines 534–541why, one step back534 // update max lengths535 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 = commandPathLenhelp displays command names instead of usage in Available CommandsMasahiro Sanobefore adoptiona16cb24
lines 542–545why, one step back542 }543 nameLen := len(x.Name())544 if nameLen > c.commandsMaxNameLen {545 c.commandsMaxNameLen = nameLenMerge pull request #8 from awilliams/masterSteve Franciabefore adoption1e1ff9e
line 546why, one step back546 }Organize the files a bit betterspf13before adoption62fb674
lines 547–550why, one step back547 c.commands = append(c.commands, x)548 }549}550Add Command's RemoveCommand methodÉtienne Vallette d'Osiabefore adoptionf479c92
lines 551–584why, one step back551// 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}584Organize the files a bit betterspf13before adoption62fb674
lines 585–586why, one step back585// Convenience method to Print to the defined output586func (c *Command) Print(i ...interface{}) {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 587why, one step back587 fmt.Fprint(c.Out(), i...)Organize the files a bit betterspf13before adoption62fb674
lines 588–603why, one step back588}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 inputRefactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 604why, one step back604// Can be defined by user by overriding UsageFuncOrganize the files a bit betterspf13before adoption62fb674
line 605why, one step back605func (c *Command) Usage() error {Help improvementsspf13before adoption2d02c31
line 606why, one step back606 c.mergePersistentFlags()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 607why, one step back607 err := c.UsageFunc()(c)Help improvementsspf13before adoption2d02c31
lines 608–615why, one step back608 return err609}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 back616 err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)Organize the files a bit betterspf13before adoption62fb674
lines 617–619why, one step back617 return err618}619fix trailing <nil> on help outputspf13before adoption3958385
line 620why, one step back620func (c *Command) UsageString() string {Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 621why, one step back621 tmpOutput := c.outputfix trailing <nil> on help outputspf13before adoption3958385
line 622why, one step back622 bb := new(bytes.Buffer)Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 623why, one step back623 c.SetOutput(bb)fix trailing <nil> on help outputspf13before adoption3958385
line 624why, one step back624 c.Usage()Refactored code to eliminate need for a commander. Much simpler interface now.spf13before adoption79bdde5
line 625why, one step back625 c.output = tmpOutputfix trailing <nil> on help outputspf13before adoption3958385
lines 626–628why, one step back626 return bb.String()627}628Code commentaryAhsanul Haquebefore adoptione1e66f7
line 629why, one step back629// CommandPath returns the full path to this command.Organize the files a bit betterspf13before adoption62fb674
lines 630–704why, one step back630func (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 nameReplace prefix matching with aliasesSam Ghodsbefore adoption8816572
lines 705–718why, one step back705}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 back719}720721func (c *Command) HasExample() bool {722 return len(c.Example) > 0Organize the files a bit betterspf13before adoption62fb674
lines 723–739why, one step back723}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}739Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 740why, one step back740// 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 back741func (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 back748 c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name())Organize the files a bit betterspf13before adoption62fb674
lines 749–752why, one step back749 }750 return c.flags751}752Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 753–757why, one step back753// Get the local FlagSet specifically set in the current command754func (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 back758 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 back760 })761 return local762}763new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 764–767why, one step back764// All Flags which were inherited from parents commands765func (c *Command) InheritedFlags() *flag.FlagSet {766 c.mergePersistentFlags()767Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 768–769why, one step back768 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 back770Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 771why, one step back771 var rmerge func(x *Command)new InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
line 772why, one step back772Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 773–784why, one step back773 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 back785786 if c.HasParent() {787 rmerge(c.parent)788 }789Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 790why, one step back790 return inheritednew InheritedFlags() command to tell all flags which persisted from a parentEric Parisbefore adoptionb96dd75
lines 791–792why, one step back791}792new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 793–794why, one step back793// All Flags which were not inherited from parent commands794func (c *Command) NonInheritedFlags() *flag.FlagSet {Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
line 795why, one step back795 return c.LocalFlags()new NonInheritedFlags() which give all flags which were not persisted from a parent commandEric Parisbefore adoptionf8e1ec5
lines 796–797why, one step back796}797Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 798why, one step back798// Get the Persistent FlagSet specifically set in the current commandOrganize the files a bit betterspf13before adoption62fb674
lines 799–819why, one step back799func (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}819Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
line 820why, one step back820// 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 back821func (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}829Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 830–834why, one step back830// Does the command has flags specifically declared locally831func (c *Command) HasLocalFlags() bool {832 return c.LocalFlags().HasFlags()833}834Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 835–838why, one step back835func (c *Command) HasInheritedFlags() bool {836 return c.InheritedFlags().HasFlags()837}838Organize the files a bit betterspf13before adoption62fb674
lines 839–865why, one step back839// Climbs up the command tree looking for matching flag840func (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 back866 returnOrganize the files a bit betterspf13before adoption62fb674
lines 867–868why, one step back867}868Restores the ability to fetch local only flagsfabianofranzbefore adoptionefb045e
lines 869–872why, one step back869func (c *Command) Parent() *Command {870 return c.parent871}872Organize the files a bit betterspf13before adoption62fb674
lines 873–875why, one step back873func (c *Command) mergePersistentFlags() {874 var rmerge func(x *Command)875Explicitly support local flags overwriting persistent/inherited flagsJeff Lowdermilkbefore adoption5c91469
lines 876–888why, one step back876 // Save the set of local flags877 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 back889 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}