This repository has been archived by the owner on Jul 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunc.go
115 lines (99 loc) · 1.98 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
// 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 heidou
import (
"go/token"
"strings"
"text/template"
"github.com/iancoleman/strcase"
"github.com/jinzhu/inflection"
)
var (
Funcs = template.FuncMap{
"receiver": receiver,
"snake": snake,
"pascal": pascal,
"camel": camel,
"plural": plural,
"singular": singular,
"ops": ops,
}
)
// 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(strcase.ToSnake(s), "_")
min := len(parts[0])
for _, w := range parts[1:] {
if len(w) < min {
min = len(w)
}
}
//TODO 重复检测
s = parts[0][:1]
for _, w := range parts[1:] {
s += w[:1]
}
name := strings.ToLower(s)
if token.Lookup(name).IsKeyword() {
name = "_" + name
}
return name
}
func snake(s string) string {
return strcase.ToSnake(s)
}
func pascal(s string) string {
return strcase.ToCamel(s)
}
func camel(s string) string {
return strcase.ToLowerCamel(s)
}
func plural(s string) string {
p := inflection.Plural(s)
if p == s {
p += "Slice"
}
return p
}
func singular(s string) string {
return inflection.Singular(s)
}
func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
// ops returns all operations for given field.
func ops(f *Field) (operations []string) {
var ops []string
switch f.MetaType.GqlType {
case "Boolean":
ops = boolOps
case "Int":
ops = numericOps
case "String":
ops = numericOps
case "Time":
ops = numericOps
default:
ops = numericOps
}
for _, op := range f.Operations {
if contains(ops, op) {
operations = append(operations, op)
}
}
return operations
}