forked from akash-network/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
printer.go
68 lines (58 loc) · 1.25 KB
/
printer.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
package uiutil
import (
"bytes"
"fmt"
"io"
"os"
)
// Out is the default out
var Out = os.Stdout
// Component in the interface that UI components need to implement
type Component interface {
Bytes() []byte
}
type Printer interface {
Component
AddTitle(string) Printer
Add(Component) Printer
Flush() error
}
// printer represents a buffered container for components that can be flushed
type printer struct {
out io.Writer
comps []Component
}
// NewPrinter returns a pointer to a new printer object
func NewPrinter(out io.Writer) Printer {
if out == nil {
out = Out
}
return &printer{out: out}
}
// Add adds the components to the printer
func (p *printer) Add(c Component) Printer {
p.comps = append(p.comps, c)
return p
}
// AddTitle adds a Title to the printer
func (p *printer) AddTitle(title string) Printer {
return p.Add(&Title{text: title})
}
// Bytes returns the formmated string of the output
func (p *printer) Bytes() []byte {
var buf bytes.Buffer
for _, c := range p.comps {
buf.Write(c.Bytes())
buf.Write([]byte{'\n'})
}
return buf.Bytes()
}
// Flush prints the output to the writer and clears the buffer
func (p *printer) Flush() error {
_, err := fmt.Fprintln(p.out, p)
if err != nil {
return err
}
p.comps = nil
return nil
}