Merge pull request #1100 from Nokel81/set-err-writer

Set App.ErrWriter in App.Setup()
This commit is contained in:
lynn [they] 2020-04-01 20:48:17 -07:00 committed by GitHub
commit 95b323fc6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 14 deletions

20
app.go
View File

@ -118,6 +118,7 @@ func NewApp() *App {
Action: helpCommand.Action, Action: helpCommand.Action,
Compiled: compileTime(), Compiled: compileTime(),
Writer: os.Stdout, Writer: os.Stdout,
ErrWriter: os.Stderr,
} }
} }
@ -163,6 +164,10 @@ func (a *App) Setup() {
a.Writer = os.Stdout a.Writer = os.Stdout
} }
if a.ErrWriter == nil {
a.ErrWriter = os.Stderr
}
var newCommands []*Command var newCommands []*Command
for _, c := range a.Commands { for _, c := range a.Commands {
@ -196,10 +201,6 @@ func (a *App) Setup() {
if a.Metadata == nil { if a.Metadata == nil {
a.Metadata = make(map[string]interface{}) a.Metadata = make(map[string]interface{})
} }
if a.Writer == nil {
a.Writer = os.Stdout
}
} }
func (a *App) newFlagSet() (*flag.FlagSet, error) { func (a *App) newFlagSet() (*flag.FlagSet, error) {
@ -326,7 +327,7 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
// code in the cli.ExitCoder // code in the cli.ExitCoder
func (a *App) RunAndExitOnError() { func (a *App) RunAndExitOnError() {
if err := a.Run(os.Args); err != nil { if err := a.Run(os.Args); err != nil {
_, _ = fmt.Fprintln(a.errWriter(), err) _, _ = fmt.Fprintln(a.ErrWriter, err)
OsExiter(1) OsExiter(1)
} }
} }
@ -480,15 +481,6 @@ func (a *App) VisibleFlags() []Flag {
return visibleFlags(a.Flags) return visibleFlags(a.Flags)
} }
func (a *App) errWriter() io.Writer {
// When the app ErrWriter is nil use the package level one.
if a.ErrWriter == nil {
return ErrWriter
}
return a.ErrWriter
}
func (a *App) appendFlag(fl Flag) { func (a *App) appendFlag(fl Flag) {
if !hasFlag(a.Flags, fl) { if !hasFlag(a.Flags, fl) {
a.Flags = append(a.Flags, fl) a.Flags = append(a.Flags, fl)

View File

@ -2152,3 +2152,34 @@ func newTestApp() *App {
a.Writer = ioutil.Discard a.Writer = ioutil.Discard
return a return a
} }
func TestSetupInitializesBothWriters(t *testing.T) {
a := &App{}
a.Setup()
if a.ErrWriter != os.Stderr {
t.Errorf("expected a.ErrWriter to be os.Stderr")
}
if a.Writer != os.Stdout {
t.Errorf("expected a.Writer to be os.Stdout")
}
}
func TestSetupInitializesOnlyNilWriters(t *testing.T) {
wr := &bytes.Buffer{}
a := &App{
ErrWriter: wr,
}
a.Setup()
if a.ErrWriter != wr {
t.Errorf("expected a.ErrWriter to be a *bytes.Buffer instance")
}
if a.Writer != os.Stdout {
t.Errorf("expected a.Writer to be os.Stdout")
}
}