-
Notifications
You must be signed in to change notification settings - Fork 890
/
func.go
495 lines (453 loc) · 11.6 KB
/
func.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package gen
import (
"bytes"
"errors"
"fmt"
"go/token"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"text/template"
"unicode"
"entgo.io/ent/schema/field"
"github.com/go-openapi/inflect"
)
var (
// Funcs are the predefined template
// functions used by the codegen.
Funcs = template.FuncMap{
"ops": fieldOps,
"add": add,
"append": reflect.Append,
"appends": reflect.AppendSlice,
"order": order,
"camel": camel,
"snake": snake,
"pascal": pascal,
"extend": extend,
"xrange": xrange,
"receiver": receiver,
"plural": plural,
"aggregate": aggregate,
"primitives": primitives,
"singular": rules.Singularize,
"quote": quote,
"base": filepath.Base,
"keys": keys,
"join": join,
"isNil": isNil,
"lower": strings.ToLower,
"upper": strings.ToUpper,
"hasField": hasField,
"hasImport": hasImport,
"indirect": indirect,
"hasPrefix": strings.HasPrefix,
"hasSuffix": strings.HasSuffix,
"trimPackage": trimPackage,
"xtemplate": xtemplate,
"hasTemplate": hasTemplate,
"matchTemplate": matchTemplate,
"split": strings.Split,
"tagLookup": tagLookup,
"toString": toString,
"dict": dict,
"get": get,
"set": set,
"unset": unset,
"hasKey": hasKey,
"list": list,
"fail": fail,
"replace": strings.ReplaceAll,
}
rules = ruleset()
acronyms = make(map[string]struct{})
)
// quote only strings.
func quote(v interface{}) interface{} {
if s, ok := v.(string); ok {
return strconv.Quote(s)
}
return v
}
// fieldOps returns all predicate operations for a given field.
func fieldOps(f *Field) (ops []Op) {
switch t := f.Type.Type; {
case f.HasGoType() && !f.ConvertedToBasic() && !f.Type.Valuer():
case t == field.TypeJSON:
case t == field.TypeBool:
ops = boolOps
case t == field.TypeString && strings.ToLower(f.Name) != "id":
ops = stringOps
if f.HasGoType() && !f.ConvertedToBasic() && f.Type.Valuer() {
ops = numericOps
}
case t == field.TypeEnum || f.IsEdgeField():
ops = enumOps
default:
ops = numericOps
}
if f.Optional {
ops = append(ops, nillableOps...)
}
return ops
}
// xrange generates a slice of len n.
func xrange(n int) (a []int) {
for i := 0; i < n; i++ {
a = append(a, i)
}
return
}
// plural a name.
func plural(name string) string {
p := rules.Pluralize(name)
if p == name {
p += "Slice"
}
return p
}
func isSeparator(r rune) bool {
return r == '_' || r == '-' || unicode.IsSpace(r)
}
func pascalWords(words []string) string {
for i, w := range words {
upper := strings.ToUpper(w)
if _, ok := acronyms[upper]; ok {
words[i] = upper
} else {
words[i] = rules.Capitalize(w)
}
}
return strings.Join(words, "")
}
// pascal converts the given name into a PascalCase.
//
// user_info => UserInfo
// full_name => FullName
// user_id => UserID
// full-admin => FullAdmin
//
func pascal(s string) string {
words := strings.FieldsFunc(s, isSeparator)
return pascalWords(words)
}
// camel converts the given name into a camelCase.
//
// user_info => userInfo
// full_name => fullName
// user_id => userID
// full-admin => fullAdmin
//
func camel(s string) string {
words := strings.FieldsFunc(s, isSeparator)
if len(words) == 1 {
return strings.ToLower(words[0])
}
return strings.ToLower(words[0]) + pascalWords(words[1:])
}
// snake converts the given struct or field name into a snake_case.
//
// Username => username
// FullName => full_name
// HTTPCode => http_code
//
func snake(s string) string {
var (
j int
b strings.Builder
)
for i := 0; i < len(s); i++ {
r := rune(s[i])
// Put '_' if it is not a start or end of a word, current letter is uppercase,
// and previous is lowercase (cases like: "UserInfo"), or next letter is also
// a lowercase and previous letter is not "_".
if i > 0 && i < len(s)-1 && unicode.IsUpper(r) {
if unicode.IsLower(rune(s[i-1])) ||
j != i-1 && unicode.IsLower(rune(s[i+1])) && unicode.IsLetter(rune(s[i-1])) {
j = i
b.WriteString("_")
}
}
b.WriteRune(unicode.ToLower(r))
}
return b.String()
}
// receiver returns the receiver name of the given type.
//
// []T => t
// [1]T => t
// User => u
// UserQuery => uq
//
func receiver(s string) (r string) {
// Trim invalid tokens for identifier prefix.
s = strings.Trim(s, "[]*&0123456789")
parts := strings.Split(snake(s), "_")
min := len(parts[0])
for _, w := range parts[1:] {
if len(w) < min {
min = len(w)
}
}
for i := 1; i < min; i++ {
r := parts[0][:i]
for _, w := range parts[1:] {
r += w[:i]
}
if _, ok := importPkg[r]; !ok {
s = r
break
}
}
name := strings.ToLower(s)
if token.Lookup(name).IsKeyword() {
name = "_" + name
}
return name
}
// typeScope wraps the Type object with extended scope.
type typeScope struct {
*Type
Scope map[interface{}]interface{}
}
// graphScope wraps the Graph object with extended scope.
type graphScope struct {
*Graph
Scope map[interface{}]interface{}
}
// extend extends the parent block with a KV pairs.
//
// {{ with $scope := extend $ "key" "value" }}
// {{ template "setters" $scope }}
// {{ end}}
//
func extend(v interface{}, kv ...interface{}) (interface{}, error) {
scope := make(map[interface{}]interface{})
if len(kv)%2 != 0 {
return nil, fmt.Errorf("invalid number of parameters: %d", len(kv))
}
for i := 0; i < len(kv); i += 2 {
scope[kv[i]] = kv[i+1]
}
switch v := v.(type) {
case *Type:
return &typeScope{Type: v, Scope: scope}, nil
case *Graph:
return &graphScope{Graph: v, Scope: scope}, nil
case *typeScope:
for k := range v.Scope {
scope[k] = v.Scope[k]
}
return &typeScope{Type: v.Type, Scope: scope}, nil
case *graphScope:
for k := range v.Scope {
scope[k] = v.Scope[k]
}
return &graphScope{Graph: v.Graph, Scope: scope}, nil
default:
return nil, fmt.Errorf("invalid type for extend: %T", v)
}
}
// add calculates summarize list of variables.
func add(xs ...int) (n int) {
for _, x := range xs {
n += x
}
return
}
func ruleset() *inflect.Ruleset {
rules := inflect.NewDefaultRuleset()
// Add common initialisms from golint and more.
for _, w := range []string{
"ACL", "API", "ASCII", "AWS", "CPU", "CSS", "DNS", "EOF", "GB", "GUID",
"HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "KB", "LHS", "MAC", "MB",
"QPS", "RAM", "RHS", "RPC", "SLA", "SMTP", "SQL", "SSH", "SSO", "TCP",
"TLS", "TTL", "UDP", "UI", "UID", "URI", "URL", "UTF8", "UUID", "VM",
"XML", "XMPP", "XSRF", "XSS",
} {
acronyms[w] = struct{}{}
rules.AddAcronym(w)
}
return rules
}
// order returns a map of sort orders.
// The key is the function name, and the value its database keyword.
func order() map[string]string {
return map[string]string{
"asc": "incr",
"desc": "decr",
}
}
// aggregate returns a map between all agg-functions and if they accept a field name as a parameter or not.
func aggregate() map[string]bool {
return map[string]bool{
"min": true,
"max": true,
"sum": true,
"mean": true,
"count": false,
}
}
// keys returns the given map keys.
func keys(v reflect.Value) ([]string, error) {
if k := v.Type().Kind(); k != reflect.Map {
return nil, fmt.Errorf("expect map for keys, got: %s", k)
}
keys := make([]string, v.Len())
for i, v := range v.MapKeys() {
keys[i] = v.String()
}
sort.Strings(keys)
return keys, nil
}
// primitives returns all primitives types.
func primitives() []string {
return []string{field.TypeString.String(), field.TypeInt.String(), field.TypeFloat64.String(), field.TypeBool.String()}
}
// join is a wrapper around strings.Join to provide consistent output.
func join(a []string, sep string) string {
sort.Strings(a)
return strings.Join(a, sep)
}
// xtemplate dynamically executes templates by their names.
func xtemplate(name string, v interface{}) (string, error) {
buf := bytes.NewBuffer(nil)
if err := templates.ExecuteTemplate(buf, name, v); err != nil {
return "", err
}
return buf.String(), nil
}
// hasTemplate checks whether a template exists in the loaded templates.
func hasTemplate(name string) bool {
for _, t := range templates.Templates() {
if t.Name() == name {
return true
}
}
return false
}
// matchTemplate returns all template names that match the given patterns.
func matchTemplate(patterns ...string) []string {
var (
names []string
exists = make(map[string]struct{})
)
for _, pattern := range patterns {
for _, t := range templates.Templates() {
name := t.Name()
if _, ok := exists[name]; ok {
continue
}
if match, _ := filepath.Match(pattern, name); match {
names = append(names, name)
exists[name] = struct{}{}
}
}
}
sort.Strings(names)
return names
}
// hasField determines if a struct has a field with the given name.
func hasField(v interface{}, name string) bool {
vr := reflect.Indirect(reflect.ValueOf(v))
return vr.FieldByName(name).IsValid()
}
// hasImport reports if the package name exists in the predefined import packages.
func hasImport(name string) bool {
_, ok := importPkg[name]
return ok
}
// trimPackage trims the package name from the given identifier.
func trimPackage(ident, pkg string) string {
return strings.TrimPrefix(ident, pkg+".")
}
// isNil reports whether its argument v is nil.
func isNil(v interface{}) bool {
rv := indirect(reflect.ValueOf(v))
if !rv.IsValid() {
return true
}
switch rv.Kind() {
case reflect.Invalid:
return true
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice:
return rv.IsNil()
default:
return false
}
}
// indirect returns the item at the end of indirection.
func indirect(v reflect.Value) reflect.Value {
for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
}
return v
}
// tagLookup returns the value associated with key in the tag string.
func tagLookup(tag, key string) string {
v, _ := reflect.StructTag(tag).Lookup(key)
return v
}
// toString converts `v` to a string.
func toString(v interface{}) string {
switch v := v.(type) {
case string:
return v
case []byte:
return string(v)
case error:
return v.Error()
case fmt.Stringer:
return v.String()
default:
return fmt.Sprint(v)
}
}
// dict creates a dictionary from a list of pairs.
func dict(v ...interface{}) map[string]interface{} {
lenv := len(v)
dict := make(map[string]interface{}, lenv/2)
for i := 0; i < lenv; i += 2 {
key := toString(v[i])
if i+1 >= lenv {
dict[key] = ""
continue
}
dict[key] = v[i+1]
}
return dict
}
// get the value from the dict for key.
func get(d map[string]interface{}, key string) interface{} {
if val, ok := d[key]; ok {
return val
}
return ""
}
// set adds a value to the dict for key.
func set(d map[string]interface{}, key string, value interface{}) map[string]interface{} {
d[key] = value
return d
}
// unset removes a key from the dict.
func unset(d map[string]interface{}, key string) map[string]interface{} {
delete(d, key)
return d
}
// hasKey tests whether a key is found in dict.
func hasKey(d map[string]interface{}, key string) bool {
_, ok := d[key]
return ok
}
// list creates a list from values.
func list(v ...interface{}) []interface{} {
return v
}
// fail unconditionally returns an empty string and an error with the specified text.
func fail(msg string) (string, error) {
return "", errors.New(msg)
}