Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set App.ErrWriter in App.Setup() #1100

Merged
merged 2 commits into from Apr 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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")
}
}