Refactored code to eliminate need for a commander. Much simpler interface now.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by spf13 · committed by spf13 · parent a2845e7 · Browse files · 3 files·+238 added−238 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+238 added−238 removed
- other:+238 added−238 removed
Provenance
- Commit
79bdde5- Tree
c82c214- Author
spf13 <steve.francia@gmail.com>- Committer
spf13 <steve.francia@gmail.com>- Parent
a2845e7
3 files changed+238 added−238 removed
modified:cobra_test.go+17 added-12 removed
39 unmodified lines40 Long: `an slightly useless command for testing.`,41 Run: timesRunner,42 }43 44-var cmdRoot = &Command{44+var cmdRootNoRun = &Command{45 Use: "cobra-test",46 Short: "The root can run it's own function",47 Long: "The root description for help",48+}49+50+var cmdRootWithRun = &Command{51+ Use: "cobra-test",52+ Short: "The root can run it's own function",53+ Long: "The root description for help",54 Run: func(cmd *Command, args []string) {55 rootcalled = true56 },57 }5 unmodified lines63 func flagInit() {64 cmdEcho.ResetFlags()65 cmdPrint.ResetFlags()66 cmdTimes.ResetFlags()61- cmdRoot.ResetFlags()67+ cmdRootNoRun.ResetFlags()68+ cmdRootWithRun.ResetFlags()69 cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")70 cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")71 cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")72 cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")9 unmodified lines82 cmdPrint.ResetCommands()83 cmdTimes.ResetCommands()84 }85 79-func initialize() *Commander {86+func initialize() *Command {87 tt, tp, te = nil, nil, nil81- var c = NewCommander()82- c.SetName("cobratest")88+ var c = cmdRootNoRun89 flagInit()90 commandInit()91 return c92 }93 88-func initializeWithRootCmd() *Commander {89- cmdRoot.ResetCommands()94+func initializeWithRootCmd() *Command {95+ cmdRootWithRun.ResetCommands()96 tt, tp, te, rootcalled = nil, nil, nil, false91- cmdRoot.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")92- cmdRoot.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag intthree")93- var c = cmdRoot.ToCommander()97 flagInit()98+ cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")99+ cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag intthree")100 commandInit()96- return c101+ return cmdRootWithRun102 }103 104 func TestSingleCommand(t *testing.T) {105 c := initialize()212 unmodified lines318 t.Errorf("Wrong error message displayed, \n %s", buf.String())319 }320 }321 317-func TestCommandToCommander(t *testing.T) {322+func TestRunnableRootCommand(t *testing.T) {323 c := initializeWithRootCmd()324 c.AddCommand(cmdPrint, cmdEcho)325 c.SetArgs([]string(nil))326 c.Execute()21 unmodified linesmodified:command.go+221 added-38 removed
19 unmodified lines20 "bytes"21 "fmt"22 flag "github.com/spf13/pflag"23 "io"24+ "os"25 "strings"26 )27 28 // Command is just that, a command for your application.15 unmodified lines44 pflags *flag.FlagSet45 // Run runs the command.46 // The args are the arguments after the command name.47 Run func(cmd *Command, args []string)47- // Commands is the list of commands supported by this Commander program.48+ // Commands is the list of commands supported by this program.49 commands []*Command50 // Parent Command for this command50- parent *Command51- cmdr *Commander51+ parent *Command52+53 flagErrorBuf *bytes.Buffer54+55+ args []string56+ output *io.Writer // nil means stderr; use out() accessor57+ usageFunc func(*Command) error // Usage can be defined by application58+ usageTemplate string // Can be defined by Application59+ helpTemplate string // Can be defined by Application60+ helpFunc func(*Command, []string) // Help can be defined by application61+ helpCommand *Command // The help command62 }63 55-// Convert a Command into an (initialized) Commander56-func (cmd *Command) ToCommander() (c *Commander) {57- c = NewCommander()58- c.name = cmd.Name()59- c.Use = cmd.Use60- c.Short = cmd.Short61- c.Long = cmd.Long62- c.flags = cmd.flags63- c.pflags = cmd.pflags64- c.Run = cmd.Run65- c.commands = cmd.commands66- c.resetChildrensParents()67- c.flagErrorBuf = cmd.flagErrorBuf68- return64+// os.Args[1:] by default, if desired, can be overridden65+// particularly useful when testing.66+func (c *Command) SetArgs(a []string) {67+ c.args = a68 }69 70+func (c *Command) Out() io.Writer {71+ if c.output != nil {72+ return *c.output73+ }74+75+ if c.HasParent() {76+ return c.parent.Out()77+ } else {78+ return os.Stderr79+ }80+}81+82+// SetOutput sets the destination for usage and error messages.83+// If output is nil, os.Stderr is used.84+func (c *Command) SetOutput(output io.Writer) {85+ c.output = &output86+}87+88+// Usage can be defined by application89+func (c *Command) SetUsageFunc(f func(*Command) error) {90+ c.usageFunc = f91+}92+93+// Can be defined by Application94+func (c *Command) SetUsageTemplate(s string) {95+ c.usageTemplate = s96+}97+98+// Can be defined by Application99+func (c *Command) SetHelpFunc(f func(*Command, []string)) {100+ c.helpFunc = f101+}102+103+func (c *Command) SetHelpCommand(cmd *Command) {104+ c.helpCommand = cmd105+}106+107+// Can be defined by Application108+func (c *Command) SetHelpTemplate(s string) {109+ c.helpTemplate = s110+}111+112+func (c *Command) UsageFunc() (f func(*Command) error) {113+ if c.usageFunc != nil {114+ return c.usageFunc115+ }116+117+ if c.HasParent() {118+ return c.parent.UsageFunc()119+ } else {120+ return func(c *Command) error {121+ err := tmpl(c.Out(), c.UsageTemplate(), c)122+ return err123+ }124+ }125+}126+func (c *Command) HelpFunc() func(*Command, []string) {127+ if c.helpFunc != nil {128+ return c.helpFunc129+ }130+131+ if c.HasParent() {132+ return c.parent.HelpFunc()133+ } else {134+ return func(c *Command, args []string) {135+ if len(args) == 0 {136+ // Help called without any topic, calling on root137+ c.Root().Help()138+ return139+ }140+141+ cmd, _, e := c.Root().Find(args)142+ if cmd == nil || e != nil {143+ c.Printf("Unknown help topic %#q.", args)144+145+ c.Root().Usage()146+ } else {147+ err := cmd.Help()148+ if err != nil {149+ c.Println(err)150+ }151+ }152+ }153+ }154+}155+156+func (c *Command) UsageTemplate() string {157+ if c.usageTemplate != "" {158+ return c.usageTemplate159+ }160+161+ if c.HasParent() {162+ return c.parent.UsageTemplate()163+ } else {164+ return `{{ $cmd := . }}165+Usage: {{if .Runnable}}166+ {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}167+ {{ .CommandPath}} [command]{{end}}168+{{ if .HasSubCommands}}169+Available Commands: {{range .Commands}}{{if .Runnable}}170+ {{.Use | printf "%-15s"}} :: {{.Short}}{{end}}{{end}}171+{{end}}172+{{ if .HasFlags}} Available Flags:173+{{.Flags.FlagUsages}}{{end}}{{if .HasParent}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}174+Additional help topics: {{if gt .Commands 0 }}{{range .Commands}}{{if not .Runnable}} {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}{{if gt .Parent.Commands 1 }}{{range .Parent.Commands}}{{if .Runnable}}{{if not (eq .Name $cmd.Name) }}{{end}}175+ {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}{{end}}176+{{end}}177+Use "{{.Root.Name}} help [command]" for more information about that command.178+`179+ }180+}181+182+func (c *Command) HelpTemplate() string {183+ if c.helpTemplate != "" {184+ return c.helpTemplate185+ }186+187+ if c.HasParent() {188+ return c.parent.HelpTemplate()189+ } else {190+ return `{{.Long | trim}}191+{{if .Runnable}}{{.UsageString}}{{end}}192+`193+ }194+}195+196 // Really only used when casting a command to a commander197 func (c *Command) resetChildrensParents() {198 for _, x := range c.commands {199 x.parent = c7 unmodified lines207 return nil, nil, fmt.Errorf("Called find() on a nil Command")208 }209 210 if len(arrs) == 0 {86- return c.Commander().cmd, arrs, nil211+ return c.Root(), arrs, nil212 }213 214 var innerfind func(*Command, []string) (*Command, []string)215 32 unmodified lines248 249 return findRoot(c)250 }251 127-func (c *Command) Commander() *Commander {128- cmdr := c.Root()129- if cmdr.cmdr != nil {130- return cmdr.cmdr131- } else {132- panic("commander not found")133- }134-}135-136-func (c *Command) Out() io.Writer {137- return c.Commander().out()138-}139-252 // execute the command determined by args and the command tree253 func (c *Command) findAndExecute(args []string) (err error) {254 255 cmd, a, e := c.Find(args)17 unmodified lines273 return nil274 }275 }276 277+// Call execute to use the args (os.Args[1:] by default)278+// and run through the command tree finding appropriate matches279+// for commands and then corresponding flags.280+func (c *Command) Execute() (err error) {281+282+ // Regardless of what command execute is called on, run on Root only283+ if c.HasParent() {284+ return c.Root().Execute()285+ }286+287+ // initialize help as the last point possible to allow for user288+ // overriding289+ c.initHelp()290+291+ var args []string292+293+ if len(c.args) == 0 {294+ args = os.Args[1:]295+ } else {296+ args = c.args297+ }298+299+ if len(args) == 0 {300+ // Only the executable is called and the root is runnable, run it301+ if c.Runnable() {302+ err = c.execute([]string(nil))303+ } else {304+ c.Usage()305+ }306+ } else {307+ err = c.findAndExecute(args)308+ }309+310+ // Now handle the case where the root is runnable and only flags are provided311+ if err != nil && c.Runnable() {312+ e := c.ParseFlags(args)313+ if e != nil {314+ return e315+ } else {316+ argWoFlags := c.Flags().Args()317+ if len(argWoFlags) > 0 {318+ c.Usage()319+ } else {320+ c.Run(c, argWoFlags)321+ err = nil322+ }323+ }324+ }325+326+ if err != nil {327+ c.Println("Error:", err.Error())328+ c.Printf("%v: invalid command %#q\n", c.Root().Name(), os.Args[1:])329+ c.Printf("Run '%v help' for usage\n", c.Root().Name())330+ }331+332+ return333+}334+335+func (c *Command) initHelp() {336+ if c.helpCommand == nil {337+ c.helpCommand = &Command{338+ Use: "help [command]",339+ Short: "Help about any command",340+ Long: `Help provides help for any command in the application.341+ Simply type ` + c.Name() + ` help [path to command] for full details.`,342+ Run: c.HelpFunc(),343+ }344+ }345+ c.AddCommand(c.helpCommand)346+}347+348 // Used for testing349 func (c *Command) ResetCommands() {350 c.commands = nil351 }14 unmodified lines366 }367 368 // Convenience method to Print to the defined output369 func (c *Command) Print(i ...interface{}) {187- c.Commander().PrintOut(i...)370+ fmt.Fprint(c.Out(), i...)371 }372 373 // Convenience method to Println to the defined output374 func (c *Command) Println(i ...interface{}) {8 unmodified lines383 }384 385 // Output the usage for the command386 // Used when a user provides invalid input204-// Can be defined by user by overriding Commander.UsageFunc387+// Can be defined by user by overriding UsageFunc388 func (c *Command) Usage() error {389 c.mergePersistentFlags()207- err := c.Commander().UsageFunc(c)390+ err := c.UsageFunc()(c)391 return err392 }393 394 // Output the help for the command395 // Used when a user calls help [command]396 // by the default HelpFunc in the commander397 func (c *Command) Help() error {398 c.mergePersistentFlags()216- err := tmpl(c.Commander().Out(), c.Commander().HelpTemplate, c)399+ err := tmpl(c.Out(), c.HelpTemplate(), c)400 return err401 }402 403 func (c *Command) UsageString() string {221- tmpOutput := c.Commander().cmdr.output404+ tmpOutput := c.output405 bb := new(bytes.Buffer)223- c.Commander().SetOutput(bb)406+ c.SetOutput(bb)407 c.Usage()225- c.Commander().cmdr.output = tmpOutput408+ c.output = tmpOutput409 return bb.String()410 }411 412 // The full path to this command198 unmodified linesdeleted:commander.go-188 removed
1-// Copyright © 2013 Steve Francia <spf@spf13.com>.2-//3-// Licensed under the Apache License, Version 2.0 (the "License");4-// you may not use this file except in compliance with the License.5-// You may obtain a copy of the License at6-// http://www.apache.org/licenses/LICENSE-2.07-//8-// Unless required by applicable law or agreed to in writing, software9-// distributed under the License is distributed on an "AS IS" BASIS,10-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11-// See the License for the specific language governing permissions and12-// limitations under the License.13-14-// Commands similar to git, go tools and other modern CLI tools15-// inspired by go, go-Commander, gh and subcommand16-17-package cobra18-19-import (20- "fmt"21- "io"22- "os"23-)24-25-// A Commander holds the configuration for the command line tool.26-type Commander struct {27- // A Commander is also a Command for top level and global help & flags28- Command29-30- args []string31- output *io.Writer // nil means stderr; use out() accessor32- UsageFunc func(*Command) error // Usage can be defined by application33- UsageTemplate string // Can be defined by Application34- HelpTemplate string // Can be defined by Application35- HelpFunc func(*Command, []string) // Help can be defined by application36- HelpCommand *Command // The help command37- cmd *Command // The command version of itself38-}39-40-// Provide the user with a new commander.41-func NewCommander() (c *Commander) {42- c = new(Commander)43- c.cmdr = c44- c.UsageFunc = c.defaultUsage45- c.HelpFunc = c.defaultHelp46- c.initTemplates()47- return48-}49-50-func (c *Commander) initHelp() {51- if c.HelpCommand == nil {52- c.HelpCommand = &Command{53- Use: "help [command]",54- Short: "Help about any command",55- Long: `Help provides help for any command in the application.56- Simply type ` + c.Name() + ` help [path to command] for full details.`,57- Run: c.HelpFunc,58- }59- }60- c.AddCommand(c.HelpCommand)61-}62-63-// Name for commander, should match application name64-func (c *Commander) SetName(name string) {65- c.name = name66-}67-68-// os.Args[1:] by default, if desired, can be overridden69-// particularly useful when testing.70-func (c *Commander) SetArgs(a []string) {71- c.args = a72-}73-74-// Call execute to use the args (os.Args[1:] by default)75-// and run through the command tree finding appropriate matches76-// for commands and then corresponding flags.77-func (c *Commander) Execute() (err error) {78- // initialize help as the last point possible to allow for user79- // overriding80- c.initHelp()81- var args []string82-83- if len(c.args) == 0 {84- args = os.Args[1:]85- } else {86- args = c.args87- }88-89- if len(args) == 0 {90- // Only the executable is called and the root is runnable, run it91- if c.Runnable() {92- err = c.execute([]string(nil))93- } else {94- c.Usage()95- }96- } else {97- err = c.findAndExecute(args)98- }99-100- // Now handle the case where the root is runnable and only flags are provided101- if err != nil && c.Runnable() {102- e := c.ParseFlags(args)103- if e != nil {104- return e105- } else {106- argWoFlags := c.Flags().Args()107- if len(argWoFlags) > 0 {108- c.Usage()109- } else {110- c.Run(c.cmd, argWoFlags)111- err = nil112- }113- }114- }115-116- if err != nil {117- c.Println("Error:", err.Error())118- c.Printf("%v: invalid command %#q\n", c.Root().Name(), os.Args[1:])119- c.Printf("Run '%v help' for usage\n", c.Root().Name())120- }121-122- return123-}124-125-func (c *Commander) out() io.Writer {126- if c.output == nil {127- return os.Stderr128- }129- return *c.output130-}131-132-func (cmdr *Commander) defaultUsage(c *Command) error {133- err := tmpl(cmdr.out(), cmdr.UsageTemplate, c)134- return err135-}136-137-func (cmdr *Commander) defaultHelp(c *Command, args []string) {138- if len(args) == 0 {139- // Help called without any topic, calling on root140- c.Root().Help()141- return142- }143-144- cmd, _, e := c.Root().Find(args)145- if cmd == nil || e != nil {146- cmdr.Printf("Unknown help topic %#q.", args)147-148- c.Root().Usage()149- } else {150- err := cmd.Help()151- if err != nil {152- c.Println(err)153- }154- }155-}156-157-//Print to out158-func (c *Commander) PrintOut(i ...interface{}) {159- fmt.Fprint(c.out(), i...)160-}161-162-// SetOutput sets the destination for usage and error messages.163-// If output is nil, os.Stderr is used.164-func (c *Commander) SetOutput(output io.Writer) {165- c.output = &output166-}167-168-func (c *Commander) initTemplates() {169- c.UsageTemplate = `{{ $cmd := . }}170-Usage: {{if .Runnable}}171- {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}172- {{ .CommandPath}} [command]{{end}}173-{{ if .HasSubCommands}}174-Available Commands: {{range .Commands}}{{if .Runnable}}175- {{.Use | printf "%-15s"}} :: {{.Short}}{{end}}{{end}}176-{{end}}177-{{ if .HasFlags}} Available Flags:178-{{.Flags.FlagUsages}}{{end}}{{if .HasParent}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}179-Additional help topics: {{if gt .Commands 0 }}{{range .Commands}}{{if not .Runnable}} {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}{{if gt .Parent.Commands 1 }}{{range .Parent.Commands}}{{if .Runnable}}{{if not (eq .Name $cmd.Name) }}{{end}}180- {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}{{end}}181-{{end}}182-Use "{{.Commander.Name}} help [command]" for more information about that command.183-`184-185- c.HelpTemplate = `{{.Long | trim}}186-{{if .Runnable}}{{.UsageString}}{{end}}187-`188-}