Skip to content

Commit 6de96b8

Browse files
eparisbep
authored andcommitted
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.
1 parent 6264dc6 commit 6de96b8

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

command.go

+11-3
Original file line numberDiff line numberDiff line change
@@ -79,18 +79,26 @@ func (c *Command) SetArgs(a []string) {
7979
c.args = a
8080
}
8181

82-
func (c *Command) Out() io.Writer {
82+
func (c *Command) getOut(def io.Writer) io.Writer {
8383
if c.output != nil {
8484
return *c.output
8585
}
8686

8787
if c.HasParent() {
8888
return c.parent.Out()
8989
} else {
90-
return os.Stderr
90+
return def
9191
}
9292
}
9393

94+
func (c *Command) Out() io.Writer {
95+
return c.getOut(os.Stderr)
96+
}
97+
98+
func (c *Command) getOutOrStdout() io.Writer {
99+
return c.getOut(os.Stdout)
100+
}
101+
94102
// SetOutput sets the destination for usage and error messages.
95103
// If output is nil, os.Stderr is used.
96104
func (c *Command) SetOutput(output io.Writer) {
@@ -658,7 +666,7 @@ func (c *Command) Usage() error {
658666
// by the default HelpFunc in the commander
659667
func (c *Command) Help() error {
660668
c.mergePersistentFlags()
661-
err := tmpl(c.Out(), c.HelpTemplate(), c)
669+
err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)
662670
return err
663671
}
664672

0 commit comments

Comments
 (0)