Skip to content

Commit

Permalink
Merge pull request #1100 from Nokel81/set-err-writer
Browse files Browse the repository at this point in the history
Set App.ErrWriter in App.Setup()
  • Loading branch information
coilysiren committed Apr 2, 2020
2 parents 51a2257 + fed64f3 commit 95b323f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 14 deletions.
20 changes: 6 additions & 14 deletions app.go
Expand Up @@ -118,6 +118,7 @@ func NewApp() *App {
Action: helpCommand.Action,
Compiled: compileTime(),
Writer: os.Stdout,
ErrWriter: os.Stderr,
}
}

Expand Down Expand Up @@ -163,6 +164,10 @@ func (a *App) Setup() {
a.Writer = os.Stdout
}

if a.ErrWriter == nil {
a.ErrWriter = os.Stderr
}

var newCommands []*Command

for _, c := range a.Commands {
Expand Down Expand Up @@ -196,10 +201,6 @@ func (a *App) Setup() {
if a.Metadata == nil {
a.Metadata = make(map[string]interface{})
}

if a.Writer == nil {
a.Writer = os.Stdout
}
}

func (a *App) newFlagSet() (*flag.FlagSet, error) {
Expand Down Expand Up @@ -326,7 +327,7 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
// code in the cli.ExitCoder
func (a *App) RunAndExitOnError() {
if err := a.Run(os.Args); err != nil {
_, _ = fmt.Fprintln(a.errWriter(), err)
_, _ = fmt.Fprintln(a.ErrWriter, err)
OsExiter(1)
}
}
Expand Down Expand Up @@ -480,15 +481,6 @@ func (a *App) VisibleFlags() []Flag {
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) {
if !hasFlag(a.Flags, fl) {
a.Flags = append(a.Flags, fl)
Expand Down
31 changes: 31 additions & 0 deletions app_test.go
Expand Up @@ -2152,3 +2152,34 @@ func newTestApp() *App {
a.Writer = ioutil.Discard
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")
}
}

0 comments on commit 95b323f

Please sign in to comment.