From 5c91d2e95affa1c09dbaaac2bddd9e864c1e0721 Mon Sep 17 00:00:00 2001 From: jolheiser Date: Sun, 16 Jul 2023 21:12:52 -0500 Subject: [PATCH] fix: print errors to stderr and exit code 1 Signed-off-by: jolheiser --- imp.go | 2 +- main.go | 19 +++++++++++-------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/imp.go b/imp.go index f103d86..8d90abe 100644 --- a/imp.go +++ b/imp.go @@ -49,7 +49,7 @@ func runImp(root, ignore string, write, gofumpt, gofumptExtra bool) error { } formatted, err := impFormat(data, mod, gofumpt, gofumptExtra) - if err != nil { + if err != nil && !errors.Is(err, format.ErrNoImports) { return fmt.Errorf("could not format file %q: %w", walkPath, err) } diff --git a/main.go b/main.go index 93c03a9..929bb33 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,13 @@ import ( var Version = "develop" func main() { + if err := mainErr(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func mainErr() error { fs := flag.NewFlagSet("imp", flag.ExitOnError) writeFlag := fs.Bool("write", false, "Write the re-ordered imports instead of just printing them") fs.BoolVar(writeFlag, "w", *writeFlag, "--write") @@ -28,17 +35,15 @@ func main() { if *stdinFlag { mod, err := modInfo() if err != nil { - fmt.Println(err) - return + return err } src, err := io.ReadAll(os.Stdin) if err != nil { - fmt.Println(err) - return + return err } formatted, err := impFormat(src, mod, *gofumptFlag, *gofumptExtraFlag) if err != nil { - fmt.Println(err) + return err } fmt.Print(string(formatted)) } @@ -48,9 +53,7 @@ func main() { root = fs.Arg(0) } - if err := runImp(root, *ignoreFlag, *writeFlag, *gofumptFlag, *gofumptExtraFlag); err != nil { - fmt.Println(err) - } + return runImp(root, *ignoreFlag, *writeFlag, *gofumptFlag, *gofumptExtraFlag) } type module struct {