-
Notifications
You must be signed in to change notification settings - Fork 869
/
go_gen.go
311 lines (280 loc) · 8.82 KB
/
go_gen.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
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package definition
import (
"bytes"
"fmt"
"go/format"
"strings"
"unicode"
"cuelang.org/go/cue"
"github.com/fatih/camelcase"
"github.com/pkg/errors"
"github.com/oam-dev/kubevela/apis/types"
velacue "github.com/oam-dev/kubevela/pkg/cue"
)
// StructParameter is a parameter that can be printed as a struct.
type StructParameter struct {
types.Parameter
// GoType is the same to parameter.Type but can be print in Go
GoType string
Fields []Field
}
// Field is a field of a struct.
type Field struct {
Name string
// GoType is the same to parameter.Type but can be print in Go
GoType string
OmitEmpty bool
}
//nolint:gochecknoglobals
var (
WellKnownAbbreviations = map[string]bool{
"API": true,
"DB": true,
"HTTP": true,
"HTTPS": true,
"ID": true,
"JSON": true,
"OS": true,
"SQL": true,
"SSH": true,
"URI": true,
"URL": true,
"XML": true,
"YAML": true,
"CPU": true,
"PVC": true,
}
DefaultNamer = NewFieldNamer("")
)
// A FieldNamer generates a Go field name from a CUE label.
type FieldNamer interface {
FieldName(label string) string
SetPrefix(string)
}
// NewFieldNamer returns a new FieldNamer.
func NewFieldNamer(prefix string) FieldNamer {
return &AbbrFieldNamer{Prefix: prefix, Abbreviations: WellKnownAbbreviations}
}
var structs []StructParameter
// GeneratorParameterStructs generates structs for parameters in cue.
func GeneratorParameterStructs(param cue.Value) ([]StructParameter, error) {
structs = []StructParameter{}
err := parseParameters(param, "Parameter")
return structs, err
}
// NewStructParameter creates a StructParameter
func NewStructParameter() StructParameter {
return StructParameter{
Parameter: types.Parameter{},
GoType: "",
Fields: []Field{},
}
}
// parseParameters will be called recursively to parse parameters
func parseParameters(paraValue cue.Value, paramKey string) error {
param := NewStructParameter()
param.Name = paramKey
param.Type = paraValue.IncompleteKind()
param.Short, param.Usage, param.Alias, param.Ignore = velacue.RetrieveComments(paraValue)
if def, ok := paraValue.Default(); ok && def.IsConcrete() {
param.Default = velacue.GetDefault(def)
}
// only StructKind will be separated go struct, other will be just a field
if param.Type == cue.StructKind {
arguments, err := paraValue.Struct()
if err != nil {
return fmt.Errorf("augument not as struct: %w", err)
}
if arguments.Len() == 0 { // in cue, empty struct like: foo: map[string]int
tl := paraValue.Template()
if tl != nil { // map type
// TODO: kind maybe not simple type like string/int, if it is a struct, parseParameters should be called
kind, err := trimIncompleteKind(tl("").IncompleteKind().String())
if err != nil {
return errors.Wrap(err, "invalid parameter kind")
}
param.GoType = fmt.Sprintf("map[string]%s", kind)
}
}
for i := 0; i < arguments.Len(); i++ {
var subParam Field
fi := arguments.Field(i)
if fi.IsDefinition {
continue
}
val := fi.Value
name := fi.Name
subParam.Name = name
subParam.OmitEmpty = fi.IsOptional
switch val.IncompleteKind() {
case cue.StructKind:
if subField, err := val.Struct(); err == nil && subField.Len() == 0 { // err cannot be not nil,so ignore it
if mapValue, ok := val.Elem(); ok {
// In the future we could recursively call to support complex map-value(struct or list)
subParam.GoType = fmt.Sprintf("map[string]%s", mapValue.IncompleteKind().String())
} else {
// element in struct not defined, use interface{}
subParam.GoType = "map[string]interface{}"
}
} else {
if err := parseParameters(val, name); err != nil {
return err
}
subParam.GoType = DefaultNamer.FieldName(name)
}
case cue.ListKind:
elem, success := val.Elem()
if !success {
// fail to get elements, use the value of ListKind to be the type
subParam.GoType = val.IncompleteKind().String()
break
}
switch elem.Kind() {
case cue.StructKind:
subParam.GoType = fmt.Sprintf("[]%s", DefaultNamer.FieldName(name))
if err := parseParameters(elem, name); err != nil {
return err
}
default:
subParam.GoType = fmt.Sprintf("[]%s", elem.IncompleteKind().String())
}
default:
subParam.GoType = val.IncompleteKind().String()
}
param.Fields = append(param.Fields, subParam)
}
}
structs = append(structs, param)
return nil
}
// GenGoCodeFromParams generates go code from parameters
func GenGoCodeFromParams(parameters []StructParameter) (string, error) {
var buf bytes.Buffer
for _, parameter := range parameters {
if parameter.Usage == "" {
parameter.Usage = "-"
}
fmt.Fprintf(&buf, "// %s %s\n", DefaultNamer.FieldName(parameter.Name), parameter.Usage)
genField(parameter, &buf)
}
source, err := format.Source(buf.Bytes())
if err != nil {
fmt.Println("Failed to format source:", err)
}
return string(source), nil
}
// PrintParamGosStruct prints the StructParameter in Golang struct format
func PrintParamGosStruct(parameters []StructParameter) {
code, err := GenGoCodeFromParams(parameters)
if err != nil {
fmt.Println("Fail to gen code, err:", err)
}
fmt.Print(code)
}
func genField(param StructParameter, buffer *bytes.Buffer) {
fieldName := DefaultNamer.FieldName(param.Name)
if param.Type == cue.StructKind { // only struct kind will be separated struct
// cue struct can be Go map or struct
if strings.HasPrefix(param.GoType, "map[string]") {
fmt.Fprintf(buffer, "type %s %s", fieldName, param.GoType)
} else {
fmt.Fprintf(buffer, "type %s struct {\n", fieldName)
for _, f := range param.Fields {
jsonTag := f.Name
if f.OmitEmpty {
jsonTag = fmt.Sprintf("%s,omitempty", jsonTag)
}
fmt.Fprintf(buffer, " %s %s `json:\"%s\"`\n", DefaultNamer.FieldName(f.Name), f.GoType, jsonTag)
}
fmt.Fprintf(buffer, "}\n")
}
} else {
fmt.Fprintf(buffer, "type %s %s\n", fieldName, param.GoType)
}
}
// trimIncompleteKind allows 2 types of incomplete kind, return the non-null one, more than two types of incomplete kind will return error
// 1. (null|someKind)
// 2. someKind
func trimIncompleteKind(mask string) (string, error) {
mask = strings.Trim(mask, "()")
ks := strings.Split(mask, "|")
if len(ks) == 1 {
return ks[0], nil
}
if len(ks) == 2 && ks[0] == "null" {
return ks[1], nil
}
return "", fmt.Errorf("invalid incomplete kind: %s", mask)
}
// An AbbrFieldNamer generates Go field names from Go
// struct field while keeping abbreviations uppercased.
type AbbrFieldNamer struct {
// Prefix is a prefix to add to all field names with first char capitalized automatically.
Prefix string
prefixWithFirstCharCapitalized string
Abbreviations map[string]bool
}
// SetPrefix set a prefix to namer.
func (a *AbbrFieldNamer) SetPrefix(s string) {
a.Prefix = s
}
// FieldName implements FieldNamer.FieldName.
func (a *AbbrFieldNamer) FieldName(field string) string {
if a.prefixWithFirstCharCapitalized == "" && a.Prefix != "" {
a.prefixWithFirstCharCapitalized = strings.ToUpper(a.Prefix[:1]) + a.Prefix[1:]
}
components := SplitComponents(field)
for i, component := range components {
switch {
case component == "":
// do nothing
case a.Abbreviations[strings.ToUpper(component)]:
components[i] = strings.ToUpper(component)
case component == strings.ToUpper(component):
runes := []rune(component)
components[i] = string(runes[0]) + strings.ToLower(string(runes[1:]))
default:
runes := []rune(component)
runes[0] = unicode.ToUpper(runes[0])
components[i] = string(runes)
}
}
runes := []rune(strings.Join(components, ""))
for i, r := range runes {
if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' {
runes[i] = '_'
}
}
fieldName := string(runes)
if !unicode.IsLetter(runes[0]) && runes[0] != '_' {
fieldName = "_" + fieldName
}
if a.prefixWithFirstCharCapitalized != "" {
fieldName = a.prefixWithFirstCharCapitalized + fieldName
}
return fieldName
}
// SplitComponents splits name into components. name may be kebab case, snake
// case, or camel case.
func SplitComponents(name string) []string {
switch {
case strings.ContainsRune(name, '-'):
return strings.Split(name, "-")
case strings.ContainsRune(name, '_'):
return strings.Split(name, "_")
default:
return camelcase.Split(name)
}
}