-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflag_tables.go
More file actions
113 lines (92 loc) · 2.05 KB
/
Copy pathflag_tables.go
File metadata and controls
113 lines (92 loc) · 2.05 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
package flag
import (
"fmt"
"regexp"
"strings"
"github.com/fatih/color"
"github.com/mattn/go-runewidth"
)
var defaultTablePrint func(head ...string) CmdTablePrint
func SetTablePrint(print func(head ...string) CmdTablePrint) {
defaultTablePrint = print
}
func newCmdTable(head ...string) CmdTablePrint {
if defaultTablePrint != nil {
return defaultTablePrint(head...)
}
return NewMarkdwonTable(head...)
}
type CmdTablePrint interface {
Add(data ...string)
Print()
}
type MarkdwonTable struct {
head []string
rows [][]string
}
var ansiColorRegex = regexp.MustCompile(`\x1b\[[0-9;]*m`)
func NewMarkdwonTable(head ...string) *MarkdwonTable {
return &MarkdwonTable{
head: append([]string(nil), head...),
}
}
func (m *MarkdwonTable) Add(data ...string) {
row := make([]string, len(data))
copy(row, data)
m.rows = append(m.rows, row)
}
func (m *MarkdwonTable) Print() {
if len(m.head) == 0 {
return
}
colNum := len(m.head)
widths := make([]int, colNum)
for i, h := range m.head {
widths[i] = visibleWidth(h)
}
for _, row := range m.rows {
for i := 0; i < colNum && i < len(row); i++ {
w := visibleWidth(row[i])
if w > widths[i] {
widths[i] = w
}
}
}
headerFmt := color.New(color.FgGreen, color.Underline).SprintfFunc()
idFmt := color.New(color.FgYellow).SprintfFunc()
printRow := func(cols []string, isHeader bool) {
for i := 0; i < colNum; i++ {
var cell string
if i < len(cols) {
cell = cols[i]
}
if isHeader {
cell = headerFmt("%s", cell)
} else if i == 0 {
cell = idFmt("%s", cell)
}
fmt.Print(padRightDisplay(cell, widths[i]))
if i != colNum-1 {
fmt.Print(" ")
}
}
fmt.Println()
}
printRow(m.head, true)
for _, row := range m.rows {
printRow(row, false)
}
}
func padRightDisplay(s string, width int) string {
w := visibleWidth(s)
if w >= width {
return s
}
return s + strings.Repeat(" ", width-w)
}
func visibleWidth(s string) int {
return runewidth.StringWidth(stripANSI(s))
}
func stripANSI(s string) string {
return ansiColorRegex.ReplaceAllString(s, "")
}