-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler_resolution.go
More file actions
334 lines (286 loc) · 8.21 KB
/
Copy pathhandler_resolution.go
File metadata and controls
334 lines (286 loc) · 8.21 KB
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
package annot8
import (
"go/ast"
"go/parser"
"go/token"
"log/slog"
"net/http"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sort"
"strings"
)
var (
trailingIdentRegexp = regexp.MustCompile(`([A-Za-z_][A-Za-z0-9_]*)$`)
receiverMethodRegexp = regexp.MustCompile(`\(\*?([A-Za-z_][A-Za-z0-9_]*)\)\.([A-Za-z_][A-Za-z0-9_]*)$`)
commonRouteExclusions = map[string]struct{}{
"": {},
"v1": {},
"api": {},
}
)
// HandlerInfo describes the source location for a handler function.
type HandlerInfo struct {
File string
FunctionName string
Package string
}
// extractHandlerInfo resolves an http.Handler to source-level information.
func (g *Generator) extractHandlerInfo(handler http.Handler, route string) *HandlerInfo {
slog.Debug("[annot8] extractHandlerInfo: called")
handlerValue := reflect.ValueOf(handler)
if handlerValue.Kind() != reflect.Func {
return nil
}
pc := handlerValue.Pointer()
if cached := g.getHandlerFromCache(pc); cached != nil {
return cached
}
funcInfo := runtime.FuncForPC(pc)
if funcInfo == nil {
return nil
}
file, _ := funcInfo.FileLine(pc)
rawName := funcInfo.Name()
name := resolveRuntimeName(rawName)
slog.Debug(
"[annot8] extractHandlerInfo: runtime info",
"file", file,
"rawName", rawName,
"name", name,
"route", route,
)
if file == "<autogenerated>" || file == "" {
recvType, methodName, ok := extractReceiverAndMethod(rawName)
if ok {
if typeIndex != nil {
if candPath, candMethod, found := findCandidatesInTypeIndex(typeIndex, recvType, methodName, route); found {
file = candPath
name = candMethod
goto resolved
}
}
if projectRoot := findProjectRoot(); projectRoot != "" {
if path := scanProjectForMethod(projectRoot, recvType, methodName); path != "" {
file = path
name = methodName
goto resolved
}
}
}
}
resolved:
unique := buildUniqueFunctionName(file, name)
slog.Debug("[annot8] extractHandlerInfo: resolved", "file", file, "unique", unique)
if file != "" {
if alt := preferRouteSegmentCandidate(typeIndex, route, file, name); alt != "" {
slog.Debug(
"[annot8] extractHandlerInfo: preferRouteSegmentCandidate switched file",
"from", file,
"to", alt,
"route", route,
)
file = alt
unique = buildUniqueFunctionName(file, name)
}
}
hi := &HandlerInfo{File: file, FunctionName: unique}
g.setHandlerCache(pc, hi)
return hi
}
// getHandlerFromCache looks up handler info for a function pointer.
func (g *Generator) getHandlerFromCache(pc uintptr) *HandlerInfo {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.handlerCache[pc]
}
// setHandlerCache stores handler info for a function pointer.
func (g *Generator) setHandlerCache(pc uintptr, hi *HandlerInfo) {
g.cacheMu.Lock()
g.handlerCache[pc] = hi
g.cacheMu.Unlock()
}
// resolveRuntimeName extracts a short function/method name from a runtime symbol.
func resolveRuntimeName(raw string) string {
name := strings.TrimSuffix(raw, "-fm")
if m := trailingIdentRegexp.FindString(name); m != "" {
return m
}
return name
}
// extractReceiverAndMethod parses the receiver type and method from a runtime name.
func extractReceiverAndMethod(raw string) (recvType, method string, ok bool) {
rawClean := strings.TrimSuffix(raw, "-fm")
if m := receiverMethodRegexp.FindStringSubmatch(rawClean); len(m) == 3 {
return m[1], m[2], true
}
return "", "", false
}
// findCandidatesInTypeIndex locates handler methods in the type index.
func findCandidatesInTypeIndex(ti *TypeIndex, recvType, methodName, route string) (path, method string, found bool) {
type candidate struct {
path string
method string
}
var candidates []candidate
for path, af := range ti.files {
for _, decl := range af.Decls {
fd, ok := decl.(*ast.FuncDecl)
if !ok || fd.Recv == nil || fd.Name == nil || fd.Name.Name != methodName {
continue
}
if len(fd.Recv.List) == 0 {
continue
}
switch recv := fd.Recv.List[0].Type.(type) {
case *ast.StarExpr:
if ident, ok := recv.X.(*ast.Ident); ok && ident.Name == recvType && fd.Doc != nil {
candidates = append(candidates, candidate{path: path, method: methodName})
}
case *ast.Ident:
if recv.Name == recvType && fd.Doc != nil {
candidates = append(candidates, candidate{path: path, method: methodName})
}
}
}
}
if len(candidates) == 0 {
return "", "", false
}
if len(candidates) == 1 {
return candidates[0].path, candidates[0].method, true
}
parts := strings.Split(route, "/")
var meaningful []string
for _, seg := range parts {
if seg == "" || seg == "v1" || seg == "api" || strings.ContainsAny(seg, "{}*") {
continue
}
meaningful = append(meaningful, seg)
}
var routeSeg, penult string
if len(meaningful) > 0 {
routeSeg = meaningful[len(meaningful)-1]
if len(meaningful) > 1 {
penult = meaningful[len(meaningful)-2]
}
}
sort.Slice(candidates, func(i, j int) bool { return candidates[i].path < candidates[j].path })
if penult != "" {
for _, c := range candidates {
if strings.Contains(c.path, "/"+penult+"/") || strings.Contains(filepath.Base(c.path), penult) {
return c.path, c.method, true
}
}
}
for _, c := range candidates {
base := filepath.Base(c.path)
if strings.Contains(c.path, "/"+routeSeg+"/") ||
strings.HasSuffix(c.path, "/"+routeSeg+".go") ||
strings.Contains(c.path, routeSeg) ||
strings.Contains(base, routeSeg) ||
strings.Contains(base, routeSeg+"s") {
return c.path, c.method, true
}
}
return candidates[0].path, candidates[0].method, true
}
// scanProjectForMethod walks the project and returns the first file that matches receiver+method.
func scanProjectForMethod(projectRoot, recvType, methodName string) string {
fset := token.NewFileSet()
var foundPath string
_ = filepath.Walk(projectRoot, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() || !strings.HasSuffix(path, ".go") {
return nil
}
parsed, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return nil
}
for _, decl := range parsed.Decls {
fd, ok := decl.(*ast.FuncDecl)
if !ok || fd.Recv == nil || fd.Name == nil || fd.Name.Name != methodName {
continue
}
if len(fd.Recv.List) == 0 {
continue
}
switch recv := fd.Recv.List[0].Type.(type) {
case *ast.StarExpr:
if ident, ok := recv.X.(*ast.Ident); ok && ident.Name == recvType && fd.Doc != nil {
foundPath = path
return filepath.SkipDir
}
case *ast.Ident:
if recv.Name == recvType && fd.Doc != nil {
foundPath = path
return filepath.SkipDir
}
}
}
return nil
})
return foundPath
}
// buildUniqueFunctionName composes a deterministic function identifier.
func buildUniqueFunctionName(file, name string) string {
if file == "" || file == "<autogenerated>" {
return name
}
normalized := filepath.ToSlash(file)
parts := strings.Split(normalized, "/")
var fileName string
if len(parts) > 0 {
fileName = strings.TrimSuffix(parts[len(parts)-1], ".go")
}
var packageDir string
for i := len(parts) - 1; i >= 0; i-- {
if parts[i] != "" && !strings.HasSuffix(parts[i], ".go") {
packageDir = parts[i]
break
}
}
switch {
case packageDir != "" && fileName != "":
return packageDir + "." + fileName + "." + name
case packageDir != "":
return packageDir + "." + name
default:
return name
}
}
// preferRouteSegmentCandidate prefers files whose path matches the route segment.
func preferRouteSegmentCandidate(ti *TypeIndex, route, currentFile, methodName string) string {
if ti == nil {
return ""
}
segments := strings.Split(route, "/")
var routeSeg string
for i := len(segments) - 1; i >= 0; i-- {
seg := segments[i]
if _, skip := commonRouteExclusions[seg]; skip || strings.ContainsAny(seg, "{}*") {
continue
}
routeSeg = seg
break
}
normalizedCurrent := filepath.ToSlash(currentFile)
if routeSeg == "" || strings.Contains(normalizedCurrent, "/"+routeSeg+"/") {
return ""
}
for path, af := range ti.files {
normalizedPath := filepath.ToSlash(path)
if !strings.Contains(normalizedPath, "/"+routeSeg+"/") {
continue
}
for _, decl := range af.Decls {
if fd, ok := decl.(*ast.FuncDecl); ok && fd.Name != nil && fd.Name.Name == methodName {
return path
}
}
}
return ""
}