This repository has been archived by the owner on Mar 24, 2022. It is now read-only.
forked from cloudfoundry/bosh-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
116 lines (94 loc) · 2.13 KB
/
writer.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package table
import (
"fmt"
"io"
"strings"
)
type Writer struct {
w io.Writer
emptyStr string
bgStr string
borderStr string
rows [][]writerCell
widths map[int]int
}
type writerCell struct {
Value Value
String string
}
type hasCustomWriter interface {
Fprintf(io.Writer, string, ...interface{}) (int, error)
}
func NewWriter(w io.Writer, emptyStr, bgStr, borderStr string) *Writer {
return &Writer{
w: w,
emptyStr: emptyStr,
bgStr: bgStr,
borderStr: borderStr,
widths: map[int]int{},
}
}
func (w *Writer) Write(vals []Value) {
rowsToAdd := 1
colsWithRows := [][]writerCell{}
for i, val := range vals {
var rowsInCol []writerCell
cleanStr := strings.Replace(val.String(), "\r", "", -1)
lines := strings.Split(cleanStr, "\n")
if len(lines) == 1 && lines[0] == "" {
rowsInCol = append(rowsInCol, writerCell{Value: val, String: w.emptyStr})
} else {
for _, line := range lines {
rowsInCol = append(rowsInCol, writerCell{Value: val, String: line})
}
}
rowsInColLen := len(rowsInCol)
for _, cell := range rowsInCol {
if len(cell.String) > w.widths[i] {
w.widths[i] = len(cell.String)
}
}
colsWithRows = append(colsWithRows, rowsInCol)
if rowsInColLen > rowsToAdd {
rowsToAdd = rowsInColLen
}
}
for i := 0; i < rowsToAdd; i++ {
var row []writerCell
for _, col := range colsWithRows {
if i < len(col) {
row = append(row, col[i])
} else {
row = append(row, writerCell{})
}
}
w.rows = append(w.rows, row)
}
}
func (w *Writer) Flush() error {
for _, row := range w.rows {
for colIdx, col := range row {
if customWriter, ok := col.Value.(hasCustomWriter); ok {
_, err := customWriter.Fprintf(w.w, "%s", col.String)
if err != nil {
return err
}
} else {
_, err := fmt.Fprintf(w.w, "%s", col.String)
if err != nil {
return err
}
}
paddingSize := w.widths[colIdx] - len(col.String)
_, err := fmt.Fprintf(w.w, strings.Repeat(w.bgStr, paddingSize)+w.borderStr)
if err != nil {
return err
}
}
_, err := fmt.Fprintln(w.w)
if err != nil {
return err
}
}
return nil
}