-
Notifications
You must be signed in to change notification settings - Fork 10
/
common.go
503 lines (433 loc) · 13.5 KB
/
common.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
496
497
498
499
500
501
502
503
package go_openrpc_reflect
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"net/url"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strings"
"github.com/alecthomas/jsonschema"
go_jsonschema_walk "github.com/etclabscore/go-jsonschema-walk"
"github.com/go-openapi/spec"
meta_schema "github.com/open-rpc/meta-schema"
)
var errType = reflect.TypeOf((*error)(nil)).Elem()
var errAutogenerated = errors.New("autogenerated file")
var errInvalidFilepath = errors.New("invalid filepath")
var nullContentDescriptor meta_schema.ContentDescriptorObject
var nullSchema meta_schema.JSONSchema
func init() {
nullS := "Null"
var nullT interface{}
nullT = "null"
required, deprecated := true, false
nullSchema = meta_schema.JSONSchema{
JSONSchemaObject: &meta_schema.JSONSchemaObject{
Type: &meta_schema.Type{
SimpleTypes: (*meta_schema.SimpleTypes)(&nullT),
},
}}
nullContentDescriptor = meta_schema.ContentDescriptorObject{
Name: (*meta_schema.ContentDescriptorObjectName)(&nullS),
Description: (*meta_schema.ContentDescriptorObjectDescription)(&nullS),
// Summary: (*meta_schema.ContentDescriptorObjectSummary)(&nullS),
Schema: &nullSchema,
Required: (*meta_schema.ContentDescriptorObjectRequired)(&required),
Deprecated: (*meta_schema.ContentDescriptorObjectDeprecated)(&deprecated),
}
}
func receiverMethods(methodHandler MethodRegisterer, name string, receiver interface{}) (object []meta_schema.MethodObject, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("receiverMethods error: %w", err)
}
}()
ty := reflect.TypeOf(receiver)
rval := reflect.ValueOf(receiver)
methods := []meta_schema.MethodObject{}
for m := 0; m < ty.NumMethod(); m++ {
method := ty.Method(m)
if !methodHandler.IsMethodEligible(method) {
continue
}
fdecl, err := getAstFuncDecl(rval, method)
if err != nil {
if err == errAutogenerated {
continue
}
// if err == errInvalidFilepath {
// rval = reflect.ValueOf(rval.Type())
// fdecl, err = getAstFuncDecl(rval, method)
// if err != nil {
// return nil, fmt.Errorf("getAstFuncDecl2 error: %w", err)
// }
// }
return nil, fmt.Errorf("getAstFuncDecl error: %w, receiver: %v", err, ty.String())
}
name, err := methodHandler.GetMethodName(name, rval, method, fdecl)
if err != nil {
return nil, err
}
description, err := methodHandler.GetMethodDescription(rval, method, fdecl)
if err != nil {
return nil, err
}
summary, err := methodHandler.GetMethodSummary(rval, method, fdecl)
if err != nil {
return nil, err
}
tags, err := methodHandler.GetMethodTags(rval, method, fdecl)
if err != nil {
return nil, err
}
paramsStructure, err := methodHandler.GetMethodParamStructure(rval, method, fdecl)
if err != nil {
return nil, err
}
params := []meta_schema.ContentDescriptorOrReference{}
paramCDs, err := methodHandler.GetMethodParams(rval, method, fdecl)
if err != nil {
return nil, err
}
for i := range paramCDs {
cp := paramCDs[i]
params = append(params, meta_schema.ContentDescriptorOrReference{
ContentDescriptorObject: &cp,
})
}
resultCD, err := methodHandler.GetMethodResult(rval, method, fdecl)
if err != nil {
return nil, err
}
methodErrors, err := methodHandler.GetMethodErrors(rval, method, fdecl)
if err != nil {
return nil, err
}
links, err := methodHandler.GetMethodLinks(rval, method, fdecl)
if err != nil {
return nil, err
}
examples, err := methodHandler.GetMethodExamples(rval, method, fdecl)
if err != nil {
return nil, err
}
deprecated, err := methodHandler.GetMethodDeprecated(rval, method, fdecl)
if err != nil {
return nil, err
}
exDocs, err := methodHandler.GetMethodExternalDocs(rval, method, fdecl)
if err != nil {
return nil, err
}
me := meta_schema.MethodObject{
Name: (*meta_schema.MethodObjectName)(&name),
Description: (*meta_schema.MethodObjectDescription)(&description),
Summary: (*meta_schema.MethodObjectSummary)(&summary),
Tags: tags,
ParamStructure: (*meta_schema.MethodObjectParamStructure)(¶msStructure),
Params: (*meta_schema.MethodObjectParams)(¶ms),
Result: &meta_schema.MethodObjectResult{ContentDescriptorObject: &resultCD},
Errors: methodErrors,
Links: links,
Examples: examples,
Deprecated: (*meta_schema.MethodObjectDeprecated)(&deprecated),
ExternalDocs: exDocs,
}
methods = append(methods, me)
}
return methods, nil
}
func buildContentDescriptorObject(registerer ContentDescriptorRegisterer, r reflect.Value, m reflect.Method, field *ast.Field, ty reflect.Type) (cd meta_schema.ContentDescriptorObject, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("build content descriptor error: %w", err)
}
}()
name, err := registerer.GetContentDescriptorName(r, m, field)
if err != nil {
return cd, err
}
description, err := registerer.GetContentDescriptorDescription(r, m, field)
if err != nil {
return cd, err
}
summary, err := registerer.GetContentDescriptorSummary(r, m, field)
if err != nil {
return cd, err
}
required, err := registerer.GetContentDescriptorRequired(r, m, field)
if err != nil {
return cd, err
}
deprecated, err := registerer.GetContentDescriptorDeprecated(r, m, field)
if err != nil {
return cd, err
}
schema, err := registerer.GetSchema(r, m, field, ty)
if err != nil {
return cd, err
}
// // If name == description, eg. 'hexutil.Bytes' == 'hexutil.Bytes',
// // that means the field represent an unnamed variable. Mostly likely an unnamed return value.
// // Assigning a content descriptor name as a Go type name may be undesirable,
// // particularly since the 'name' field is used in by-name paramStructure cases to key
// // the parameter object.
// // So instead of using this default, let's set the name value to be something
// // generic given the context of the schema instead.
// //
// if name == description {
// // Field is unnamed.
// if schema.Title != nil {
// name = (string)(*schema.Title)
// } else if schema.Type != nil {
// if schema.Type.UnorderedSetOfAny17L18NF5VWcS9ROi != nil {
// u := schema.Type.UnorderedSetOfAny17L18NF5VWcS9ROi
// uu := *u
// a := uu[0]
// n, ok := a.(string)
// if !ok {
// panic("notok1")
// }
// name = n
// } else if schema.Type.Any17L18NF5 != nil {
// a := schema.Type.Any17L18NF5
// aa := *a
// n, ok := aa.(string)
// if !ok {
// panic("notok2")
// }
// name = n
// }
// }
// }
cd = meta_schema.ContentDescriptorObject{
Name: (*meta_schema.ContentDescriptorObjectName)(&name),
Description: (*meta_schema.ContentDescriptorObjectDescription)(&description),
Summary: (*meta_schema.ContentDescriptorObjectSummary)(&summary),
Schema: &schema,
Required: (*meta_schema.ContentDescriptorObjectRequired)(&required),
Deprecated: (*meta_schema.ContentDescriptorObjectDeprecated)(&deprecated),
}
return
}
func buildJSONSchemaObject(registerer SchemaRegisterer, r reflect.Value, m reflect.Method, field *ast.Field, ty reflect.Type) (schema meta_schema.JSONSchema, err error) {
if !jsonschemaPkgSupport(ty) {
err = json.Unmarshal([]byte(`{"type": "object", "title": "typeUnsupportedByJSONSchema"}`), &schema)
return
}
rflctr := jsonschema.Reflector{
AllowAdditionalProperties: false,
RequiredFromJSONSchemaTags: true,
ExpandedStruct: false,
IgnoredTypes: registerer.SchemaIgnoredTypes(),
TypeMapper: registerer.SchemaTypeMap(),
}
jsch := rflctr.ReflectFromType(ty)
// Poor man's glue.
// Need to get the type from the go struct -> json reflector package
// to the swagger/go-openapi/jsonschema spec.
// Do this with JSON marshaling.
// Hacky? Maybe. Effective? Maybe.
mm, err := json.Marshal(jsch)
if err != nil {
return schema, err
}
err = json.Unmarshal(mm, &schema)
if err != nil {
return schema, fmt.Errorf("unmarshal jsch error: %v\n\n%s", err, string(mm))
}
if mutations := registerer.SchemaMutations(ty); len(mutations) > 0 {
jj := spec.Schema{}
err = json.Unmarshal(mm, &jj)
if err != nil {
return schema, err
}
a := go_jsonschema_walk.NewWalker()
for _, m := range mutations {
// Initialize the mutation the function.
// This way, the function is able to be aware of the mutation context,
// ie establish the root schema context.
mutFn := m(&jj)
if err := a.DepthFirst(&jj, mutFn); err != nil {
return schema, err
}
}
out, err := json.Marshal(jj)
if err != nil {
return schema, err
}
schema = meta_schema.JSONSchema{} // Reinitialize
err = json.Unmarshal(out, &schema)
if err != nil {
fmt.Println(string(out))
return schema, fmt.Errorf("error: %v, schema: %s", err, string(out))
}
}
examples, err := registerer.SchemaExamples(ty)
if err != nil {
return schema, err
}
schema.JSONSchemaObject.Examples = examples // ok if nil
return schema, nil
}
func isExportedMethod(method reflect.Method) bool {
return method.PkgPath == ""
}
func isExportedOrBuiltinType(t reflect.Type) bool {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
// PkgPath will be non-empty even for an exported type,
// so we need to check the type name as well.
return token.IsExported(t.Name()) || t.PkgPath() == ""
}
func getAstFuncDecl(r reflect.Value, m reflect.Method) (*ast.FuncDecl, error) {
runtimeFunc := runtime.FuncForPC(m.Func.Pointer())
runtimeFile, _ := runtimeFunc.FileLine(runtimeFunc.Entry())
if strings.Contains(runtimeFile, "autogenerated") {
return nil, errAutogenerated
}
tokenFileSet := token.NewFileSet()
if !filepath.IsAbs(runtimeFile) {
return nil, fmt.Errorf("%w: %s", errInvalidFilepath, runtimeFile)
}
astFile, err := parser.ParseFile(tokenFileSet, runtimeFile, nil, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("parse file: %w, method: %s, file: %s", err, m.Name, runtimeFile)
}
rfName := runtimeFuncBaseName(runtimeFunc)
for _, decl := range astFile.Decls {
fn, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
if fn.Name == nil || fn.Name.Name != rfName {
continue
}
fnRecName := ""
if fn.Recv != nil && fn.Recv.List != nil && len(fn.Recv.List) > 0 {
for _, l := range fn.Recv.List {
if fnRecName != "" {
break
}
i, ok := l.Type.(*ast.Ident)
if ok {
fnRecName = i.Name
continue
}
s, ok := l.Type.(*ast.StarExpr)
if ok {
fnRecName = fmt.Sprintf("%v", s.X)
}
}
}
// Ensure that the receiver name matches.
reRec := regexp.MustCompile(fnRecName + `\s`)
if !reRec.MatchString(r.String()) {
continue
}
return fn, nil
}
return nil, nil
}
func runtimeFuncBaseName(rf *runtime.Func) string {
spl := strings.Split(rf.Name(), ".")
return spl[len(spl)-1]
}
func githubLinkFromValue(receiver reflect.Value, runtimeF *runtime.Func) (*url.URL, error) {
ty := receiver.Type()
switch ty.Kind() {
case reflect.Ptr, reflect.Interface:
ty = ty.Elem()
}
packagePath := ty.PkgPath()
if !strings.HasPrefix(packagePath, "github.com") {
return nil, fmt.Errorf("'%s': not a github.com package name", packagePath)
}
uris := strings.Split(packagePath, "/") // eg. github.com / ethereum / go-ethereum / internal / ethapi / api.go | [.(*MyRec)... ]
githubURIOwnerName := strings.Join(uris[:3], "/")
githubURIRevision := "blob/master"
pkgRelDir := ""
pkgRelDir = strings.Join(uris[3:], "/")
if pkgRelDir != "" {
// Otherwise we get a double // for files at the module root.
pkgRelDir = "/" + pkgRelDir
}
runtimeFile, runtimeLine := runtimeF.FileLine(runtimeF.Entry())
base := filepath.Base(runtimeFile)
ref := fmt.Sprintf("https://%s/%s%s/%s#L%d", githubURIOwnerName, githubURIRevision, pkgRelDir, base, runtimeLine)
return url.Parse(ref)
}
func expandedFieldNamesFromList(in []*ast.Field) (out []*ast.Field) {
expandedFields := []*ast.Field{}
for _, f := range in {
expandedFields = append(expandedFields, fieldsWithNames(f)...)
}
return expandedFields
}
// fieldsWithNames expands a field (either parameter or result, in this case) to
// fields which all have at least one name, or at least one field with one name.
// This handles unnamed fields, and fields declared using multiple names with one type.
// Unnamed fields are assigned a name that is the 'printed' identity of the field Type,
// eg. int -> int, bool -> bool
func fieldsWithNames(f *ast.Field) (fields []*ast.Field) {
if f == nil {
return nil
}
if len(f.Names) == 0 {
fields = append(fields, &ast.Field{
Doc: f.Doc,
Names: []*ast.Ident{{Name: printIdentField(f)}},
Type: f.Type,
Tag: f.Tag,
Comment: f.Comment,
})
return
}
for _, ident := range f.Names {
fields = append(fields, &ast.Field{
Doc: f.Doc,
Names: []*ast.Ident{ident},
Type: f.Type,
Tag: f.Tag,
Comment: f.Comment,
})
}
return
}
func printIdentField(f *ast.Field) string {
b := []byte{}
buf := bytes.NewBuffer(b)
fs := token.NewFileSet()
printer.Fprint(buf, fs, f.Type.(ast.Node))
return buf.String()
}
func jsonschemaPkgSupport(r reflect.Type) bool {
rr := r
if rr.Kind() == reflect.Ptr {
rr = rr.Elem()
}
switch rr.Kind() {
case reflect.Struct,
reflect.Map,
reflect.Slice, reflect.Array,
reflect.Interface,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64,
reflect.Bool,
reflect.String,
reflect.Ptr:
// reflect.Chan:
return true
default:
return false
}
}