mirror of
https://github.com/spf13/cobra
synced 2024-11-16 18:57:08 +00:00
Default usage output to stdout
If the command has not set an output explicitly everything will go to stderr. This makes a lot of sense, but is a huge PITA for people who want to be able to grep the help output. It is very common for users to want to do command --help | grep flag This patch fixes that by default help output (but not error output like an invalid command) to stdout instead of defaulting to stderr.
This commit is contained in:
parent
6264dc67e1
commit
b45857769c
1 changed files with 11 additions and 3 deletions
14
command.go
14
command.go
|
@ -79,7 +79,7 @@ func (c *Command) SetArgs(a []string) {
|
||||||
c.args = a
|
c.args = a
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Command) Out() io.Writer {
|
func (c *Command) getOut(def io.Writer) io.Writer {
|
||||||
if c.output != nil {
|
if c.output != nil {
|
||||||
return *c.output
|
return *c.output
|
||||||
}
|
}
|
||||||
|
@ -87,10 +87,18 @@ func (c *Command) Out() io.Writer {
|
||||||
if c.HasParent() {
|
if c.HasParent() {
|
||||||
return c.parent.Out()
|
return c.parent.Out()
|
||||||
} else {
|
} else {
|
||||||
return os.Stderr
|
return def
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Command) Out() io.Writer {
|
||||||
|
return c.getOut(os.Stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Command) getOutOrStdout() io.Writer {
|
||||||
|
return c.getOut(os.Stdout)
|
||||||
|
}
|
||||||
|
|
||||||
// SetOutput sets the destination for usage and error messages.
|
// SetOutput sets the destination for usage and error messages.
|
||||||
// If output is nil, os.Stderr is used.
|
// If output is nil, os.Stderr is used.
|
||||||
func (c *Command) SetOutput(output io.Writer) {
|
func (c *Command) SetOutput(output io.Writer) {
|
||||||
|
@ -658,7 +666,7 @@ func (c *Command) Usage() error {
|
||||||
// by the default HelpFunc in the commander
|
// by the default HelpFunc in the commander
|
||||||
func (c *Command) Help() error {
|
func (c *Command) Help() error {
|
||||||
c.mergePersistentFlags()
|
c.mergePersistentFlags()
|
||||||
err := tmpl(c.Out(), c.HelpTemplate(), c)
|
err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue