forked from naoina/toml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
59 lines (55 loc) · 1.19 KB
/
util.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
package toml
import (
"go/ast"
"reflect"
"strings"
"unicode"
)
// toCamelCase returns a copy of the string s with all Unicode letters mapped to their camel case.
// It will convert to upper case previous letter of '_' and first letter, and remove letter of '_'.
func toCamelCase(s string) string {
if s == "" {
return ""
}
result := make([]rune, 0, len(s))
upper := false
for _, r := range s {
if r == '_' {
upper = true
continue
}
if upper {
result = append(result, unicode.ToUpper(r))
upper = false
continue
}
result = append(result, r)
}
result[0] = unicode.ToUpper(result[0])
return string(result)
}
const (
fieldTagName = "toml"
)
func findField(rv reflect.Value, name string) (field reflect.Value, fieldName string, found bool) {
rt := rv.Type()
for i := 0; i < rt.NumField(); i++ {
ft := rt.Field(i)
if !ast.IsExported(ft.Name) {
continue
}
if tag := ft.Tag.Get(fieldTagName); tag == name {
return rv.Field(i), ft.Name, true
}
}
for _, name := range []string{
strings.Title(name),
toCamelCase(name),
strings.ToUpper(name),
} {
if field := rv.FieldByName(name); field.IsValid() {
return field, name, true
}
}
return field, "", false
}