11package golang
22
33import (
4- "regexp"
54 "strings"
5+ "unicode"
66)
77
8- var IdentPattern = regexp .MustCompile ("[^a-zA-Z0-9_]+" )
9-
108type Constant struct {
119 Name string
1210 Type string
@@ -29,21 +27,38 @@ func (e Enum) ValidTag() string {
2927 return TagsToString (e .ValidTags )
3028}
3129
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.
3244func 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 )
3746}
3847
48+ // EnumValueName removes all non ident symbols (all but letters, numbers and
49+ // underscore) and converts snake case ident to camel case.
3950func 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 )
4754 }
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 )
4964}
0 commit comments