-
Notifications
You must be signed in to change notification settings - Fork 2
/
lang.go
89 lines (70 loc) · 1.82 KB
/
lang.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
package schema
import (
"reflect"
"strings"
)
// DetailedTypeName takes a type and returns it verbatim.
func DetailedTypeName(t reflect.Type) string {
if t.Kind() == reflect.Ptr {
return "*" + t.Elem().Name()
}
return t.Name()
}
// SimpleTypeName takes a type and returns a more universal/generic name.
// Floats are always "float", unsigned ints are always "uint", ints are always "int".
func SimpleTypeName(t reflect.Type) string {
isPtr := t.Kind() == reflect.Ptr
elemType := t
if isPtr {
elemType = t.Elem()
}
out := elemType.Name()
switch elemType.Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
out = "uint"
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
out = "int"
case reflect.Float32, reflect.Float64:
out = "float"
}
if isPtr {
out = "*" + out
}
return out
}
// TypeNameStartsWithVowel returns true if the type name starts with a vowel.
// This doesn't include "u" as a vowel since words like "user" should be "a user"
// and not "an user".
func TypeNameStartsWithVowel(t string) bool {
if t == "" {
return false
}
t = strings.TrimLeft(t, "*")
switch strings.ToLower(t[:1]) {
case "a", "e", "i", "o":
return true
}
return false
}
// TypeNameWithArticle returns the type name with an indefinite article ("a" or "an").
// If the type name is "null" it just returns "null".
func TypeNameWithArticle(t string) string {
if t == "null" {
return t
}
if TypeNameStartsWithVowel(t) {
return "an " + t
} else {
return "a " + t
}
}
// FieldNameWithPath returns the field name including the path in the following format: parent1.parent2.name
func FieldNameWithPath(f string, path []string) string {
b := strings.Builder{}
for _, p := range path {
b.WriteString(p)
b.WriteRune('.')
}
b.WriteString(f)
return b.String()
}