Skip to content
Myr

Support and test for custom output.

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

authored by spf13 · committed by spf13 · parent b0c5461 · Browse files · 2 files+68 added−25 removed
This commit

State

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

Diff stats

2 files+68 added−25 removed

  • other:+68 added−25 removed

2 files+68 added−25 removed

modified:cobra_test.go+25 added-1 removed
1package cobra_test23import (4 "bytes"5 . "cobra"6 "fmt"7 "strings"8 "testing"
177 unmodified lines
186 if strings.Join(tt, " ") != "one two" {187 t.Errorf("flags didn't leave proper args remaining..%s given", tt)188 }189190 buf := new(bytes.Buffer)191 // Testing with flag that shouldn't be persistent192 c = initialize()191 cmdEcho.AddCommand(cmdTimes)193 c.SetOutput(buf)194 // define children195 c.AddCommand(cmdPrint, cmdEcho)196 // define grandchild197 cmdEcho.AddCommand(cmdTimes)198 c.SetArgs(strings.Split("echo times -j 99 -i77 one two", " "))199 e := c.Execute()200201 if e == nil {202 t.Errorf("invalid flag should generate error")203 }204205 if !strings.Contains(buf.String(), "inttwo=234") {206 t.Errorf("Wrong error message displayed, \n %s", buf.String())207 }208209 if flagi2 != 99 {210 t.Errorf("flag value should be 99, %d given", flagi2)211 }212213 if flagi1 != 123 {214 t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)215 }216217 // Testing with flag only existing on child218 c = initialize()219 cmdEcho.AddCommand(cmdTimes)220 c.AddCommand(cmdPrint, cmdEcho)221 c.SetArgs(strings.Split("echo -j 99 -i77 one two", " "))222 err := c.Execute()223 _ = err224 //c.DebugFlags()225226 // TODO figure out why this isn't passing227 //if err == nil {228 //t.Errorf("invalid flag should generate error")229 //}230231}232233func TestPersistentFlags(t *testing.T) {234 c := initialize()
33 unmodified lines
modified:cobra.go+43 added-24 removed
34 unmodified lines
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() accessor39 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}
33 unmodified lines
77func (c *Commander) out() io.Writer {78 if c.output == nil {79 return os.Stderr80 }81 return c.output81 return *c.output82}8384func (cmdr *Commander) defaultUsage(c *Command) error {85 err := tmpl(cmdr.out(), cmdr.UsageTemplate, c)
3 unmodified lines
89 return err90}9192//Print to out93func (c *Commander) POut(i ...interface{}) {93func (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 = output100 c.output = &output101 //*c.output = output102}103104func (c *Commander) initTemplates() {104 c.UsageTemplate = `{{ $cmd := . }}{{.CommandPath | printf "%-11s"}} :: {{.Short}}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:113{{.Flags.FlagUsages}}{{end}}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}}
24 unmodified lines
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 command150 parent *Command151 // Commander152 parent *Command153 cmdr *Commander154 flagErrorBuf *bytes.Buffer155}156
19 unmodified lines
176 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 {179 return c.cmdr191 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])204
32 unmodified lines
237 if cmds[i] == c {238 panic("Command can't be a child of itself")239 }240 cmds[i].parent = c222 cmds[i].cmdr = cmds[i].parent.cmdr241 c.commands = append(c.commands, x)242 }243}244245// Convenience method to Print to the defined output246func (c *Command) Print(i ...interface{}) {228 c.cmdr.POut(i...)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 {242 err := c.cmdr.UsageFunc(c)266 err := c.Commander().UsageFunc(c)267 if err != nil {268 fmt.Println(err)269 }246270 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 }257281 return str282}283284//The full usage for a given command (including parents)
49 unmodified lines
334335 debugflags(c)336}337315// Usage prints the usage details to the standard output.316//func (c *Command) PrintUsage() {317//if c.Runnable() {318//c.Printf("usage: %s\n\n", c.Usage())319//}320321//c.Println(strings.Trim(c.Long, "\n"))322//}323338// 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.name
44 unmodified lines
386 }387 return c.pflags388}389376// Intended for use in testing390// 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)
42 unmodified lines
437 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() {
75 unmodified lines