Skip to content
Myr

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

3 files+238 added−238 removed

modified:cobra_test.go+17 added-12 removed
39 unmodified lines
40 Long: `an slightly useless command for testing.`,41 Run: timesRunner,42}4344var cmdRoot = &Command{44var cmdRootNoRun = &Command{45 Use: "cobra-test",46 Short: "The root can run it's own function",47 Long: "The root description for help",48}4950var 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 lines
63func 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 lines
82 cmdPrint.ResetCommands()83 cmdTimes.ResetCommands()84}8579func initialize() *Commander {86func 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}9388func initializeWithRootCmd() *Commander {89 cmdRoot.ResetCommands()94func 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}103104func TestSingleCommand(t *testing.T) {105 c := initialize()
212 unmodified lines
318 t.Errorf("Wrong error message displayed, \n %s", buf.String())319 }320}321317func TestCommandToCommander(t *testing.T) {322func TestRunnableRootCommand(t *testing.T) {323 c := initializeWithRootCmd()324 c.AddCommand(cmdPrint, cmdEcho)325 c.SetArgs([]string(nil))326 c.Execute()
21 unmodified lines
modified:command.go+221 added-38 removed
19 unmodified lines
20 "bytes"21 "fmt"22 flag "github.com/spf13/pflag"23 "io"24 "os"25 "strings"26)2728// Command is just that, a command for your application.
15 unmodified lines
44 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 *Command5253 flagErrorBuf *bytes.Buffer5455 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}6355// Convert a Command into an (initialized) Commander56func (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.66func (c *Command) SetArgs(a []string) {67 c.args = a68}6970func (c *Command) Out() io.Writer {71 if c.output != nil {72 return *c.output73 }7475 if c.HasParent() {76 return c.parent.Out()77 } else {78 return os.Stderr79 }80}8182// SetOutput sets the destination for usage and error messages.83// If output is nil, os.Stderr is used.84func (c *Command) SetOutput(output io.Writer) {85 c.output = &output86}8788// Usage can be defined by application89func (c *Command) SetUsageFunc(f func(*Command) error) {90 c.usageFunc = f91}9293// Can be defined by Application94func (c *Command) SetUsageTemplate(s string) {95 c.usageTemplate = s96}9798// Can be defined by Application99func (c *Command) SetHelpFunc(f func(*Command, []string)) {100 c.helpFunc = f101}102103func (c *Command) SetHelpCommand(cmd *Command) {104 c.helpCommand = cmd105}106107// Can be defined by Application108func (c *Command) SetHelpTemplate(s string) {109 c.helpTemplate = s110}111112func (c *Command) UsageFunc() (f func(*Command) error) {113 if c.usageFunc != nil {114 return c.usageFunc115 }116117 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}126func (c *Command) HelpFunc() func(*Command, []string) {127 if c.helpFunc != nil {128 return c.helpFunc129 }130131 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 }140141 cmd, _, e := c.Root().Find(args)142 if cmd == nil || e != nil {143 c.Printf("Unknown help topic %#q.", args)144145 c.Root().Usage()146 } else {147 err := cmd.Help()148 if err != nil {149 c.Println(err)150 }151 }152 }153 }154}155156func (c *Command) UsageTemplate() string {157 if c.usageTemplate != "" {158 return c.usageTemplate159 }160161 if c.HasParent() {162 return c.parent.UsageTemplate()163 } else {164 return `{{ $cmd := . }}165Usage: {{if .Runnable}}166 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}167 {{ .CommandPath}} [command]{{end}}168{{ if .HasSubCommands}}169Available 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) }}174Additional 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}}177Use "{{.Root.Name}} help [command]" for more information about that command.178`179 }180}181182func (c *Command) HelpTemplate() string {183 if c.helpTemplate != "" {184 return c.helpTemplate185 }186187 if c.HasParent() {188 return c.parent.HelpTemplate()189 } else {190 return `{{.Long | trim}}191{{if .Runnable}}{{.UsageString}}{{end}}192`193 }194}195196// Really only used when casting a command to a commander197func (c *Command) resetChildrensParents() {198 for _, x := range c.commands {199 x.parent = c
7 unmodified lines
207 return nil, nil, fmt.Errorf("Called find() on a nil Command")208 }209210 if len(arrs) == 0 {86 return c.Commander().cmd, arrs, nil211 return c.Root(), arrs, nil212 }213214 var innerfind func(*Command, []string) (*Command, []string)215
32 unmodified lines
248249 return findRoot(c)250}251127func (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}135136func (c *Command) Out() io.Writer {137 return c.Commander().out()138}139252// execute the command determined by args and the command tree253func (c *Command) findAndExecute(args []string) (err error) {254255 cmd, a, e := c.Find(args)
17 unmodified lines
273 return nil274 }275}276277// 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.280func (c *Command) Execute() (err error) {281282 // Regardless of what command execute is called on, run on Root only283 if c.HasParent() {284 return c.Root().Execute()285 }286287 // initialize help as the last point possible to allow for user288 // overriding289 c.initHelp()290291 var args []string292293 if len(c.args) == 0 {294 args = os.Args[1:]295 } else {296 args = c.args297 }298299 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 }309310 // 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 }325326 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 }331332 return333}334335func (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}347348// Used for testing349func (c *Command) ResetCommands() {350 c.commands = nil351}
14 unmodified lines
366}367368// Convenience method to Print to the defined output369func (c *Command) Print(i ...interface{}) {187 c.Commander().PrintOut(i...)370 fmt.Fprint(c.Out(), i...)371}372373// Convenience method to Println to the defined output374func (c *Command) Println(i ...interface{}) {
8 unmodified lines
383}384385// 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 UsageFunc388func (c *Command) Usage() error {389 c.mergePersistentFlags()207 err := c.Commander().UsageFunc(c)390 err := c.UsageFunc()(c)391 return err392}393394// Output the help for the command395// Used when a user calls help [command]396// by the default HelpFunc in the commander397func (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}402403func (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}411412// The full path to this command
198 unmodified lines
deleted: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.1314// Commands similar to git, go tools and other modern CLI tools15// inspired by go, go-Commander, gh and subcommand1617package cobra1819import (20 "fmt"21 "io"22 "os"23)2425// A Commander holds the configuration for the command line tool.26type Commander struct {27 // A Commander is also a Command for top level and global help & flags28 Command2930 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}3940// Provide the user with a new commander.41func NewCommander() (c *Commander) {42 c = new(Commander)43 c.cmdr = c44 c.UsageFunc = c.defaultUsage45 c.HelpFunc = c.defaultHelp46 c.initTemplates()47 return48}4950func (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}6263// Name for commander, should match application name64func (c *Commander) SetName(name string) {65 c.name = name66}6768// os.Args[1:] by default, if desired, can be overridden69// particularly useful when testing.70func (c *Commander) SetArgs(a []string) {71 c.args = a72}7374// 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.77func (c *Commander) Execute() (err error) {78 // initialize help as the last point possible to allow for user79 // overriding80 c.initHelp()81 var args []string8283 if len(c.args) == 0 {84 args = os.Args[1:]85 } else {86 args = c.args87 }8889 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 }99100 // 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 }115116 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 }121122 return123}124125func (c *Commander) out() io.Writer {126 if c.output == nil {127 return os.Stderr128 }129 return *c.output130}131132func (cmdr *Commander) defaultUsage(c *Command) error {133 err := tmpl(cmdr.out(), cmdr.UsageTemplate, c)134 return err135}136137func (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 }143144 cmd, _, e := c.Root().Find(args)145 if cmd == nil || e != nil {146 cmdr.Printf("Unknown help topic %#q.", args)147148 c.Root().Usage()149 } else {150 err := cmd.Help()151 if err != nil {152 c.Println(err)153 }154 }155}156157//Print to out158func (c *Commander) PrintOut(i ...interface{}) {159 fmt.Fprint(c.out(), i...)160}161162// SetOutput sets the destination for usage and error messages.163// If output is nil, os.Stderr is used.164func (c *Commander) SetOutput(output io.Writer) {165 c.output = &output166}167168func (c *Commander) initTemplates() {169 c.UsageTemplate = `{{ $cmd := . }}170Usage: {{if .Runnable}}171 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}172 {{ .CommandPath}} [command]{{end}}173{{ if .HasSubCommands}}174Available 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) }}179Additional 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}}182Use "{{.Commander.Name}} help [command]" for more information about that command.183`184185 c.HelpTemplate = `{{.Long | trim}}186{{if .Runnable}}{{.UsageString}}{{end}}187`188}