-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathappDiscovery.ts
More file actions
214 lines (184 loc) · 6.75 KB
/
appDiscovery.ts
File metadata and controls
214 lines (184 loc) · 6.75 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
/**
* FastAPI app discovery logic.
* Handles finding FastAPI apps via pyproject.toml, VS Code settings, or automatic detection.
*/
import * as toml from "toml"
import * as vscode from "vscode"
import type { EntryPoint } from "./core/internal"
import type { Parser } from "./core/parser"
import { findProjectRoot, uriPath } from "./core/pathUtils"
import { buildRouterGraph } from "./core/routerResolver"
import { routerNodeToAppDefinition } from "./core/transformer"
import { collectRoutes, countRouters } from "./core/treeUtils"
import type { AppDefinition } from "./core/types"
import { log } from "./utils/logger"
import { createTimer, trackEntrypointDetected } from "./utils/telemetry"
import { vscodeFileSystem } from "./vscode/vscodeFileSystem"
export type { EntryPoint }
/**
* Parses an entrypoint string in module:variable notation.
* Supports formats like "my_app.main:app" or "main".
* Returns the relative file path and optional variable name.
*/
export function parseEntrypointString(value: string): {
relativePath: string
variableName?: string
} {
const colonIndex = value.indexOf(":")
const modulePath = colonIndex === -1 ? value : value.slice(0, colonIndex)
const variableName =
colonIndex === -1 ? undefined : value.slice(colonIndex + 1)
const relativePath = `${modulePath.replace(/\./g, "/")}.py`
return { relativePath, variableName }
}
/**
* Scans for common FastAPI entry point files (main.py, __init__.py).
* Returns URI strings sorted by depth (shallower first).
*/
async function automaticDetectEntryPoints(
folder: vscode.WorkspaceFolder,
): Promise<string[]> {
const [mainFiles, initFiles] = await Promise.all([
vscode.workspace.findFiles(
new vscode.RelativePattern(folder, "**/main.py"),
),
vscode.workspace.findFiles(
new vscode.RelativePattern(folder, "**/__init__.py"),
),
])
return [...mainFiles, ...initFiles]
.map((uri) => uri.toString())
.sort((a, b) => uriPath(a).split("/").length - uriPath(b).split("/").length)
}
/**
* Parses pyproject.toml to find a defined entrypoint.
* Supports module:variable notation, e.g. "my_app.main:app"
*/
async function parsePyprojectForEntryPoint(
folderUri: vscode.Uri,
): Promise<EntryPoint | null> {
const pyprojectUri = vscode.Uri.joinPath(folderUri, "pyproject.toml")
if (!(await vscodeFileSystem.exists(pyprojectUri.toString()))) {
return null
}
try {
const document = await vscode.workspace.openTextDocument(pyprojectUri)
const contents = toml.parse(document.getText()) as Record<string, unknown>
const entrypoint = (contents.tool as Record<string, unknown> | undefined)
?.fastapi as Record<string, unknown> | undefined
const entrypointValue = entrypoint?.entrypoint as string | undefined
if (!entrypointValue) {
return null
}
const { relativePath, variableName } =
parseEntrypointString(entrypointValue)
const fullUri = vscode.Uri.joinPath(folderUri, relativePath)
return (await vscodeFileSystem.exists(fullUri.toString()))
? { filePath: fullUri.toString(), variableName }
: null
} catch {
// Invalid TOML syntax - silently fall back to auto-detection
return null
}
}
/**
* Discovers FastAPI apps in the workspace.
* Priority: VS Code settings > pyproject.toml > automatic detection
*/
export async function discoverFastAPIApps(
parser: Parser,
): Promise<AppDefinition[]> {
const workspaceFolders = vscode.workspace.workspaceFolders
if (!workspaceFolders) {
log("No workspace folders found")
return []
}
log(
`Discovering FastAPI apps in ${workspaceFolders.length} workspace folder(s)...`,
)
const apps: AppDefinition[] = []
for (const folder of workspaceFolders) {
const folderTimer = createTimer()
let detectionMethod: "config" | "pyproject" | "heuristic" = "heuristic"
const folderApps: AppDefinition[] = []
const config = vscode.workspace.getConfiguration("fastapi", folder.uri)
const customEntryPoint = config.get<string>("entryPoint")
let candidates: EntryPoint[]
// If user specified an entry point in settings, use that
if (customEntryPoint) {
const { relativePath, variableName } =
parseEntrypointString(customEntryPoint)
const entryUri = vscode.Uri.joinPath(folder.uri, relativePath)
if (!(await vscodeFileSystem.exists(entryUri.toString()))) {
log(`Custom entry point not found: ${customEntryPoint}`)
vscode.window.showWarningMessage(
`FastAPI entry point not found: ${customEntryPoint}`,
)
continue
}
log(`Using custom entry point: ${customEntryPoint}`)
candidates = [{ filePath: entryUri.toString(), variableName }]
detectionMethod = "config"
} else {
// Otherwise, check pyproject.toml or auto-detect
const pyprojectEntry = await parsePyprojectForEntryPoint(folder.uri)
if (pyprojectEntry) {
candidates = [pyprojectEntry]
detectionMethod = "pyproject"
} else {
const detected = await automaticDetectEntryPoints(folder)
candidates = detected.map((filePath) => ({ filePath }))
detectionMethod = "heuristic"
log(
`Found ${candidates.length} candidate entry file(s) in ${folder.name}`,
)
}
// If no candidates found, try the active editor as a last resort
if (candidates.length === 0) {
const activeEditor = vscode.window.activeTextEditor
if (activeEditor?.document.languageId === "python") {
candidates = [{ filePath: activeEditor.document.uri.toString() }]
}
}
}
for (const candidate of candidates) {
const projectRoot = await findProjectRoot(
candidate.filePath,
folder.uri.toString(),
vscodeFileSystem,
)
const routerNode = await buildRouterGraph(
candidate.filePath,
parser,
projectRoot,
vscodeFileSystem,
candidate.variableName,
)
if (routerNode) {
const app = routerNodeToAppDefinition(routerNode, folder.uri.fsPath)
folderApps.push(app)
apps.push(app)
break // TODO: Only use first successful app per workspace folder, for now
}
}
const folderRoutes = collectRoutes(folderApps)
if (folderApps.length > 0) {
const app = folderApps[0]
log(
`Found FastAPI app "${app.name}" with ${folderRoutes.length} route(s) in ${app.routers.length} router(s)`,
)
}
// Track entrypoint detection per workspace folder
trackEntrypointDetected({
duration_ms: folderTimer(),
method: detectionMethod,
success: folderApps.length > 0,
routes_count: folderRoutes.length,
routers_count: countRouters(folderApps),
})
}
if (apps.length === 0) {
log("No FastAPI apps found in workspace")
}
return apps
}