-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprinter.go
More file actions
79 lines (71 loc) · 1.7 KB
/
printer.go
File metadata and controls
79 lines (71 loc) · 1.7 KB
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
package markdown
import (
"fmt"
"io"
"sync"
)
// Printer that prints to []string, makes writing and testing console apps easier.
type Printer struct {
mu sync.Mutex
w io.Writer
e io.Writer
lines []string
history []string
errors []string
}
// NewPrinter creates a new buffered writer, typically from os.Stdout and os.Stderr
func NewPrinter(w io.Writer, e io.Writer) *Printer {
p := &Printer{}
p.w = w
p.e = e
return p
}
// NewTestWriter returns a test writer that does not flush to the console
func NewTestWriter() *Printer {
p := &Printer{}
p.w = nil
p.e = nil
return p
}
// Println prints and appends a line to the internal stdout printer buffer
func (p *Printer) Println(format string, a ...interface{}) {
p.mu.Lock()
defer p.mu.Unlock()
line := fmt.Sprintf(format+"\n", a...)
p.lines = append(p.lines, line)
}
// PrintErrln prints and appends a line to the internal std err buffer
func (p *Printer) PrintErrln(format string, a ...interface{}) {
p.mu.Lock()
defer p.mu.Unlock()
line := fmt.Sprintf(format+"\n", a...)
p.errors = append(p.errors, line)
}
// GetLines returns all the lines printed.
func (p *Printer) GetLines() []string {
p.mu.Lock()
defer p.mu.Unlock()
lines := make([]string, len(p.lines))
copy(lines, p.lines)
copy(lines, p.errors)
return lines
}
// Flush buffered output to stdout and stderr writers
func (p *Printer) Flush() {
p.mu.Lock()
defer p.mu.Unlock()
p.history = append(p.history, p.lines...)
p.history = append(p.history, p.errors...)
if p.w != nil {
for _, l := range p.lines {
fmt.Fprint(p.w, l)
}
}
if p.e != nil {
for _, l := range p.errors {
fmt.Fprint(p.e, l)
}
}
p.lines = make([]string, 0)
p.errors = make([]string, 0)
}