-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patht-plot.go
More file actions
328 lines (269 loc) · 7.33 KB
/
t-plot.go
File metadata and controls
328 lines (269 loc) · 7.33 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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
Options:
- `-k N` - column number for plot, starting from 1, by default try to detect the first column of numbers
- `-s ...` - style, "bar-simple", "bar-horizontal-1px", "bar-vertical-1px" (default: "bar-simple")
- `-c "#"` - chart character (default: `#`)
- `-w N` - width of chart (default: rest of terminal width using $COLUMNS)
- `-skip regex` - skip lines matching regex
- `-h` - print help and exit
*/
package main
import (
"flag"
"fmt"
"os"
"regexp"
"slices"
"strconv"
"strings"
"unicode/utf8"
"github.com/mattn/go-runewidth"
"github.com/msoap/byline"
"github.com/msoap/tcg"
"github.com/msoap/tcg/turtle"
"golang.org/x/term"
)
const (
defaultTermWidth = 80
maxTermWidth = 120
minChartWidth = 10
widthReserve = 8
)
type opt struct {
style chartStyle
columnN int
barChar string
width int
skipReg *regexp.Regexp
}
type lineData struct {
line string
num float64
width int
}
func main() {
cfg := parseArgs()
lines, err := readStdin()
if err != nil {
printErr("read stdin: %s\n", err)
}
info := getTextInfo(cfg, lines)
maxs := getAllMax(cfg.skipReg, info)
chartLines := createChart(cfg, lines, info, maxs)
fmt.Println(strings.Join(chartLines, "\n"))
}
func printErr(frmt string, args ...any) {
fmt.Fprintf(os.Stderr, frmt, args...)
os.Exit(1)
}
func parseArgs() opt {
res := opt{}
skipReg := ""
doHelp := flag.Bool("h", false, "print help and exit")
flag.Var(&res.style, "s", `style, "bar-simple", "bar-horizontal-1px", "bar-vertical-1px" (default: "bar-simple")`)
flag.IntVar(&res.columnN, "k", 0, "column number for plot, starting from 1, by default try to detect the first column of numbers")
flag.StringVar(&res.barChar, "c", "■", "bar chart character")
flag.IntVar(&res.width, "w", 0, "width of chart")
flag.StringVar(&skipReg, "skip", "", "skip lines matching regex")
flag.Parse()
if *doHelp {
flag.PrintDefaults()
os.Exit(0)
}
if len(res.barChar) == 0 && res.style == csBarSimple {
printErr("bar chart character is empty\n")
}
if skipReg != "" {
var err error
res.skipReg, err = regexp.Compile(skipReg)
if err != nil {
printErr("compile skip regex %q: %s\n", skipReg, err)
}
}
return res
}
func readStdin() ([]string, error) {
return byline.
NewReader(os.Stdin).
MapString(func(in string) string {
return strings.TrimRight(in, "\n")
}).
ReadAllSliceString()
}
func getTextInfo(cfg opt, lines []string) []lineData {
res := make([]lineData, len(lines))
fieldsList := make([][]string, len(lines))
for i, line := range lines {
fieldsList[i] = strings.Fields(line)
}
columnN := cfg.columnN
if columnN == 0 {
columnN = detectNumbersColumn(fieldsList)
}
for i, line := range lines {
res[i].line = line
res[i].width = runewidth.StringWidth(line)
fields := fieldsList[i]
if columnN > len(fields) {
continue
}
res[i].num, _ = strconv.ParseFloat(fields[columnN-1], 64)
}
return res
}
// detectNumbersColumn tries to find the first column with numbers
// meaning that most of its values can be parsed as float64
// and returns its number (starting from 1)
func detectNumbersColumn(fieldsList [][]string) int {
if len(fieldsList) == 0 {
return 1
}
numCols := 0
for _, fields := range fieldsList {
if len(fields) > numCols {
numCols = len(fields)
}
}
if numCols == 0 {
return 1
}
type colCount struct {
col int // 0-based column index
count int
}
counts := make([]colCount, 0, numCols)
for col := 0; col < numCols; col++ {
numericCount := 0
for row := 0; row < len(fieldsList); row++ {
// Skip if row doesn't have enough columns
if col >= len(fieldsList[row]) {
continue
}
value := strings.TrimSpace(fieldsList[row][col])
if value == "" {
continue
}
if _, err := strconv.ParseFloat(value, 64); err == nil {
numericCount++
}
}
counts = append(counts, colCount{col: col, count: numericCount})
}
// Sort by numeric counts in descending order
slices.SortStableFunc(counts, func(a, b colCount) int {
return b.count - a.count
})
if len(counts) > 0 {
return counts[0].col + 1
}
return 1 // Default to first column if no numeric columns found
}
func getAllMax(skipReg *regexp.Regexp, info []lineData) lineData {
maxNum, maxWidth := 0.0, 0
for _, item := range info {
if skipReg != nil && skipReg.MatchString(item.line) {
continue
}
if item.num > maxNum {
maxNum = item.num
}
if item.width > maxWidth {
maxWidth = item.width
}
}
return lineData{"", maxNum, maxWidth}
}
func createChart(cfg opt, lines []string, info []lineData, maxs lineData) []string {
termWidth := getTermWidth()
chartWidth := 0
if cfg.width > 0 {
chartWidth = cfg.width
} else {
chartWidth = termWidth - maxs.width - widthReserve
if chartWidth < minChartWidth {
chartWidth = minChartWidth
}
}
switch cfg.style {
case csBarSimple:
barChart := renderChartSimple(cfg.barChar, chartWidth, info, maxs)
lines = alignTextLines(lines, maxs)
res := make([]string, len(lines))
for i := range lines {
if cfg.skipReg != nil && cfg.skipReg.MatchString(lines[i]) {
res[i] = lines[i]
continue
}
res[i] = lines[i] + "\t" + barChart[i]
}
return res
case csBarHorizontal1px:
return renderChartBarHorizontal1px(chartWidth, info, maxs)
case csBarVertical1px:
return renderChartVertical1px(info, maxs)
default:
printErr("style %v is not implemented yet\n", cfg.style)
return nil
}
}
func getTermWidth() int {
// "tput cols"/"stty size"/$COLUMNS is not working in programs
width, _, _ := term.GetSize(int(os.Stdout.Fd()))
if width == 0 {
width = defaultTermWidth
}
if width > maxTermWidth {
width = maxTermWidth
}
return width
}
func alignTextLines(lines []string, maxs lineData) []string {
res := make([]string, len(lines))
for i, line := range lines {
if l := utf8.RuneCountInString(line); l < maxs.width {
line += strings.Repeat(" ", maxs.width-l)
}
res[i] = line
}
return res
}
func renderChartSimple(barChar string, width int, info []lineData, maxs lineData) []string {
canvas := tcg.NewBuffer(width, len(info))
for i, item := range info {
chartWidth := int(float64(item.num) / float64(maxs.num) * float64(width))
canvas.HLine(0, i, chartWidth, tcg.Black)
}
firstRune, _ := utf8.DecodeRuneInString(barChar)
mode, err := tcg.NewPixelMode(1, 1, []rune{' ', firstRune})
if err != nil {
printErr("create pixel mode for %q: %s\n", barChar, err)
}
res := canvas.RenderAsStrings(*mode)
if len(info) != len(res) {
printErr("something went wrong, len(info) != len(res), %d != %d\n", len(info), len(res))
}
return res
}
func renderChartBarHorizontal1px(width int, info []lineData, maxs lineData) []string {
tcgMode := tcg.Mode2x3
canvas := tcg.NewBuffer(width*tcgMode.Width(), len(info))
for i, item := range info {
barLen := int(float64(item.num) / float64(maxs.num) * float64(width*tcgMode.Width()))
canvas.HLine(0, i, barLen, tcg.Black)
}
res := canvas.RenderAsStrings(tcgMode)
return res
}
func renderChartVertical1px(info []lineData, maxs lineData) []string {
const heightInChars = 10
tcgMode := tcg.Mode2x3
heightInPx := tcgMode.Height() * heightInChars
canvas := tcg.NewBuffer(len(info), heightInPx)
trtl := turtle.New(&canvas)
for i, item := range info {
barLen := int(float64(item.num) / float64(maxs.num) * float64(heightInPx))
trtl.GoToAbs(i, heightInPx).Up(barLen)
}
res := canvas.RenderAsStrings(tcgMode)
return res
}