-
Notifications
You must be signed in to change notification settings - Fork 9
/
printer.go
273 lines (227 loc) 路 5.45 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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package printer
import (
"bufio"
"fmt"
"io"
"math"
"os"
"strings"
"github.com/acarl005/stripansi"
"github.com/mattn/go-runewidth"
"github.com/olekukonko/ts"
)
var Output io.Writer = os.Stdout
// print style control
type Printer interface {
Print(s ...string)
}
type Byline struct {
*bufio.Writer
}
func NewByline() Printer {
return &Byline{bufio.NewWriter(Output)}
}
func (b *Byline) Print(s ...string) {
for _, v := range s {
_, _ = b.WriteString(v)
_ = b.WriteByte('\n')
}
_ = b.Flush()
}
// Modified from github.com/acarl005/textcol
type FitTerminal struct {
*bufio.Writer
}
func NewFitTerminal() Printer {
return &FitTerminal{Writer: bufio.NewWriter(Output)}
}
func (f *FitTerminal) Print(s ...string) {
f.printColumns(&s)
}
func (f *FitTerminal) printColumns(strs *[]string) {
defer f.Flush()
maxLength := 0
// also keep track of each individual length to easily calculate padding
lengths := make([]int, 0, len(*strs))
for _, str := range *strs {
colorless := stripansi.Strip(str)
// len() is insufficient here, as it counts emojis as 4 characters each
length := runewidth.StringWidth(colorless)
maxLength = max(maxLength, length)
lengths = append(lengths, length)
}
// see how wide the terminal is
width := getTermWidth()
// calculate the dimensions of the columns
numCols, numRows := calculateTableSize(width, 4, maxLength, len(*strs))
// if we're forced into a single column, fall back to simple printing (one per line)
if numCols == 1 {
for _, str := range *strs {
_, _ = f.WriteString(str)
_ = f.WriteByte('\n')
}
return
}
// `i` will be a left-to-right index. this will need to get converted to a top-to-bottom index
for i := 0; i < numCols*numRows; i++ {
// treat output like a "table" with (x, y) coordinates as an intermediate representation
// first calculate (x, y) from i
x, y := rowIndexToTableCoords(i, numCols)
// then convey (x, y) to `j`, the top-to-bottom index
j := tableCoordsToColIndex(x, y, numRows)
// try to access the array, but the table might have more cells than array elements, so only try to access if within bounds
strLen := 0
str := ""
if j < len(lengths) {
strLen = lengths[j]
str = (*strs)[j]
}
// calculate the amount of padding required
numSpacesRequired := maxLength - strLen
spaceStr := strings.Repeat(" ", numSpacesRequired+1)
// print the item itself
_, _ = f.WriteString(str)
// if we're at the last column, print a line break
if x+1 == numCols {
_ = f.WriteByte('\n')
} else {
_, _ = f.WriteString(spaceStr)
}
}
}
// getTermWidth returns the width of the terminal in characters
// this is a modified version
func getTermWidth() int {
size, _ := ts.GetSize()
return size.Col()
}
/*
original version
func getTermWidth() int {
cmd := exec.Command("stty", "size")
cmd.Stdin = os.Stdin
out, err1 := cmd.Output()
check(err1)
numsStr := strings.Trim(string(out), "\n ")
width, err2 := strconv.Atoi(strings.Split(numsStr, " ")[1])
check(err2)
return width
}
*/
func calculateTableSize(width, margin, maxLength, numCells int) (int, int) {
numCols := (width + margin) / (maxLength + margin)
if numCols == 0 {
numCols = 1
}
numRows := int(math.Ceil(float64(numCells) / float64(numCols)))
return numCols, numRows
}
func rowIndexToTableCoords(i, numCols int) (int, int) {
x := i % numCols
y := i / numCols
return x, y
}
func tableCoordsToColIndex(x, y, numRows int) int {
return y + numRows*x
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
type CommaPrint struct {
*Across
}
func NewCommaPrint() *CommaPrint {
return &CommaPrint{
Across: NewAcross(),
}
}
func (c *CommaPrint) Print(s ...string) {
r := s[:len(s)-1]
for i := range r {
r[i] += ","
}
c.printRowWithNoSpace(&s)
}
type Across struct {
*bufio.Writer
}
func NewAcross() *Across {
return &Across{
Writer: bufio.NewWriter(Output),
}
}
func (a *Across) Print(s ...string) {
a.printRow(&s)
}
func (a *Across) printRowWithNoSpace(strs *[]string) {
defer a.Flush()
width := getTermWidth()
maxLength := 0
for _, str := range *strs {
maxLength += runewidth.StringWidth(stripansi.Strip(str))
if maxLength <= width {
_, _ = a.WriteString(str)
} else {
_, _ = a.WriteString("\n" + str)
maxLength = runewidth.StringWidth(stripansi.Strip(str))
}
}
_ = a.WriteByte('\n')
}
func (a *Across) printRow(strs *[]string) {
defer a.Flush()
width := getTermWidth()
const m = 4
strLen := make([]int, len(*strs))
maxLength := 0
for i, str := range *strs {
colorless := stripansi.Strip(str)
strLen[i] = runewidth.StringWidth(colorless)
maxLength = max(maxLength, strLen[i])
}
cols := (width + m) / (maxLength + 2*m)
if cols == 0 {
cols = 1
}
colWidth := (width+m)/cols - m
for i := 0; i < len(*strs); i += cols {
for j := 0; j < cols && i+j < len(*strs); j++ {
index := i + j
str := (*strs)[index]
padding := colWidth - strLen[index]
if padding < 0 {
padding = 0
}
if j < cols-1 {
fmt.Fprintf(a, "%s%s", str, a.stringOf(' ', padding+m))
} else {
fmt.Fprintf(a, "%s%s", str, a.stringOf(' ', padding))
}
}
_ = a.WriteByte('\n')
}
}
func (a *Across) stringOf(ch rune, count int) string {
s := make([]rune, count)
for i := 0; i < count; i++ {
s[i] = ch
}
return string(s)
}
type Zero struct {
bufio.Writer
}
func NewZero() *Zero {
return &Zero{
Writer: *bufio.NewWriter(Output),
}
}
func (z *Zero) Print(s ...string) {
defer z.Flush()
for _, str := range s {
_, _ = z.WriteString(str)
}
}