Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@
"package": "vsce package",
"publish:marketplace": "vsce publish",
"lint": "biome check --write --unsafe --no-errors-on-unmatched --files-ignore-unknown=true src/",
"test": "vscode-test",
"test": "bun run compile && vscode-test",
"prepare": "husky"
},
"devDependencies": {
Expand All @@ -146,6 +146,7 @@
"typescript": "^5.0.0"
},
"dependencies": {
"toml": "^3.0.0",
"web-tree-sitter": "^0.26.3"
},
"lint-staged": {
Expand Down
148 changes: 148 additions & 0 deletions src/appDiscovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/**
* FastAPI app discovery logic.
* Handles finding FastAPI apps via pyproject.toml, VS Code settings, or automatic detection.
*/

import { existsSync } from "node:fs"
import { isAbsolute, sep } from "node:path"
import * as toml from "toml"
import * as vscode from "vscode"
import type { EntryPoint } from "./core/internal"
import type { Parser } from "./core/parser"
import { findProjectRoot } from "./core/pathUtils"
import { buildRouterGraph } from "./core/routerResolver"
import { routerNodeToAppDefinition } from "./core/transformer"
import type { AppDefinition } from "./core/types"

export type { EntryPoint }

/**
* Scans for common FastAPI entry point files (main.py, __init__.py).
* Returns paths sorted by depth (shallower first).
*/
async function automaticDetectEntryPoints(
folderPath: string,
): Promise<string[]> {
const [mainFiles, initFiles] = await Promise.all([
vscode.workspace.findFiles(
new vscode.RelativePattern(folderPath, "**/main.py"),
),
vscode.workspace.findFiles(
new vscode.RelativePattern(folderPath, "**/__init__.py"),
),
])

return [...mainFiles, ...initFiles]
.map((uri) => uri.fsPath)
.sort((a, b) => a.split(sep).length - b.split(sep).length)
}

/**
* Parses pyproject.toml to find a defined entrypoint.
* Supports module:variable notation, e.g. "my_app.main:app"
*/
async function parsePyprojectForEntryPoint(
folderPath: string,
): Promise<EntryPoint | null> {
const pyprojectPath = vscode.Uri.joinPath(
vscode.Uri.file(folderPath),
"pyproject.toml",
)

if (!existsSync(pyprojectPath.fsPath)) {
return null
}

try {
const document = await vscode.workspace.openTextDocument(pyprojectPath)
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
}

// Parse "my_app.main:app" format (variable name after : is optional)
const colonIndex = entrypointValue.indexOf(":")
const modulePath =
colonIndex === -1 ? entrypointValue : entrypointValue.slice(0, colonIndex)
const variableName =
colonIndex === -1 ? undefined : entrypointValue.slice(colonIndex + 1)

// Convert module path to file path: my_app.main -> my_app/main.py
const relativePath = `${modulePath.replace(/\./g, sep)}.py`
const fullPath = vscode.Uri.joinPath(
vscode.Uri.file(folderPath),
relativePath,
).fsPath

return existsSync(fullPath) ? { filePath: fullPath, 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) return []

const apps: AppDefinition[] = []

for (const folder of workspaceFolders) {
const config = vscode.workspace.getConfiguration("fastapi", folder.uri)
const customEntryPoint = config.get<string>("entryPoint")

let candidates: EntryPoint[]

if (customEntryPoint) {
const entryPath = isAbsolute(customEntryPoint)
? customEntryPoint
: vscode.Uri.joinPath(folder.uri, customEntryPoint).fsPath

if (!existsSync(entryPath)) {
vscode.window.showWarningMessage(
`FastAPI entry point not found: ${customEntryPoint}`,
)
continue
}

candidates = [{ filePath: entryPath }]
} else {
const pyprojectEntry = await parsePyprojectForEntryPoint(
folder.uri.fsPath,
)
candidates = pyprojectEntry
? [pyprojectEntry]
: (await automaticDetectEntryPoints(folder.uri.fsPath)).map(
(filePath) => ({ filePath }),
)
}

for (const candidate of candidates) {
const projectRoot = findProjectRoot(candidate.filePath, folder.uri.fsPath)
const routerNode = buildRouterGraph(
candidate.filePath,
parser,
projectRoot,
candidate.variableName,
)

if (routerNode) {
apps.push(routerNodeToAppDefinition(routerNode, folder.uri.fsPath))
break
}
}
}

return apps
}
5 changes: 5 additions & 0 deletions src/core/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,8 @@ export interface RouterNode {
}[]
children: { router: RouterNode; prefix: string; tags: string[] }[]
}

export interface EntryPoint {
filePath: string
variableName?: string
}
26 changes: 21 additions & 5 deletions src/core/routerResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,16 @@ export type { RouterNode }

/**
* Finds the main FastAPI app or APIRouter in the list of routers.
* We want to prioritize FastAPI apps over APIRouters.
* If targetVariable is specified, only returns the router with that variable name.
* Otherwise, prioritizes FastAPI apps over APIRouters.
*/
function findAppRouter(routers: RouterInfo[]): RouterInfo | undefined {
function findAppRouter(
routers: RouterInfo[],
targetVariable?: string,
): RouterInfo | undefined {
if (targetVariable) {
return routers.find((r) => r.variableName === targetVariable)
}
return (
routers.find((r) => r.type === "FastAPI") ??
routers.find((r) => r.type === "APIRouter")
Expand All @@ -20,13 +27,21 @@ function findAppRouter(routers: RouterInfo[]): RouterInfo | undefined {

/**
* Builds a router graph starting from the given entry file.
* If targetVariable is specified, only that specific app/router will be used.
*/
export function buildRouterGraph(
entryFile: string,
parser: Parser,
projectRoot: string,
targetVariable?: string,
): RouterNode | null {
return buildRouterGraphInternal(entryFile, parser, projectRoot, new Set())
return buildRouterGraphInternal(
entryFile,
parser,
projectRoot,
new Set(),
targetVariable,
)
}

/**
Expand All @@ -37,6 +52,7 @@ function buildRouterGraphInternal(
parser: Parser,
projectRoot: string,
visited: Set<string>,
targetVariable?: string,
): RouterNode | null {
// Resolve the full path of the entry file if necessary
let resolvedEntryFile = entryFile
Expand All @@ -61,8 +77,8 @@ function buildRouterGraphInternal(
return null
}

// Find FastAPI instantiation
let appRouter = findAppRouter(analysis.routers)
// Find FastAPI instantiation (filter by targetVariable if specified)
let appRouter = findAppRouter(analysis.routers, targetVariable)

// If no FastAPI/APIRouter found and this is an __init__.py, check for re-exports
if (!appRouter && resolvedEntryFile.endsWith("__init__.py")) {
Expand Down
Loading