-
Notifications
You must be signed in to change notification settings - Fork 10
/
streams.go
81 lines (61 loc) · 1.84 KB
/
streams.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package term
import (
"fmt"
"io"
"sync"
"github.com/fatih/color"
"github.com/simplesurance/baur/v3/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
lock sync.Mutex
}
func NewStream(out io.Writer) *Stream {
return &Stream{stream: out}
}
func (s *Stream) Printf(format string, a ...any) {
s.lock.Lock()
defer s.lock.Unlock()
fmt.Fprintf(s.stream, format, a...)
}
func (s *Stream) Println(a ...any) {
s.lock.Lock()
defer s.lock.Unlock()
fmt.Fprintln(s.stream, a...)
}
// TaskPrintf prints a message that is prefixed with '<TASK-NAME>: '
func (s *Stream) TaskPrintf(task *baur.Task, format string, a ...any) {
prefix := Highlight(fmt.Sprintf("%s: ", task))
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 ...any) {
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 ...any) {
s.ErrPrintln(err, fmt.Sprintf(format, a...))
}
// PrintErrln prints as message that is prefixed with "ERROR: "
func (s *Stream) PrintErrln(msg ...any) {
s.Println(ErrorPrefix, fmt.Sprint(msg...))
}
// PrintSep prints a separator line
func (s *Stream) PrintSep() {
fmt.Fprintln(s.stream, separator)
}
func (s *Stream) Write(p []byte) (n int, err error) {
s.lock.Lock()
defer s.lock.Unlock()
return s.stream.Write(p)
}