forked from go-courier/httptransport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openapi_generator.go
142 lines (116 loc) · 3.57 KB
/
openapi_generator.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
package openapi
import (
"context"
"encoding/json"
"go/ast"
"go/types"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/fatih/color"
"github.com/go-courier/oas"
"github.com/go-courier/packagesx"
"github.com/pkg/errors"
)
func NewOpenAPIGenerator(pkg *packagesx.Package) *OpenAPIGenerator {
return &OpenAPIGenerator{
pkg: pkg,
openapi: oas.NewOpenAPI(),
routerScanner: NewRouterScanner(pkg),
}
}
type OpenAPIGenerator struct {
pkg *packagesx.Package
openapi *oas.OpenAPI
routerScanner *RouterScanner
}
func rootRouter(pkgInfo *packagesx.Package, callExpr *ast.CallExpr) *types.Var {
if len(callExpr.Args) > 0 {
if selectorExpr, ok := callExpr.Fun.(*ast.SelectorExpr); ok {
if typesFunc, ok := pkgInfo.TypesInfo.ObjectOf(selectorExpr.Sel).(*types.Func); ok {
if signature, ok := typesFunc.Type().(*types.Signature); ok {
if isRouterType(signature.Params().At(0).Type()) {
if selectorExpr.Sel.Name == "Run" || selectorExpr.Sel.Name == "Serve" {
switch node := callExpr.Args[0].(type) {
case *ast.SelectorExpr:
return pkgInfo.TypesInfo.ObjectOf(node.Sel).(*types.Var)
case *ast.Ident:
return pkgInfo.TypesInfo.ObjectOf(node).(*types.Var)
}
}
}
}
}
}
}
return nil
}
func (g *OpenAPIGenerator) Scan(ctx context.Context) {
defer func() {
g.routerScanner.operatorScanner.BindSchemas(g.openapi)
}()
for ident, def := range g.pkg.TypesInfo.Defs {
if typFunc, ok := def.(*types.Func); ok {
if typFunc.Name() != "main" {
continue
}
ast.Inspect(ident.Obj.Decl.(*ast.FuncDecl), func(node ast.Node) bool {
switch n := node.(type) {
case *ast.CallExpr:
if rootRouterVar := rootRouter(g.pkg, n); rootRouterVar != nil {
router := g.routerScanner.Router(rootRouterVar)
routes := router.Routes()
operationIDs := map[string]*Route{}
for _, route := range routes {
method := route.Method()
operation := g.OperationByOperatorTypes(method, route.Operators...)
if _, exists := operationIDs[operation.OperationId]; exists {
panic(errors.Errorf("operationID %s should be unique", operation.OperationId))
}
operationIDs[operation.OperationId] = route
g.openapi.AddOperation(oas.HttpMethod(strings.ToLower(method)), g.patchPath(route.Path(), operation), operation)
}
}
}
return true
})
return
}
}
}
var reHttpRouterPath = regexp.MustCompile("/:([^/]+)")
func (g *OpenAPIGenerator) patchPath(openapiPath string, operation *oas.Operation) string {
return reHttpRouterPath.ReplaceAllStringFunc(openapiPath, func(str string) string {
name := reHttpRouterPath.FindAllStringSubmatch(str, -1)[0][1]
isParameterDefined := false
for _, parameter := range operation.Parameters {
if parameter.In == "path" && parameter.Name == name {
isParameterDefined = true
}
}
if isParameterDefined {
return "/{" + name + "}"
}
return "/0"
})
}
func (g *OpenAPIGenerator) OperationByOperatorTypes(method string, operatorTypes ...*OperatorWithTypeName) *oas.Operation {
operation := &oas.Operation{}
length := len(operatorTypes)
for idx := range operatorTypes {
operatorTypes[idx].BindOperation(method, operation, idx == length-1)
}
return operation
}
func (g *OpenAPIGenerator) Output(cwd string) {
file := filepath.Join(cwd, "openapi.json")
data, err := json.MarshalIndent(g.openapi, "", " ")
if err != nil {
return
}
_ = ioutil.WriteFile(file, data, os.ModePerm)
log.Printf("generated openapi spec into %s", color.MagentaString(file))
}