-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathstrings.go
More file actions
79 lines (63 loc) · 1.68 KB
/
Copy pathstrings.go
File metadata and controls
79 lines (63 loc) · 1.68 KB
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
package parameters
import (
"regexp"
"strings"
"unicode"
)
// KnownAbbreviations contains lower case versions of abbreviations to match.
// Any entry in this list will become full upper case when converting from
// snake_case to camelCase
//
// user_id -> UserID
var KnownAbbreviations = []string{"id", "json", "html", "xml"}
var camelCaseRe = regexp.MustCompile(`(?:^[\p{Ll}]|\d+|[\p{Lu}]+)[\p{Ll}]*`)
// CamelToSnakeCase converts CamelCase to snake_case
// Consecutive capital letters will be treated as one word:
// HTML -> html
func CamelToSnakeCase(str string) string {
words := camelCaseRe.FindAllString(str, -1)
for i := 0; i < len(words); i++ {
words[i] = strings.ToLower(words[i])
}
return strings.Join(words, "_")
}
// SnakeToCamelCase converts snake_case to CamelCase.
// When:
// ucFirst = false - snake_case -> snakeCase
// ucFirst = true - snake_case -> SnakeCase
func SnakeToCamelCase(str string, ucFirst bool) string {
words := strings.Split(str, "_")
var i int
if ucFirst {
i = 0
} else {
i = 1
}
for i = i; i < len(words); i++ {
if isKnownAbbreviation(words[i]) {
words[i] = strings.ToUpper(words[i])
} else {
words[i] = MakeFirstUpperCase(words[i])
}
}
return strings.Join(words, "")
}
// MakeFirstUpperCase upper cases the first letter of the string
func MakeFirstUpperCase(s string) string {
// Handle empty and 1 character strings
if len(s) < 2 {
return strings.ToUpper(s)
}
runes := []rune(s)
runes[0] = unicode.ToUpper(runes[0])
return string(runes)
}
func isKnownAbbreviation(word string) bool {
word = strings.ToLower(word)
for _, value := range KnownAbbreviations {
if value == word {
return true
}
}
return false
}