diff --git a/internal/command/helpers.go b/internal/command/helpers.go index 87dc8b92e..ee9a52c75 100644 --- a/internal/command/helpers.go +++ b/internal/command/helpers.go @@ -6,8 +6,6 @@ import ( "os" "path/filepath" - "github.com/fatih/color" - "github.com/simplesurance/baur/v2/internal/command/term" "github.com/simplesurance/baur/v2/internal/format" "github.com/simplesurance/baur/v2/internal/log" @@ -217,10 +215,13 @@ func mustWriteRow(fmt format.Formatter, row ...interface{}) { exitOnErr(err) } -var errorPrefix = color.New(color.FgRed).Sprint("ERROR:") - func exitOnErrf(err error, format string, v ...interface{}) { - exitOnErr(err, fmt.Sprintf(format, v...)) + if err == nil { + return + } + + stderr.ErrPrintf(err, format, v...) + exitFunc(1) } func exitOnErr(err error, msg ...interface{}) { @@ -228,14 +229,7 @@ func exitOnErr(err error, msg ...interface{}) { return } - if len(msg) == 0 { - stderr.Println(errorPrefix, err) - exitFunc(1) - } - - wholeMsg := fmt.Sprint(msg...) - stderr.Printf("%s %s: %s\n", errorPrefix, wholeMsg, err) - + stderr.ErrPrintln(err, msg...) exitFunc(1) } diff --git a/internal/command/term/streams.go b/internal/command/term/streams.go index 5b60f7a7e..667442c81 100644 --- a/internal/command/term/streams.go +++ b/internal/command/term/streams.go @@ -5,11 +5,15 @@ import ( "io" "sync" + "github.com/fatih/color" + "github.com/simplesurance/baur/v2/pkg/baur" ) const separator = "------------------------------------------------------------------------------" +var errorPrefix = color.New(color.FgRed).Sprint("ERROR:") + // Stream is a concurrency-safe output for term.messages. type Stream struct { stream io.Writer @@ -41,6 +45,24 @@ func (s *Stream) TaskPrintf(task *baur.Task, format string, a ...interface{}) { s.Printf(prefix+format, a...) } +// ErrPrintln prints an error with an optional message. +// The method prints the error in the format: errorPrefix msg: err +func (s *Stream) ErrPrintln(err error, msg ...interface{}) { + if len(msg) == 0 { + s.Println(errorPrefix, err) + return + } + + wholeMsg := fmt.Sprint(msg...) + s.Printf("%s %s: %s\n", errorPrefix, wholeMsg, err) +} + +// ErrPrintf prints an error with an optional printf-style message. +// The method prints the error in the format: errorPrefix msg: err +func (s *Stream) ErrPrintf(err error, format string, a ...interface{}) { + s.ErrPrintln(err, fmt.Sprintf(format, a...)) +} + // PrintSep prints a separator line func (s *Stream) PrintSep() { fmt.Fprintln(s.stream, separator)