Skip to content
Myr

Organize the files a bit better

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by spf13 · committed by spf13 · parent 88b9d2e · Browse files · 3 files+487 added−445 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+487 added−445 removed

  • other:+487 added−445 removed

3 files+487 added−445 removed

modified:cobra.go-445 removed
15 unmodified lines
1617package cobra1819import (20 "bytes"21 "fmt"22 flag "github.com/spf13/pflag"20 "io"24 "os"21 "reflect"22 "strconv"23 "strings"24 "text/template"25)2631var _ = flag.ContinueOnError3233// A Commander holds the configuration for the command line tool.34type Commander struct {35 // A Commander is also a Command for top level and global help & flags36 Command3738 args []string39 output *io.Writer // nil means stderr; use out() accessor40 UsageFunc func(*Command) error // Usage can be defined by application41 UsageTemplate string // Can be defined by Application42 HelpTemplate string // Can be defined by Application43}4445// Provide the user with a new commander.46func NewCommander() (c *Commander) {47 c = new(Commander)48 c.cmdr = c49 c.UsageFunc = c.defaultUsage50 c.initTemplates()51 return52}5354// Name for commander, should match application name55func (c *Commander) SetName(name string) {56 c.name = name57}5859// os.Args[1:] by default, if desired, can be overridden60// particularly useful when testing.61func (c *Commander) SetArgs(a []string) {62 c.args = a63}6465// Call execute to use the args (os.Args[1:] by default)66// and run through the command tree finding appropriate matches67// for commands and then corresponding flags.68func (c *Commander) Execute() (err error) {69 if len(c.args) == 0 {70 err = c.execute(os.Args[1:])71 } else {72 err = c.execute(c.args)73 }74 return75}7677func (c *Commander) out() io.Writer {78 if c.output == nil {79 return os.Stderr80 }81 return *c.output82}8384func (cmdr *Commander) defaultUsage(c *Command) error {85 err := tmpl(cmdr.out(), cmdr.UsageTemplate, c)86 if err != nil {87 c.Println(err)88 }89 return err90}9192//Print to out93func (c *Commander) PrintOut(i ...interface{}) {94 fmt.Fprint(c.out(), i...)95}9697// SetOutput sets the destination for usage and error messages.98// If output is nil, os.Stderr is used.99func (c *Commander) SetOutput(output io.Writer) {100 c.output = &output101 //*c.output = output102}103104func (c *Commander) initTemplates() {105 c.UsageTemplate = `{{ $cmd := . }}106Usage: {{if .Runnable}}107 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}108 {{ .CommandPath}} [command]{{end}}109{{ if .HasSubCommands}}110Available Commands: {{range .Commands}}{{if .Runnable}}111 {{.Use | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}112{{end}}113{{ if .HasFlags}} Available Flags:114{{.Flags.FlagUsages}}{{end}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}115Additional help topics: {{if gt .Commands 0 }}{{range .Commands}}{{if not .Runnable}}116 {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}{{if gt .Parent.Commands 1 }}{{range .Parent.Commands}}{{if .Runnable}}{{if not (eq .Name $cmd.Name) }}{{end}}117 {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}118119{{end}}120Use "{{.Commander.Name}} help [command]" for more information about that command.121`122123 c.HelpTemplate = `{{if .Runnable}}Usage: {{.ProgramName}} {{.UsageLine}}124125{{end}}{{.Long | trim}}126`127}128129// Command is just that, a command for your application.130// eg. 'go run' ... 'run' is the command. Cobra requires131// you to define the usage and description as part of your command132// definition to ensure usability.133type Command struct {134 // Name is the command name, usually the executable's name.135 name string136 // The one-line usage message.137 Use string138 // The short description shown in the 'help' output.139 Short string140 // The long message shown in the 'help <this-command>' output.141 Long string142 // Set of flags specific to this command.143 flags *flag.FlagSet144 // Set of flags children commands will inherit145 pflags *flag.FlagSet146 // Run runs the command.147 // The args are the arguments after the command name.148 Run func(cmd *Command, args []string)149 // Commands is the list of commands supported by this Commander program.150 commands []*Command151 // Parent Command for this command152 parent *Command153 cmdr *Commander154 flagErrorBuf *bytes.Buffer155}156157// find the target command given the args and command tree158func (c *Command) Find(args []string) (cmd *Command, a []string, err error) {159 if c == nil {160 return nil, nil, fmt.Errorf("Called find() on a nil Command")161 }162163 validSubCommand := false164 if len(args) > 1 && c.HasSubCommands() {165 for _, cmd := range c.commands {166 if cmd.Name() == args[0] {167 validSubCommand = true168 return cmd.Find(args[1:])169 }170 }171 }172 if !validSubCommand && c.Runnable() {173 return c, args, nil174 }175176 return nil, nil, nil177}178179func (c *Command) Commander() *Commander {180 var findRoot func(*Command) *Command181182 findRoot = func(x *Command) *Command {183 if x.HasParent() {184 return findRoot(x.parent)185 } else {186 return x187 }188 }189 cmdr := findRoot(c)190 if cmdr.cmdr != nil {191 return cmdr.cmdr192 } else {193 panic("commander not found")194 }195}196197func (c *Command) Out() io.Writer {198 return c.Commander().out()199}200201// execute the command determined by args and the command tree202func (c *Command) execute(args []string) (err error) {203 err = fmt.Errorf("unknown subcommand %q\nRun 'help' for usage.\n", args[0])204205 if c == nil {206 return fmt.Errorf("Called Execute() on a nil Command")207 }208209 cmd, a, e := c.Find(args)210 if e == nil {211 err = cmd.ParseFlags(a)212 if err != nil {213 cmd.Usage()214 return err215 } else {216 argWoFlags := cmd.Flags().Args()217 cmd.Run(cmd, argWoFlags)218 return nil219 }220 }221 err = e222 return err223}224225// Used for testing226func (c *Command) ResetCommands() {227 c.commands = nil228}229230func (c *Command) Commands() []*Command {231 return c.commands232}233234// Add one or many commands as children of this235func (c *Command) AddCommand(cmds ...*Command) {236 for i, x := range cmds {237 if cmds[i] == c {238 panic("Command can't be a child of itself")239 }240 cmds[i].parent = c241 c.commands = append(c.commands, x)242 }243}244245// Convenience method to Print to the defined output246func (c *Command) Print(i ...interface{}) {247 c.Commander().PrintOut(i...)248}249250// Convenience method to Println to the defined output251func (c *Command) Println(i ...interface{}) {252 str := fmt.Sprintln(i...)253 c.Print(str)254}255256// Convenience method to Printf to the defined output257func (c *Command) Printf(format string, i ...interface{}) {258 str := fmt.Sprintf(format, i...)259 c.Print(str)260}261262// Output the usage for the command263// Used when a user provides invalid input264// Can be defined by user by overriding Commander.UsageFunc265func (c *Command) Usage() error {266 err := c.Commander().UsageFunc(c)267 if err != nil {268 fmt.Println(err)269 }270 return err271}272273// The full path to this command274func (c *Command) CommandPath() string {275 str := c.Name()276 x := c277 for x.HasParent() {278 str = x.parent.Name() + " " + str279 x = x.parent280 }281 return str282}283284//The full usage for a given command (including parents)285func (c *Command) UseLine() string {286 str := ""287 if c.HasParent() {288 str = c.parent.CommandPath() + " "289 }290 return str + c.Use291}292293// For use in determining which flags have been assigned to which commands294// and which persist295func (c *Command) DebugFlags() {296 c.Println("DebugFlags called on", c.Name())297 var debugflags func(*Command)298299 debugflags = func(x *Command) {300 if x.HasFlags() || x.HasPersistentFlags() {301 c.Println(x.Name())302 }303 if x.HasFlags() {304 x.flags.VisitAll(func(f *flag.Flag) {305 if x.HasPersistentFlags() {306 if x.persistentFlag(f.Name) == nil {307 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")308 } else {309 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")310 }311 } else {312 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")313 }314 })315 }316 if x.HasPersistentFlags() {317 x.pflags.VisitAll(func(f *flag.Flag) {318 if x.HasFlags() {319 if x.flags.Lookup(f.Name) == nil {320 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")321 }322 } else {323 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")324 }325 })326 }327 c.Println(x.flagErrorBuf)328 if x.HasSubCommands() {329 for _, y := range x.commands {330 debugflags(y)331 }332 }333 }334335 debugflags(c)336}337338// Name returns the command's name: the first word in the use line.339func (c *Command) Name() string {340 if c.name != "" {341 return c.name342 }343 name := c.Use344 i := strings.Index(name, " ")345 if i >= 0 {346 name = name[:i]347 }348 return name349}350351// Determine if the command is itself runnable352func (c *Command) Runnable() bool {353 return c.Run != nil354}355356// Determine if the command has children commands357func (c *Command) HasSubCommands() bool {358 return len(c.commands) > 0359}360361// Determine if the command is a child command362func (c *Command) HasParent() bool {363 return c.parent != nil364}365366// Get the Commands FlagSet367func (c *Command) Flags() *flag.FlagSet {368 if c.flags == nil {369 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)370 if c.flagErrorBuf == nil {371 c.flagErrorBuf = new(bytes.Buffer)372 }373 c.flags.SetOutput(c.flagErrorBuf)374 }375 return c.flags376}377378// Get the Commands Persistent FlagSet379func (c *Command) PersistentFlags() *flag.FlagSet {380 if c.pflags == nil {381 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)382 if c.flagErrorBuf == nil {383 c.flagErrorBuf = new(bytes.Buffer)384 }385 c.pflags.SetOutput(c.flagErrorBuf)386 }387 return c.pflags388}389390// For use in testing391func (c *Command) ResetFlags() {392 c.flagErrorBuf = new(bytes.Buffer)393 c.flagErrorBuf.Reset()394 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)395 c.flags.SetOutput(c.flagErrorBuf)396 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)397 c.pflags.SetOutput(c.flagErrorBuf)398}399400// Does the command contain flags (local not persistent)401func (c *Command) HasFlags() bool {402 return c.Flags().HasFlags()403}404405// Does the command contain persistent flags406func (c *Command) HasPersistentFlags() bool {407 return c.PersistentFlags().HasFlags()408}409410// Climbs up the command tree looking for matching flag411func (c *Command) Flag(name string) (flag *flag.Flag) {412 flag = c.Flags().Lookup(name)413414 if flag == nil {415 flag = c.persistentFlag(name)416 }417418 return419}420421// recursively find matching persistent flag422func (c *Command) persistentFlag(name string) (flag *flag.Flag) {423 if c.HasPersistentFlags() {424 flag = c.PersistentFlags().Lookup(name)425 }426427 if flag == nil && c.HasParent() {428 flag = c.parent.persistentFlag(name)429 }430 return431}432433// Parses persistent flag tree & local flags434func (c *Command) ParseFlags(args []string) (err error) {435 c.mergePersistentFlags()436437 err = c.Flags().Parse(args)438 if err != nil {439 return err440 }441 if c.flagErrorBuf != nil {442 //fmt.Println(c.flagErrorBuf.String())443 return nil444 //return fmt.Errorf("%s", c.flagErrorBuf.String())445 }446 return nil447}448449func (c *Command) mergePersistentFlags() {450 var rmerge func(x *Command)451452 rmerge = func(x *Command) {453 if x.HasPersistentFlags() {454 x.PersistentFlags().VisitAll(func(f *flag.Flag) {455 if c.Flags().Lookup(f.Name) == nil {456 c.Flags().AddFlag(f)457 }458 })459 }460 if x.HasParent() {461 rmerge(x.parent)462 }463 }464465 rmerge(c)466}467468func (c *Command) Parent() *Command {469 return c.parent470}47127func Gt(a interface{}, b interface{}) bool {28 var left, right int6429 av := reflect.ValueOf(a)30
49 unmodified lines
added:command.go+368 added
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 "bytes"21 "fmt"22 flag "github.com/spf13/pflag"23 "io"24 "strings"25)2627// Command is just that, a command for your application.28// eg. 'go run' ... 'run' is the command. Cobra requires29// you to define the usage and description as part of your command30// definition to ensure usability.31type Command struct {32 // Name is the command name, usually the executable's name.33 name string34 // The one-line usage message.35 Use string36 // The short description shown in the 'help' output.37 Short string38 // The long message shown in the 'help <this-command>' output.39 Long string40 // Set of flags specific to this command.41 flags *flag.FlagSet42 // Set of flags children commands will inherit43 pflags *flag.FlagSet44 // Run runs the command.45 // The args are the arguments after the command name.46 Run func(cmd *Command, args []string)47 // Commands is the list of commands supported by this Commander program.48 commands []*Command49 // Parent Command for this command50 parent *Command51 cmdr *Commander52 flagErrorBuf *bytes.Buffer53}5455// find the target command given the args and command tree56func (c *Command) Find(args []string) (cmd *Command, a []string, err error) {57 if c == nil {58 return nil, nil, fmt.Errorf("Called find() on a nil Command")59 }6061 validSubCommand := false62 if len(args) > 1 && c.HasSubCommands() {63 for _, cmd := range c.commands {64 if cmd.Name() == args[0] {65 validSubCommand = true66 return cmd.Find(args[1:])67 }68 }69 }70 if !validSubCommand && c.Runnable() {71 return c, args, nil72 }7374 return nil, nil, nil75}7677func (c *Command) Commander() *Commander {78 var findRoot func(*Command) *Command7980 findRoot = func(x *Command) *Command {81 if x.HasParent() {82 return findRoot(x.parent)83 } else {84 return x85 }86 }87 cmdr := findRoot(c)88 if cmdr.cmdr != nil {89 return cmdr.cmdr90 } else {91 panic("commander not found")92 }93}9495func (c *Command) Out() io.Writer {96 return c.Commander().out()97}9899// execute the command determined by args and the command tree100func (c *Command) execute(args []string) (err error) {101 err = fmt.Errorf("unknown subcommand %q\nRun 'help' for usage.\n", args[0])102103 if c == nil {104 return fmt.Errorf("Called Execute() on a nil Command")105 }106107 cmd, a, e := c.Find(args)108 if e == nil {109 err = cmd.ParseFlags(a)110 if err != nil {111 cmd.Usage()112 return err113 } else {114 argWoFlags := cmd.Flags().Args()115 cmd.Run(cmd, argWoFlags)116 return nil117 }118 }119 err = e120 return err121}122123// Used for testing124func (c *Command) ResetCommands() {125 c.commands = nil126}127128func (c *Command) Commands() []*Command {129 return c.commands130}131132// Add one or many commands as children of this133func (c *Command) AddCommand(cmds ...*Command) {134 for i, x := range cmds {135 if cmds[i] == c {136 panic("Command can't be a child of itself")137 }138 cmds[i].parent = c139 c.commands = append(c.commands, x)140 }141}142143// Convenience method to Print to the defined output144func (c *Command) Print(i ...interface{}) {145 c.Commander().PrintOut(i...)146}147148// Convenience method to Println to the defined output149func (c *Command) Println(i ...interface{}) {150 str := fmt.Sprintln(i...)151 c.Print(str)152}153154// Convenience method to Printf to the defined output155func (c *Command) Printf(format string, i ...interface{}) {156 str := fmt.Sprintf(format, i...)157 c.Print(str)158}159160// Output the usage for the command161// Used when a user provides invalid input162// Can be defined by user by overriding Commander.UsageFunc163func (c *Command) Usage() error {164 err := c.Commander().UsageFunc(c)165 if err != nil {166 fmt.Println(err)167 }168 return err169}170171// The full path to this command172func (c *Command) CommandPath() string {173 str := c.Name()174 x := c175 for x.HasParent() {176 str = x.parent.Name() + " " + str177 x = x.parent178 }179 return str180}181182//The full usage for a given command (including parents)183func (c *Command) UseLine() string {184 str := ""185 if c.HasParent() {186 str = c.parent.CommandPath() + " "187 }188 return str + c.Use189}190191// For use in determining which flags have been assigned to which commands192// and which persist193func (c *Command) DebugFlags() {194 c.Println("DebugFlags called on", c.Name())195 var debugflags func(*Command)196197 debugflags = func(x *Command) {198 if x.HasFlags() || x.HasPersistentFlags() {199 c.Println(x.Name())200 }201 if x.HasFlags() {202 x.flags.VisitAll(func(f *flag.Flag) {203 if x.HasPersistentFlags() {204 if x.persistentFlag(f.Name) == nil {205 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")206 } else {207 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")208 }209 } else {210 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")211 }212 })213 }214 if x.HasPersistentFlags() {215 x.pflags.VisitAll(func(f *flag.Flag) {216 if x.HasFlags() {217 if x.flags.Lookup(f.Name) == nil {218 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")219 }220 } else {221 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")222 }223 })224 }225 c.Println(x.flagErrorBuf)226 if x.HasSubCommands() {227 for _, y := range x.commands {228 debugflags(y)229 }230 }231 }232233 debugflags(c)234}235236// Name returns the command's name: the first word in the use line.237func (c *Command) Name() string {238 if c.name != "" {239 return c.name240 }241 name := c.Use242 i := strings.Index(name, " ")243 if i >= 0 {244 name = name[:i]245 }246 return name247}248249// Determine if the command is itself runnable250func (c *Command) Runnable() bool {251 return c.Run != nil252}253254// Determine if the command has children commands255func (c *Command) HasSubCommands() bool {256 return len(c.commands) > 0257}258259// Determine if the command is a child command260func (c *Command) HasParent() bool {261 return c.parent != nil262}263264// Get the Commands FlagSet265func (c *Command) Flags() *flag.FlagSet {266 if c.flags == nil {267 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)268 if c.flagErrorBuf == nil {269 c.flagErrorBuf = new(bytes.Buffer)270 }271 c.flags.SetOutput(c.flagErrorBuf)272 }273 return c.flags274}275276// Get the Commands Persistent FlagSet277func (c *Command) PersistentFlags() *flag.FlagSet {278 if c.pflags == nil {279 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)280 if c.flagErrorBuf == nil {281 c.flagErrorBuf = new(bytes.Buffer)282 }283 c.pflags.SetOutput(c.flagErrorBuf)284 }285 return c.pflags286}287288// For use in testing289func (c *Command) ResetFlags() {290 c.flagErrorBuf = new(bytes.Buffer)291 c.flagErrorBuf.Reset()292 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)293 c.flags.SetOutput(c.flagErrorBuf)294 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)295 c.pflags.SetOutput(c.flagErrorBuf)296}297298// Does the command contain flags (local not persistent)299func (c *Command) HasFlags() bool {300 return c.Flags().HasFlags()301}302303// Does the command contain persistent flags304func (c *Command) HasPersistentFlags() bool {305 return c.PersistentFlags().HasFlags()306}307308// Climbs up the command tree looking for matching flag309func (c *Command) Flag(name string) (flag *flag.Flag) {310 flag = c.Flags().Lookup(name)311312 if flag == nil {313 flag = c.persistentFlag(name)314 }315316 return317}318319// recursively find matching persistent flag320func (c *Command) persistentFlag(name string) (flag *flag.Flag) {321 if c.HasPersistentFlags() {322 flag = c.PersistentFlags().Lookup(name)323 }324325 if flag == nil && c.HasParent() {326 flag = c.parent.persistentFlag(name)327 }328 return329}330331// Parses persistent flag tree & local flags332func (c *Command) ParseFlags(args []string) (err error) {333 c.mergePersistentFlags()334335 err = c.Flags().Parse(args)336 if err != nil {337 return err338 }339 if c.flagErrorBuf != nil {340 //fmt.Println(c.flagErrorBuf.String())341 return nil342 //return fmt.Errorf("%s", c.flagErrorBuf.String())343 }344 return nil345}346347func (c *Command) mergePersistentFlags() {348 var rmerge func(x *Command)349350 rmerge = func(x *Command) {351 if x.HasPersistentFlags() {352 x.PersistentFlags().VisitAll(func(f *flag.Flag) {353 if c.Flags().Lookup(f.Name) == nil {354 c.Flags().AddFlag(f)355 }356 })357 }358 if x.HasParent() {359 rmerge(x.parent)360 }361 }362363 rmerge(c)364}365366func (c *Command) Parent() *Command {367 return c.parent368}
added:commander.go+119 added
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}3637// Provide the user with a new commander.38func NewCommander() (c *Commander) {39 c = new(Commander)40 c.cmdr = c41 c.UsageFunc = c.defaultUsage42 c.initTemplates()43 return44}4546// Name for commander, should match application name47func (c *Commander) SetName(name string) {48 c.name = name49}5051// os.Args[1:] by default, if desired, can be overridden52// particularly useful when testing.53func (c *Commander) SetArgs(a []string) {54 c.args = a55}5657// Call execute to use the args (os.Args[1:] by default)58// and run through the command tree finding appropriate matches59// for commands and then corresponding flags.60func (c *Commander) Execute() (err error) {61 if len(c.args) == 0 {62 err = c.execute(os.Args[1:])63 } else {64 err = c.execute(c.args)65 }66 return67}6869func (c *Commander) out() io.Writer {70 if c.output == nil {71 return os.Stderr72 }73 return *c.output74}7576func (cmdr *Commander) defaultUsage(c *Command) error {77 err := tmpl(cmdr.out(), cmdr.UsageTemplate, c)78 if err != nil {79 c.Println(err)80 }81 return err82}8384//Print to out85func (c *Commander) PrintOut(i ...interface{}) {86 fmt.Fprint(c.out(), i...)87}8889// SetOutput sets the destination for usage and error messages.90// If output is nil, os.Stderr is used.91func (c *Commander) SetOutput(output io.Writer) {92 c.output = &output93 //*c.output = output94}9596func (c *Commander) initTemplates() {97 c.UsageTemplate = `{{ $cmd := . }}98Usage: {{if .Runnable}}99 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}100 {{ .CommandPath}} [command]{{end}}101{{ if .HasSubCommands}}102Available Commands: {{range .Commands}}{{if .Runnable}}103 {{.Use | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}104{{end}}105{{ if .HasFlags}} Available Flags:106{{.Flags.FlagUsages}}{{end}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }}107Additional help topics: {{if gt .Commands 0 }}{{range .Commands}}{{if not .Runnable}}108 {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}{{if gt .Parent.Commands 1 }}{{range .Parent.Commands}}{{if .Runnable}}{{if not (eq .Name $cmd.Name) }}{{end}}109 {{.CommandPath | printf "%-11s"}} :: {{.Short}}{{end}}{{end}}{{end}}110111{{end}}112Use "{{.Commander.Name}} help [command]" for more information about that command.113`114115 c.HelpTemplate = `{{if .Runnable}}Usage: {{.ProgramName}} {{.UsageLine}}116117{{end}}{{.Long | trim}}118`119}