forked from islenbo/autossh
/
show_menu.go
75 lines (61 loc) · 1.52 KB
/
show_menu.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
package app
import (
"strings"
"github.com/itsfinn/autossh/utils"
)
type Operation struct {
Key string
Label string
End bool
Process func(cfg *Config, args []string) error
}
var menuMap [][]Operation
var operations = make(map[string]Operation)
func init() {
menuMap = [][]Operation{
{
{Key: "add", Label: "添加", Process: handleAdd},
{Key: "edit", Label: "编辑", Process: handleEdit},
{Key: "remove", Label: "删除", Process: handleRemove},
},
{
{Key: "exit", Label: "退出", End: true},
},
}
}
func showMenu() {
var columnsMaxWidths = make(map[int]int)
for i := 0; i < len(menuMap); i++ {
for j := 0; j < len(menuMap[i]); j++ {
operation := menuMap[i][j]
// 计算每列最大长度
maxLen := int(utils.ZhLen(operationFormat(operation)))
if _, exists := columnsMaxWidths[j]; !exists {
columnsMaxWidths[j] = maxLen
}
if columnsMaxWidths[j] < maxLen {
columnsMaxWidths[j] = maxLen
}
operations[operation.Key] = operation
}
}
for i := 0; i < len(menuMap); i++ {
var output = ""
for j := 0; j < len(menuMap[i]); j++ {
operation := menuMap[i][j]
output += stringPadding(operationFormat(operation), columnsMaxWidths[j]) + "\t"
}
utils.Logln(strings.TrimSpace(output))
output = ""
}
}
func operationFormat(operation Operation) string {
return "[" + operation.Key + "] " + operation.Label
}
func stringPadding(str string, paddingLen int) string {
if len(str) < paddingLen {
return stringPadding(str+" ", paddingLen)
} else {
return str
}
}