-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathannotations.go
More file actions
411 lines (364 loc) · 12.7 KB
/
Copy pathannotations.go
File metadata and controls
411 lines (364 loc) · 12.7 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
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
package annot8
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"log/slog"
"path/filepath"
"strconv"
"strings"
)
// Annotation represents parsed swagger annotations
type Annotation struct {
Summary string
Description string
Tags []string
Accept []string
Produce []string
Security []string
Parameters []ParamAnnotation
Success *SuccessResponse
Failures []ErrorResponse
}
type SuccessResponse struct {
StatusCode int
DataType string
Description string
IsWrapped bool // true if {data} marker was used
}
type ParamAnnotation struct {
Name string
In string
Type string
Required bool
Description string
}
type ErrorResponse struct {
StatusCode int
Type string
Description string
}
// AnnotationParsingError represents errors encountered while parsing annotation lines.
// It contains one or more error messages for malformed annotation directives.
type AnnotationParsingError struct {
Messages []string
}
func (e *AnnotationParsingError) Error() string {
return "annotation parsing errors: " + strings.Join(e.Messages, "; ")
}
// ParseAnnotations reads the AST for the provided Go source file (or the
// project's TypeIndex cache) and extracts comment block annotations for the
// function named by `functionName`.
//
// Behavior notes:
// - Returns nil, nil if no suitable file or comments are found (not an error).
// - Uses a local AST file cache to avoid repeated parsing of the same file.
// - Accepts fully-qualified function names (e.g. "menu.handler.List") and
// extracts the simple function name before matching the AST node.
func ParseAnnotations(filePath, functionName string) (*Annotation, error) {
normalizedFilePath := filepath.ToSlash(filePath)
if strings.Contains(normalizedFilePath, "\\") {
normalizedFilePath = strings.ReplaceAll(normalizedFilePath, "\\", "/")
}
if filePath == "" || filePath == "<autogenerated>" ||
strings.Contains(normalizedFilePath, "/go/pkg/mod/") ||
!strings.HasSuffix(filePath, ".go") {
return nil, nil
}
ensureTypeIndex() // Ensure typeIndex is initialized
// Look up the AST in TypeIndex using normalized paths
astFile := typeIndex.LookupFile(normalizedFilePath)
// If no AST file found in TypeIndex, attempt to parse it manually.
// This ensures that tests using local filenames or temporary files still work.
if astFile == nil {
slog.Debug("[annot8] ParseAnnotations: file not found in TypeIndex, attempting manual parse", "filePath", normalizedFilePath)
fset := token.NewFileSet()
var err error
// Parse only comments as we only need those for annotations
astFile, err = parser.ParseFile(fset, normalizedFilePath, nil, parser.ParseComments)
if err != nil {
slog.Warn("[annot8] ParseAnnotations: failed to parse file manually", "filePath", normalizedFilePath, "error", err)
return nil, nil // Cannot proceed without AST
}
}
// Update filePath and normalizedFilePath if we found a match via case-insensitive lookup
// (though LookupFile doesn't return the path, we can assume it found it if astFile != nil and it was from index)
normalizedFilePath = filepath.ToSlash(filePath)
if strings.Contains(normalizedFilePath, "\\") {
normalizedFilePath = strings.ReplaceAll(normalizedFilePath, "\\", "/")
}
// If a qualified function name was provided (e.g. "menu.handler_addons.List")
// and the resolved file doesn't look like the intended one, try to find
// a better match using the project's TypeIndex. This helps disambiguate
// identical simple function names (like "List") that exist across
// different packages/files (for example, menu and subscription both having
// handler_addons.go with a List method).
if strings.Contains(functionName, ".") && typeIndex != nil {
slog.Debug(
"[annot8] ParseAnnotations: starting TypeIndex disambiguation",
"filePath",
filePath,
"functionName",
functionName,
)
parts := strings.Split(functionName, ".")
// We expect buildUniqueFunctionName to emit packageDir.fileName.funcName
if len(parts) >= 3 {
fileName := parts[len(parts)-2]
packageDir := parts[len(parts)-3]
// If current astFile/filePath does not already look like the qualified one,
// search the TypeIndex for a matching file path and use its parsed AST.
if astFile == nil ||
(!strings.Contains(normalizedFilePath, "/"+fileName+".go") && !strings.Contains(normalizedFilePath, "/"+packageDir+"/")) {
for p, f := range typeIndex.files {
normalizedCandidate := filepath.ToSlash(p)
if strings.HasSuffix(normalizedCandidate, "/"+fileName+".go") &&
strings.Contains(normalizedCandidate, "/"+packageDir+"/") {
astFile = f
filePath = p
normalizedFilePath = filepath.ToSlash(filePath)
normalizedFilePath = normalizedCandidate
slog.Debug(
"[annot8] ParseAnnotations: selected AST from TypeIndex",
"selected",
p,
"targetFileName",
fileName,
"packageDir",
packageDir,
)
break
}
}
}
} else if len(parts) == 2 {
// Possible formats: package.func or file.func - try to match by file or package
cand := parts[0]
if astFile == nil || (!strings.Contains(normalizedFilePath, "/"+cand+".go") && !strings.Contains(normalizedFilePath, "/"+cand+"/")) {
for p, f := range typeIndex.files {
normalizedCandidate := filepath.ToSlash(p)
if strings.HasSuffix(normalizedCandidate, "/"+cand+".go") || strings.Contains(normalizedCandidate, "/"+cand+"/") {
astFile = f
filePath = p
normalizedFilePath = filepath.ToSlash(filePath)
normalizedFilePath = normalizedCandidate
slog.Debug("[annot8] ParseAnnotations: selected AST from TypeIndex", "selected", p, "candidate", cand)
break
}
}
}
}
} else {
slog.Debug("[annot8] ParseAnnotations: no TypeIndex disambiguation performed", "filePath", filePath, "functionName", functionName)
}
// Find the function and its comment
var comment string
// Extract actual function name from qualified name (e.g., "menu.List" -> "List")
actualFunctionName := functionName
if dotIndex := strings.LastIndex(functionName, "."); dotIndex != -1 {
actualFunctionName = functionName[dotIndex+1:]
}
slog.Debug(
"[annot8] ParseAnnotations: locating function comments",
"filePath",
filePath,
"qualified",
functionName,
"actual",
actualFunctionName,
)
for _, decl := range astFile.Decls {
if funcDecl, ok := decl.(*ast.FuncDecl); ok {
if funcDecl.Name.Name == actualFunctionName {
if funcDecl.Doc != nil {
comment = funcDecl.Doc.Text()
slog.Debug(
"[annot8] ParseAnnotations: comment block found",
"file",
filePath,
"function",
actualFunctionName,
)
break
}
// found function but no doc comments
slog.Debug(
"[annot8] ParseAnnotations: function found but missing comments",
"file",
filePath,
"function",
actualFunctionName,
)
}
}
}
if comment == "" {
slog.Debug(
"[annot8] ParseAnnotations: no annotation comment found",
"file",
filePath,
"function",
actualFunctionName,
)
return nil, nil
}
annotation, err := parseAnnotationComment(comment)
if err != nil {
slog.Warn("[annot8] ParseAnnotations: parsing errors", "error", err)
}
return annotation, nil
}
// parseAnnotationComment analyses a block of comment text and builds an
// Annotation structure by scanning for known tokens such as @Summary,
// @Param, @Success, and @Failure. It accumulates parsing errors and
// returns them as an AnnotationParsingError when malformed lines are
// encountered.
func parseAnnotationComment(comment string) (*Annotation, error) {
var errs []string
annotation := &Annotation{}
lines := strings.Split(comment, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
switch {
case strings.HasPrefix(line, "@Summary "):
annotation.Summary = strings.TrimPrefix(line, "@Summary ")
case strings.HasPrefix(line, "@Description "):
annotation.Description = strings.TrimPrefix(line, "@Description ")
case strings.HasPrefix(line, "@Tags "):
tags := strings.TrimPrefix(line, "@Tags ")
annotation.Tags = strings.Split(tags, ",")
for i := range annotation.Tags {
annotation.Tags[i] = strings.TrimSpace(annotation.Tags[i])
}
case strings.HasPrefix(line, "@Accept"):
accept := strings.TrimSpace(strings.TrimPrefix(line, "@Accept"))
if accept == "" {
accept = "application/json"
}
annotation.Accept = append(annotation.Accept, accept)
case strings.HasPrefix(line, "@Produce"):
produce := strings.TrimSpace(strings.TrimPrefix(line, "@Produce"))
if produce == "" {
produce = "application/json"
}
annotation.Produce = append(annotation.Produce, produce)
case strings.HasPrefix(line, "@Security"):
security := strings.TrimSpace(strings.TrimPrefix(line, "@Security"))
annotation.Security = append(annotation.Security, security)
case strings.HasPrefix(line, "@Param "):
param, err := parseParamAnnotation(line)
if err != nil {
errs = append(errs, err.Error())
} else {
annotation.Parameters = append(annotation.Parameters, *param)
}
case strings.HasPrefix(line, "@Success "):
succ, err := parseSuccessAnnotation(line)
if err != nil {
errs = append(errs, err.Error())
} else {
annotation.Success = succ
}
case strings.HasPrefix(line, "@Failure "):
fail, err := parseFailureAnnotation(line)
if err != nil {
errs = append(errs, err.Error())
} else {
annotation.Failures = append(annotation.Failures, *fail)
}
}
}
if len(errs) > 0 {
return annotation, &AnnotationParsingError{Messages: errs}
}
return annotation, nil
}
// parseSuccessAnnotation parses a single @Success annotation line and
// converts it into a SuccessResponse containing status code, data type
// and an optional quoted description.
func parseSuccessAnnotation(line string) (*SuccessResponse, error) {
slog.Debug("[annot8] parseSuccessAnnotation: called", "line", line)
// @Success 200 {data} Type "Description"
content := strings.TrimPrefix(line, "@Success ")
parts := strings.Fields(content)
if len(parts) < 2 {
return nil, fmt.Errorf("invalid @Success annotation: %s", line)
}
statusCode, err := strconv.Atoi(parts[0])
if err != nil {
return nil, err
}
response := &SuccessResponse{StatusCode: statusCode}
remaining := strings.Join(parts[1:], " ")
// Extract type from {data} Type or {object} Type
if strings.Contains(remaining, "{data}") || strings.Contains(remaining, "{object}") {
if strings.Contains(remaining, "{data}") {
response.IsWrapped = true
}
remaining = strings.Replace(remaining, "{data}", "", 1)
remaining = strings.Replace(remaining, "{object}", "", 1)
remaining = strings.TrimSpace(remaining)
parts := strings.Fields(remaining)
if len(parts) > 0 {
response.DataType = parts[0]
}
}
// Extract description from quotes
if start := strings.Index(remaining, "\""); start != -1 {
if end := strings.LastIndex(remaining, "\""); end != -1 && end > start {
response.Description = remaining[start+1 : end]
}
}
return response, nil
}
// parseParamAnnotation parses a single @Param line into a ParamAnnotation
// structure. Expected format is: @Param <name> <in> <type> <required> "desc"
func parseParamAnnotation(line string) (*ParamAnnotation, error) {
slog.Debug("[annot8] parseParamAnnotation: called", "line", line)
// @Param name in type required "description"
content := strings.TrimPrefix(line, "@Param ")
parts := strings.Fields(content)
if len(parts) < 4 {
return nil, fmt.Errorf("invalid @Param annotation: %s", line)
}
param := &ParamAnnotation{
Name: parts[0],
In: parts[1],
Type: parts[2],
Required: parts[3] == "true",
}
// Extract description
if start := strings.Index(content, "\""); start != -1 {
if end := strings.LastIndex(content, "\""); end != -1 && end > start {
param.Description = content[start+1 : end]
}
}
return param, nil
}
// parseFailureAnnotation parses @Failure lines into an ErrorResponse. It
// extracts the numeric status code and optional quoted description.
func parseFailureAnnotation(line string) (*ErrorResponse, error) {
slog.Debug("[annot8] parseFailureAnnotation: called", "line", line)
// @Failure 400 {object} Type "Description"
content := strings.TrimPrefix(line, "@Failure ")
parts := strings.Fields(content)
if len(parts) < 2 {
return nil, fmt.Errorf("invalid @Failure annotation: %s", line)
}
statusCode, err := strconv.Atoi(parts[0])
if err != nil {
return nil, err
}
failure := &ErrorResponse{StatusCode: statusCode}
// Extract description
if start := strings.Index(content, "\""); start != -1 {
if end := strings.LastIndex(content, "\""); end != -1 && end > start {
failure.Description = content[start+1 : end]
}
}
return failure, nil
}