1
1
package golang
2
2
3
3
import (
4
- "regexp"
5
4
"strings"
5
+ "unicode"
6
6
)
7
7
8
- var IdentPattern = regexp .MustCompile ("[^a-zA-Z0-9_]+" )
9
-
10
8
type Constant struct {
11
9
Name string
12
10
Type string
@@ -29,21 +27,38 @@ func (e Enum) ValidTag() string {
29
27
return TagsToString (e .ValidTags )
30
28
}
31
29
30
+ func enumReplacer (r rune ) rune {
31
+ if strings .ContainsRune ("-/:_" , r ) {
32
+ return '_'
33
+ } else if (r >= 'a' && r <= 'z' ) ||
34
+ (r >= 'A' && r <= 'Z' ) ||
35
+ (r >= '0' && r <= '9' ) {
36
+ return r
37
+ } else {
38
+ return - 1
39
+ }
40
+ }
41
+
42
+ // EnumReplace removes all non ident symbols (all but letters, numbers and
43
+ // underscore) and returns valid ident name for provided name.
32
44
func EnumReplace (value string ) string {
33
- id := strings .Replace (value , "-" , "_" , - 1 )
34
- id = strings .Replace (id , ":" , "_" , - 1 )
35
- id = strings .Replace (id , "/" , "_" , - 1 )
36
- return IdentPattern .ReplaceAllString (id , "" )
45
+ return strings .Map (enumReplacer , value )
37
46
}
38
47
48
+ // EnumValueName removes all non ident symbols (all but letters, numbers and
49
+ // underscore) and converts snake case ident to camel case.
39
50
func EnumValueName (value string ) string {
40
- name := ""
41
- id := strings .Replace (value , "-" , "_" , - 1 )
42
- id = strings .Replace (id , ":" , "_" , - 1 )
43
- id = strings .Replace (id , "/" , "_" , - 1 )
44
- id = IdentPattern .ReplaceAllString (id , "" )
45
- for _ , part := range strings .Split (id , "_" ) {
46
- name += strings .Title (part )
51
+ parts := strings .Split (EnumReplace (value ), "_" )
52
+ for i , part := range parts {
53
+ parts [i ] = titleFirst (part )
47
54
}
48
- return name
55
+
56
+ return strings .Join (parts , "" )
57
+ }
58
+
59
+ func titleFirst (s string ) string {
60
+ r := []rune (s )
61
+ r [0 ] = unicode .ToUpper (r [0 ])
62
+
63
+ return string (r )
49
64
}
0 commit comments