-
Notifications
You must be signed in to change notification settings - Fork 4
/
datawriter.go
68 lines (58 loc) · 1.14 KB
/
datawriter.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 herd
import (
"fmt"
"io"
"strings"
)
type datawriter interface {
Write([]string) error
Flush()
}
type columnizer struct {
width int
rows [][]string
lengths []int
output io.Writer
sep string
}
func newColumnizer(w io.Writer, sep string) *columnizer {
return &columnizer{rows: make([][]string, 0), output: w, sep: sep}
}
func (c *columnizer) Write(r []string) error {
if c.lengths == nil {
c.lengths = make([]int, len(r))
}
c.rows = append(c.rows, r)
tl := len(c.lengths) - 1
for i, v := range r {
if l := len(v); l > c.lengths[i] {
c.lengths[i] = l
}
tl += c.lengths[i]
}
c.width = tl
return nil
}
func (c *columnizer) Flush() {
for _, r := range c.rows {
for i, v := range r {
if i > 0 {
fmt.Fprint(c.output, c.sep)
}
fmt.Fprintf(c.output, "%-*s", c.lengths[i], v)
}
fmt.Fprint(c.output, "\n")
}
}
type passthrough struct {
output io.Writer
}
func newPassthrough(w io.Writer) *passthrough {
return &passthrough{output: w}
}
func (p *passthrough) Write(r []string) error {
_, err := p.output.Write([]byte(strings.Join(r, " ") + "\n"))
return err
}
func (p *passthrough) Flush() {
}