Skip to content

Commit

Permalink
command: move utility functions to print errors to streams package
Browse files Browse the repository at this point in the history
Move the implementation to print errors from the command/helpers.go file to the
streams package.
It fits perfectly there.
  • Loading branch information
fho committed Jun 28, 2021
1 parent e670a09 commit 49ff93d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 13 deletions.
20 changes: 7 additions & 13 deletions internal/command/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -217,25 +215,21 @@ 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{}) {
if err == nil {
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)
}

Expand Down
22 changes: 22 additions & 0 deletions internal/command/term/streams.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 49ff93d

Please sign in to comment.