-
Notifications
You must be signed in to change notification settings - Fork 197
/
util.go
132 lines (111 loc) · 2.4 KB
/
util.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
package utils
import (
"fmt"
"io"
"strings"
)
func IgnoreErrWriteString(writer io.Writer, s string) {
_, _ = io.WriteString(writer, s)
}
const (
ColorEscape = "\033["
Green = "32m"
Red = "31m"
ColorEnd = ColorEscape + "0m"
Bold = "1"
)
const (
CharClear = "\x1b[H\x1b[2J"
CharTab = "\t"
CharNewLine = "\r\n"
CharCleanLine = '\x15'
)
func WrapperString(text string, color string, meta ...bool) string {
wrapWith := make([]string, 0)
metaLen := len(meta)
switch metaLen {
case 1:
wrapWith = append(wrapWith, Bold)
}
wrapWith = append(wrapWith, color)
return fmt.Sprintf("%s%s%s%s", ColorEscape, strings.Join(wrapWith, ";"), text, ColorEnd)
}
func WrapperTitle(text string) string {
return WrapperString(text, Green, true)
}
func WrapperWarn(text string) string {
text += "\n\r"
return WrapperString(text, Red)
}
func IgnoreErrWriteWindowTitle(writer io.Writer, title string) {
// OSC Ps ; Pt BEL
// OSC Ps ; Pt ST
// Ps = 2 ⇒ Change Window Title to Pt.
_, _ = writer.Write([]byte(fmt.Sprintf("\x1b]2;%s\x07", title)))
}
func LongestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
}
isCommonPrefix := func(length int) bool {
str0, count := strs[0][:length], len(strs)
for i := 1; i < count; i++ {
if strs[i][:length] != str0 {
return false
}
}
return true
}
minLength := len(strs[0])
for _, s := range strs {
if len(s) < minLength {
minLength = len(s)
}
}
low, high := 0, minLength
for low < high {
mid := (high-low+1)/2 + low
if isCommonPrefix(mid) {
low = mid
} else {
high = mid - 1
}
}
return strs[0][:low]
}
func FilterPrefix(strs []string, s string) (r []string) {
for _, v := range strs {
if len(v) >= len(s) {
if v[:len(s)] == s {
r = append(r, v)
}
}
}
return r
}
func LongestStr(strs []string) string {
longestStr := ""
for _, str := range strs {
if len(str) >= len(longestStr) {
longestStr = str
}
}
return longestStr
}
func Pretty(strs []string, width int) (s string) {
longestStr := LongestStr(strs)
length := len(longestStr) + 4
lineCount := width / length
for index, str := range strs {
if index == 0 {
s += fmt.Sprintf(fmt.Sprintf("%%-%ds", length), str)
} else {
if index%lineCount == 0 {
s += fmt.Sprintf(fmt.Sprintf("\n%%-%ds", length), str)
} else {
s += fmt.Sprintf(fmt.Sprintf("%%-%ds", length), str)
}
}
}
return s
}