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
54 changes: 34 additions & 20 deletions src/appDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,35 +80,49 @@ async function findAllFastAPIFiles(
async function parsePyprojectForEntryPoint(
folderUri: vscode.Uri,
): Promise<EntryPoint | null> {
const pyprojectUri = vscode.Uri.joinPath(folderUri, "pyproject.toml")
const pyprojectTomlFiles = await vscode.workspace.findFiles(
new vscode.RelativePattern(folderUri, "**/pyproject.toml"),
new vscode.RelativePattern(
folderUri,
"**/{.venv,venv,__pycache__,node_modules,.git,tests,test}/**",
),
)

if (!(await vscodeFileSystem.exists(pyprojectUri.toString()))) {
if (pyprojectTomlFiles.length === 0) {
return null
}

try {
const document = await vscode.workspace.openTextDocument(pyprojectUri)
const contents = toml.parse(document.getText()) as Record<string, unknown>
pyprojectTomlFiles.sort(
(a, b) => a.path.split("/").length - b.path.split("/").length,
)

const entrypoint = (contents.tool as Record<string, unknown> | undefined)
?.fastapi as Record<string, unknown> | undefined
const entrypointValue = entrypoint?.entrypoint as string | undefined
for (const fileUri of pyprojectTomlFiles) {
try {
const document = await vscode.workspace.openTextDocument(fileUri)
const contents = toml.parse(document.getText()) as Record<string, unknown>

if (!entrypointValue) {
return null
}
const entrypoint = (contents.tool as Record<string, unknown> | undefined)
?.fastapi as Record<string, unknown> | undefined
const entrypointValue = entrypoint?.entrypoint as string | undefined

const { relativePath, variableName } =
parseEntrypointString(entrypointValue)
const fullUri = vscode.Uri.joinPath(folderUri, relativePath)
if (!entrypointValue) {
continue
}

return (await vscodeFileSystem.exists(fullUri.toString()))
? { filePath: fullUri.toString(), variableName }
: null
} catch {
// Invalid TOML syntax - silently fall back to auto-detection
return null
const { relativePath, variableName } =
parseEntrypointString(entrypointValue)
const dirUri = vscode.Uri.joinPath(fileUri, "..")
const fullUri = vscode.Uri.joinPath(dirUri, relativePath)

return (await vscodeFileSystem.exists(fullUri.toString()))
? { filePath: fullUri.toString(), variableName }
: null
} catch {
// Invalid TOML syntax - silently fall back to next file
}
}

return null
}

/**
Expand Down
21 changes: 16 additions & 5 deletions src/core/pathUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,8 @@ export function pathMatchesPathOperation(
}

/**
* Finds the Python project root by walking up from the entry file
* until we find a directory without __init__.py (or hit the workspace root).
* This is the directory from which absolute imports are resolved.
* Finds the Python project root (the directory from which absolute imports
* are resolved) by walking up from the entry file toward the workspace root.
*/
export async function findProjectRoot(
entryUri: string,
Expand All @@ -154,12 +153,24 @@ export async function findProjectRoot(
): Promise<string> {
let dirUri = uriDirname(entryUri)

// If the entry file's directory doesn't have __init__.py, it's a top-level script
// No __init__.py — could be a namespace package. Walk up toward the
// workspace root to find a pyproject.toml; if found, that directory is
// the Python project root. Otherwise fall back to the entry dir.
if (!(await fs.exists(fs.joinPath(dirUri, "__init__.py")))) {
let searchDir = dirUri
while (isWithinDirectory(searchDir, workspaceRootUri)) {
if (await fs.exists(fs.joinPath(searchDir, "pyproject.toml"))) {
return searchDir
}
if (uriPath(searchDir) === uriPath(workspaceRootUri)) break
searchDir = uriDirname(searchDir)
}
return dirUri
}

// Walk up until we find a directory whose parent doesn't have __init__.py
// __init__.py is present, so this is a traditional package. Walk up until
// we find a directory whose parent doesn't have __init__.py — that parent
// is the project root (the directory Python adds to sys.path).
while (
isWithinDirectory(dirUri, workspaceRootUri) &&
uriPath(dirUri) !== uriPath(workspaceRootUri)
Expand Down
11 changes: 11 additions & 0 deletions src/test/core/pathUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,17 @@ suite("pathUtils", () => {

assert.strictEqual(result, appRootUri)
})

test("returns pyproject.toml dir for namespace packages in a monorepo", async () => {
// myapp/ has no __init__.py (namespace package), but service/ has pyproject.toml
const result = await findProjectRoot(
fixtures.monorepo.mainPy,
fixtures.monorepo.workspaceRoot,
nodeFileSystem,
)

assert.strictEqual(result, fixtures.monorepo.projectRoot)
})
})

suite("pathMatchesPathOperation", () => {
Expand Down
21 changes: 21 additions & 0 deletions src/test/core/routerResolver.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as assert from "node:assert"
import { Parser } from "../../core/parser"
import { findProjectRoot } from "../../core/pathUtils"
import { buildRouterGraph } from "../../core/routerResolver"
import {
fixtures,
Expand Down Expand Up @@ -517,5 +518,25 @@ suite("routerResolver", () => {
"neon router should have routes",
)
})

test("resolves imports in a monorepo with pyproject.toml in a subdirectory", async () => {
const projectRoot = await findProjectRoot(
fixtures.monorepo.mainPy,
fixtures.monorepo.workspaceRoot,
nodeFileSystem,
)
const result = await buildRouterGraph(
fixtures.monorepo.mainPy,
parser,
projectRoot,
nodeFileSystem,
)

assert.ok(result)
assert.strictEqual(result.type, "FastAPI")
assert.strictEqual(result.children.length, 1)
assert.strictEqual(result.children[0].router.prefix, "/users")
assert.ok(result.children[0].router.routes.length >= 2)
})
})
})
7 changes: 7 additions & 0 deletions src/test/fixtures/monorepo/service/myapp/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from fastapi import FastAPI

from myapp.users.router import router as users_router

app = FastAPI()

app.include_router(users_router)
13 changes: 13 additions & 0 deletions src/test/fixtures/monorepo/service/myapp/users/router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from fastapi import APIRouter

router = APIRouter(prefix="/users", tags=["users"])


@router.get("/")
def list_users():
return []


@router.get("/{user_id}")
def get_user(user_id: int):
return {"id": user_id}
Empty file.
5 changes: 5 additions & 0 deletions src/test/testUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ export const fixtures = {
join(fixturesPath, "nested-router", "app", "routes", "settings.py"),
),
},
monorepo: {
workspaceRoot: uri(join(fixturesPath, "monorepo")),
projectRoot: uri(join(fixturesPath, "monorepo", "service")),
mainPy: uri(join(fixturesPath, "monorepo", "service", "myapp", "main.py")),
},
}

/**
Expand Down
Loading