/
utils.go
105 lines (89 loc) · 2.43 KB
/
utils.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
package helper
import (
"bytes"
"fmt"
"regexp"
"strings"
"text/template"
"github.com/gookit/goutil/strutil"
)
const (
// RegGoodName match a good option, argument name
RegGoodName = `^[a-zA-Z][\w-]*$`
// RegGoodCmdName match a good command name
RegGoodCmdName = `^[a-zA-Z][\w-]*$`
// RegGoodCmdId match command id. eg: "self:init"
RegGoodCmdId = `^[a-zA-Z][\w:-]*$`
// match command path. eg: "self init"
// RegGoodCmdPath = `^[a-zA-Z][\w -]*$`
)
var (
// GoodName good name for option and argument
goodName = regexp.MustCompile(RegGoodName)
// GoodCmdId match a good command name
goodCmdId = regexp.MustCompile(RegGoodCmdId)
// GoodCmdName match a good command name
goodCmdName = regexp.MustCompile(RegGoodCmdName)
)
// IsGoodName check
func IsGoodName(name string) bool {
return goodName.MatchString(name)
}
// IsGoodCmdId check
func IsGoodCmdId(name string) bool {
return goodCmdId.MatchString(name)
}
// IsGoodCmdName check
func IsGoodCmdName(name string) bool {
return goodCmdName.MatchString(name)
}
// exec: `stty -a 2>&1`
// const (
// mac: speed 9600 baud; 97 rows; 362 columns;
// macSttyMsgPattern = `(\d+)\s+rows;\s*(\d+)\s+columns;`
// linux: speed 38400 baud; rows 97; columns 362; line = 0;
// linuxSttyMsgPattern = `rows\s+(\d+);\s*columns\s+(\d+);`
// )
var (
terminalWidth, terminalHeight int
// macSttyMsgMatch = regexp.MustCompile(macSttyMsgPattern)
// linuxSttyMsgMatch = regexp.MustCompile(linuxSttyMsgPattern)
)
// Panicf message
func Panicf(format string, v ...any) {
panic(fmt.Sprintf("GCli: "+format, v...))
}
// RenderText render text template with data. TODO use strutil.RenderText()
func RenderText(input string, data any, fns template.FuncMap, isFile ...bool) string {
t := template.New("cli")
t.Funcs(template.FuncMap{
// don't escape content
"raw": func(s string) string {
return s
},
"trim": strings.TrimSpace,
// join strings. usage {{ join .Strings ","}}
"join": func(ss []string, sep string) string {
return strings.Join(ss, sep)
},
// lower first char
"lcFirst": strutil.LowerFirst,
// upper first char
"ucFirst": strutil.UpperFirst,
})
// custom add template functions
if len(fns) > 0 {
t.Funcs(fns)
}
if len(isFile) > 0 && isFile[0] {
template.Must(t.ParseFiles(input))
} else {
template.Must(t.Parse(input))
}
// use buffer receive rendered content
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
panic(err)
}
return buf.String()
}