Skip to content

Commit

Permalink
print cli errors to stderr
Browse files Browse the repository at this point in the history
This is a small change that prints any errors that surface when
executing the cli (i.e., `cmd.Execute()`) to stderr rather than
stdout.

When redirecting streams, its useful to keep errors separated from
program output so that in the case of an error the message won't be
redirected and is still surfaced. This issue came up for me when
using this terraform-docs in a script, where I encountered an error:

    $ terraform-docs markdown path/not/to/mod > outfile
    zsh: exit 1     terraform-docs markdown path/not/to/mod > outfile

When I ran the above command in my script an error was generated
because the path was incorrect, however the error message wasn't
printed to my console and the outfile was filled with the error
message. The change here modifies the cli's output to instead show:

    $ terraform-docs markdown path/not/to/mod > outfile
    Error: Failed to read module directory: Module directory path/not/to/mod does not exist or cannot be read.
    zsh: exit 1     terraform-docs markdown path/not/to/mod > outfile

and the outfile is empty.

Signed-off-by: Anthony O'Brien <anthony@bearonis.com>
  • Loading branch information
asobrien committed Mar 27, 2021
1 parent 9c738b9 commit e4a3a84
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion cmd/root.go
Expand Up @@ -12,6 +12,7 @@ package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"

Expand All @@ -32,7 +33,7 @@ import (
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() error {
if err := NewCommand().Execute(); err != nil {
fmt.Printf("Error: %s\n", err.Error())
fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
return err
}
return nil
Expand Down

0 comments on commit e4a3a84

Please sign in to comment.