forked from zeromicro/go-zero
/
string.go
113 lines (95 loc) · 2.19 KB
/
string.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
package util
import (
"strings"
"github.com/zeromicro/go-zero/tools/goctl/util/console"
)
var goKeyword = map[string]string{
"var": "variable",
"const": "constant",
"package": "pkg",
"func": "function",
"return": "rtn",
"defer": "dfr",
"go": "goo",
"select": "slt",
"struct": "structure",
"interface": "itf",
"chan": "channel",
"type": "tp",
"map": "mp",
"range": "rg",
"break": "brk",
"case": "caz",
"continue": "ctn",
"for": "fr",
"fallthrough": "fth",
"else": "es",
"if": "ef",
"switch": "swt",
"goto": "gt",
"default": "dft",
}
// Title returns a string value with s[0] which has been convert into upper case that
// there are not empty input text
func Title(s string) string {
if len(s) == 0 {
return s
}
return strings.ToUpper(s[:1]) + s[1:]
}
// Untitle returns a string value with s[0] which has been convert into lower case that
// there are not empty input text
func Untitle(s string) string {
if len(s) == 0 {
return s
}
return strings.ToLower(s[:1]) + s[1:]
}
// Index returns the index where the item equal,it will return -1 if mismatched
func Index(slice []string, item string) int {
for i := range slice {
if slice[i] == item {
return i
}
}
return -1
}
// SafeString converts the input string into a safe naming style in golang
func SafeString(in string) string {
if len(in) == 0 {
return in
}
data := strings.Map(func(r rune) rune {
if isSafeRune(r) {
return r
}
return '_'
}, in)
headRune := rune(data[0])
if isNumber(headRune) {
return "_" + data
}
return data
}
func isSafeRune(r rune) bool {
return isLetter(r) || isNumber(r) || r == '_'
}
func isLetter(r rune) bool {
return 'A' <= r && r <= 'z'
}
func isNumber(r rune) bool {
return '0' <= r && r <= '9'
}
// EscapeGolangKeyword escapes the golang keywords.
func EscapeGolangKeyword(s string) string {
if !isGolangKeyword(s) {
return s
}
r := goKeyword[s]
console.Info("[EscapeGolangKeyword]: go keyword is forbidden %q, converted into %q", s, r)
return r
}
func isGolangKeyword(s string) bool {
_, ok := goKeyword[s]
return ok
}