This repository has been archived by the owner on Sep 9, 2020. It is now read-only.
/
strings.go
103 lines (84 loc) · 1.89 KB
/
strings.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
package ksonnet
import (
"bytes"
"strings"
"unicode"
)
var (
jsonnetKeywords = []string{"assert", "else", "error", "false", "for", "function", "if",
"import", "importstr", "in", "null", "tailstrict", "then", "self", "super",
"true"}
)
// camelCase converts a string to camel case.
func camelCase(in string) string {
out := ""
for i, r := range in {
if i == 0 {
out += strings.ToLower(string(r))
continue
}
out += string(r)
}
return out
}
// stringInSlice returns true if the string is in the slice.
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
// capitalizer adjusts the case of terms found in a string.
func toLower(b byte) byte {
return byte(unicode.ToLower(rune(b)))
}
func isUpper(b byte) bool {
return unicode.IsUpper(rune(b))
}
// capitalize adjusts the case of terms found in a string. It will convert `HTTPHeader` into
// `HttpHeader`.
func capitalize(in string) string {
l := len(in) - 1
if l == 0 {
// nothing to do when there is a one character strings
return in
}
var b bytes.Buffer
b.WriteByte(in[0])
for i := 1; i <= l; i++ {
if isUpper(in[i-1]) {
if i < l {
if isUpper(in[i+1]) || (isUpper(in[i]) && i+1 == l) {
b.WriteByte(toLower(in[i]))
} else {
b.WriteByte(in[i])
}
} else if i == l && isUpper(in[i]) {
b.WriteByte(toLower(in[i]))
} else {
b.WriteByte(in[i])
}
} else {
b.WriteByte(in[i])
}
}
return b.String()
}
// FormatKind formats a string in kind format. i.e camel case with jsonnet keywords massaged.
func FormatKind(s string) string {
if strings.ToLower(s) == "local" {
return "localStorage"
}
if strings.HasPrefix(s, "$") {
s = "dollar" + strings.Title(strings.TrimPrefix(s, "$"))
return s
}
s = capitalize(s)
s = camelCase(s)
if stringInSlice(s, jsonnetKeywords) {
s = s + "Param"
}
return s
}