-
Notifications
You must be signed in to change notification settings - Fork 10
/
env_short_long_name.go
87 lines (63 loc) · 1.25 KB
/
env_short_long_name.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
package clop
import "strings"
// gnu风格名字是,下划线(蛇形)或者(驼峰)都换成中横线风格
// LongOpt -> short-opt
// long_opt -> long-opt
// 专有名字不转换
// 专有名字词
var specialNames = map[string]bool{
"JSON": true,
"XML": true,
"YAML": true,
"URL": true,
"URI": true,
}
func wordStart(b byte) bool {
return b >= 'A' && b <= 'Z' || b == '_'
}
// gnuOptionName 转换为gnu风格的名字
func gnuOptionName(opt string) (string, error) {
var name strings.Builder
if specialNames[opt] {
return opt, nil
}
for i, b := range []byte(opt) {
if wordStart(b) {
if i != 0 {
name.WriteByte('-')
}
if b != '_' {
b = b - 'A' + 'a'
name.WriteByte(b)
}
continue
}
name.WriteByte(b)
}
return name.String(), nil
}
// 环境变量名字是大写,下划线(蛇形)风格
func envOptionName(opt string) (string, error) {
var name strings.Builder
if specialNames[opt] {
return opt, nil
}
for i, b := range []byte(opt) {
if wordStart(b) {
if i != 0 {
name.WriteByte('_')
}
if b == '_' {
continue
}
name.WriteByte(b)
continue
}
if b >= 'a' && b <= 'z' {
name.WriteByte(b - 'a' + 'A')
} else {
name.WriteByte('_')
}
}
return name.String(), nil
}