Debian Codegraph @

scripts/format_benchmarks.go

raw
1 package main
2
3 import (
4 "strings"
5 )
6
7 // formatBenchmarks finds the rows through the same parser the updater uses, so
8 // prose, sample output and anything that is not a table stay exactly as they are.
9 func formatBenchmarks(path string) error {
10 lines, err := readLines(path)
11 if err != nil {
12 return err
13 }
14 blocks, err := parseBlocks(lines)
15 if err != nil {
16 return err
17 }
18
19 var rows [][]string
20 at := map[int]int{} // line index -> index in rows
21 for _, b := range blocks {
22 for i := b.open + 1; i < b.end; i++ {
23 if fields, ok := benchFields(lines[i]); ok {
24 at[i] = len(rows)
25 rows = append(rows, fields)
26 }
27 }
28 }
29
30 // One grid for every table. Per table would re-pad every existing row once and
31 // only narrows which table a refresh reflows, which is not worth that diff.
32 widths := columnWidths(rows)
33 for i, r := range at {
34 lines[i] = padRow(rows[r], widths)
35 }
36 return writeLines(path, lines)
37 }
38
39 // padRow puts the name against the left edge and each measured value against the
40 // right edge of its column; the units follow whatever they belong to.
41 func padRow(fields []string, widths []int) string {
42 out := make([]string, len(fields))
43 for i, f := range fields {
44 switch i {
45 case 0:
46 out[i] = padRight(f, widths[i])
47 case 1, 2, 4, 6:
48 out[i] = padLeft(f, widths[i])
49 default:
50 out[i] = f
51 }
52 }
53 return strings.Join(out, " ")
54 }
55
56 func columnWidths(rows [][]string) []int {
57 maxCols := 0
58 for _, r := range rows {
59 if len(r) > maxCols {
60 maxCols = len(r)
61 }
62 }
63
64 widths := make([]int, maxCols)
65 for _, r := range rows {
66 for i, f := range r {
67 if len(f) > widths[i] {
68 widths[i] = len(f)
69 }
70 }
71 }
72 return widths
73 }
74
75 func padLeft(s string, n int) string {
76 if len(s) >= n {
77 return s
78 }
79 return strings.Repeat(" ", n-len(s)) + s
80 }
81
82 func padRight(s string, n int) string {
83 if len(s) >= n {
84 return s
85 }
86 return s + strings.Repeat(" ", n-len(s))
87 }