-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathbuilder.go
126 lines (100 loc) · 2.43 KB
/
builder.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
package docgen
import (
"errors"
"fmt"
"net/http"
"path/filepath"
"strings"
"github.com/go-chi/chi/v5"
)
func BuildDoc(r chi.Routes) (Doc, error) {
d := Doc{}
goPath := getGoPath()
if goPath == "" {
return d, errors.New("docgen: unable to determine your $GOPATH")
}
// Walk and generate the router docs
d.Router = buildDocRouter(r)
return d, nil
}
func buildDocRouter(r chi.Routes) DocRouter {
rts := r
dr := DocRouter{Middlewares: []DocMiddleware{}}
drts := DocRoutes{}
dr.Routes = drts
for _, mw := range rts.Middlewares() {
dmw := DocMiddleware{
FuncInfo: buildFuncInfo(mw),
}
dr.Middlewares = append(dr.Middlewares, dmw)
}
for _, rt := range rts.Routes() {
drt := DocRoute{Pattern: rt.Pattern, Handlers: DocHandlers{}}
if rt.SubRoutes != nil {
subRoutes := rt.SubRoutes
subDrts := buildDocRouter(subRoutes)
drt.Router = &subDrts
} else {
hall := rt.Handlers["*"]
for method, h := range rt.Handlers {
if method != "*" && hall != nil && fmt.Sprintf("%v", hall) == fmt.Sprintf("%v", h) {
continue
}
dh := DocHandler{Method: method, Middlewares: []DocMiddleware{}}
var endpoint http.Handler
chain, _ := h.(*chi.ChainHandler)
if chain != nil {
for _, mw := range chain.Middlewares {
dh.Middlewares = append(dh.Middlewares, DocMiddleware{
FuncInfo: buildFuncInfo(mw),
})
}
endpoint = chain.Endpoint
} else {
endpoint = h
}
dh.FuncInfo = buildFuncInfo(endpoint)
drt.Handlers[method] = dh
}
}
drts[rt.Pattern] = drt
}
return dr
}
func buildFuncInfo(i interface{}) FuncInfo {
fi := FuncInfo{}
frame := getCallerFrame(i)
goPathSrc := filepath.Join(getGoPath(), "src")
if frame == nil {
fi.Unresolvable = true
return fi
}
pkgName := getPkgName(frame.File)
if pkgName == "chi" {
fi.Unresolvable = true
}
funcPath := frame.Func.Name()
idx := strings.Index(funcPath, "/"+pkgName)
if idx > 0 {
fi.Pkg = funcPath[:idx+1+len(pkgName)]
fi.Func = funcPath[idx+2+len(pkgName):]
} else {
fi.Func = funcPath
}
if strings.Index(fi.Func, ".func") > 0 {
fi.Anonymous = true
}
fi.File = frame.File
fi.Line = frame.Line
if filepath.HasPrefix(fi.File, goPathSrc) {
fi.File = fi.File[len(goPathSrc)+1:]
}
// Check if file info is unresolvable
if !strings.Contains(funcPath, pkgName) {
fi.Unresolvable = true
}
if !fi.Unresolvable {
fi.Comment = getFuncComment(frame.File, frame.Line)
}
return fi
}