From 9d92f47f94ffec3d9ea168ac34ca1c045d216da9 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sat, 28 Nov 2026 21:31:33 +0900 Subject: [PATCH] fix(python): address the review of the Django PRs #6542-#6545 (#6656) Follow-up fixes to the Django support: - manage.py tasks: manage.py is looked up on each use and only a successful command list is cached; lines run while help loads go to manage.py; a failed help is reported; the active file's project picks the manage.py in a monorepo (shared via platform/django.ts); py/python3.x/Windows forms count as manage.py lines. - Django console: keeps the project root as working directory with manage.py's folder on sys.path, reads setdefault and os.environ[...] settings forms, and shows auto-imported names once reassigned. - URL names: re-reading names clears navigation's cache, names nest under include namespaces, and only path/re_path/url name= counts (small Python scanner). - Field lookups: models keyed per app, multi-table inheritance reverse names fixed, related_query_name/related_name/%(class)s rules, relation lookups and _id, completion in Q(...) and after F(...). Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/features/django/index.ts | 16 +- src/features/django/load.test.ts | 118 ++++++++ src/features/django/manage.test.ts | 15 +- src/features/django/manage.ts | 139 +++++++--- src/features/django/models.test.ts | 159 ++++++++--- src/features/django/models.ts | 290 +++++++++++++++----- src/features/django/pyscan.ts | 109 ++++++++ src/features/django/stubs.test.ts | 98 ++++++- src/features/django/stubs.ts | 41 ++- src/features/django/urls.test.ts | 117 ++++++-- src/features/django/urls.ts | 134 ++++++--- src/features/python-console/console.py | 21 +- src/features/python-console/console.test.ts | 79 ++++-- src/features/python-console/store.test.ts | 7 + src/features/python-console/store.ts | 26 +- src/platform/django.test.ts | 18 ++ src/platform/django.ts | 23 ++ src/platform/locales/text/en.json | 5 +- src/platform/locales/text/zh.json | 5 +- 19 files changed, 1158 insertions(+), 262 deletions(-) create mode 100644 src/features/django/load.test.ts create mode 100644 src/features/django/pyscan.ts create mode 100644 src/platform/django.test.ts create mode 100644 src/platform/django.ts diff --git a/src/features/django/index.ts b/src/features/django/index.ts index e38ad42ba..df07dc80a 100644 --- a/src/features/django/index.ts +++ b/src/features/django/index.ts @@ -5,7 +5,7 @@ import { executeAction, registerActions } from "@/platform/actions"; import { onIdeEvent, type RunConfig } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { notifications, registerEditorBanner, registerRunAnythingProvider } from "@/workbench/contributions"; -import { loadManage, locateManage, manageRunAnything, resetManage, useManage } from "./manage"; +import { loadCommands, locateManage, manageRunAnything, resetManage } from "./manage"; import { forgetModels, lookupCompletionExtension } from "./models"; import { checkStubs, resetStubs, useStubs, useStubsBanner } from "./stubs"; import { forgetUrlNames, urlCompletionExtension, urlNavigation } from "./urls"; @@ -32,11 +32,13 @@ export function activate(): () => void { keywords: ["django", "manage.py", "migrate", "makemigrations"], when: "projectOpen", run: async () => { - await loadManage(); - if (!useManage.getState().manage) { + const { manage, python } = await locateManage(); + if (!manage) { notifications().notify({ level: "info", title: "No manage.py in this project" }); return; } + // The commands complete once `manage.py help` answers; a failed one is tried again. + if (python) void loadCommands(manage, python, true); await executeAction("runAnything.show", "manage.py "); }, }, @@ -45,7 +47,9 @@ export function activate(): () => void { const doc = docOf(view); if (!doc || doc.virtual || doc.language !== "python") return null; const line = view.state.doc.lineAt(offset); - return urlNavigation(line.text, line.from, offset); + // With what comes before the line: `reverse(` may end the one above. + const base = Math.max(0, line.from - 200); + return urlNavigation(view.state.doc.sliceString(base, line.to), base, offset); }), registerEditorContribution({ id: "django.urlNames", extensions: urlCompletionExtension }), registerEditorContribution({ id: "django.lookups", extensions: lookupCompletionExtension }), @@ -58,12 +62,12 @@ export function activate(): () => void { // A fresh open races the index: manage.py, urls.py and models.py may be there once indexing ends. onIdeEvent("indexState", (e) => { if (e.indexing) return; - const { loaded, manage } = useManage.getState(); - if (loaded === "yes" && !manage) resetManage(); forgetUrlNames(); forgetModels(); if (!useStubs.getState().python) void checkProject(); }), + // Another interpreter for the project. + onIdeEvent("settingsChanged", (e) => e.key.startsWith("languages.python") && void checkProject()), useProject.subscribe((s, prev) => { if (s.project?.root === prev.project?.root) return; resetManage(); diff --git a/src/features/django/load.test.ts b/src/features/django/load.test.ts new file mode 100644 index 000000000..26beeba48 --- /dev/null +++ b/src/features/django/load.test.ts @@ -0,0 +1,118 @@ +// The manage.py lookup and `manage.py help` with IPC mocked: nothing failed is cached, a line +// runs without waiting for the command list, and a reset drops what an earlier project read. +import { beforeEach, expect, it, vi } from "vitest"; +import type { OutputChunk } from "@/platform/ipc"; + +const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); +const ipc = vi.hoisted(() => ({ + files: [] as string[], + helps: [] as Array<{ channel: { onmessage?: (c: OutputChunk) => void }; exit: () => void }>, + exited: (_e: { run: number }) => {}, + notify: vi.fn(), + active: null as string | null, +})); + +vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} })); +vi.mock("@/workbench/contributions", () => ({ + maybeEditorService: () => ({ activePath: () => ipc.active }), + notifications: () => ({ notify: ipc.notify }), +})); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + let id = 0; + return { + ...real, + ideEventsReady: () => Promise.resolve(), + onIdeEvent: (_type: string, handler: typeof ipc.exited) => { + ipc.exited = handler; + return () => {}; + }, + commands: { + findFilesNamed: () => ok(ipc.files), + sdkPythonEffective: (dir: string) => ok(`${dir}/.venv/bin/python`), + runStop: () => ok(null), + runStart: (_config: unknown, channel: (typeof ipc.helps)[number]["channel"]) => { + const run = ++id; + ipc.helps.push({ channel, exit: () => ipc.exited({ run }) }); + return ok({ id: run }); + }, + }, + }; +}); + +const { loadCommands, locateManage, manageRunAnything, resetManage, runManageLine, useManage } = + await import("./manage"); + +const HELP = "Available subcommands:\n\n[django]\n check\n migrate\n"; +const answer = async (text: string, kind: "stdout" | "stderr" = "stdout") => { + await vi.waitFor(() => expect(ipc.helps.length).toBeGreaterThan(0)); + const help = ipc.helps.shift()!; + help.channel.onmessage?.({ kind, text }); + help.exit(); +}; + +beforeEach(() => { + resetManage(); + ipc.files = ["/p/manage.py"]; + ipc.helps = []; + ipc.active = null; + ipc.notify.mockClear(); +}); + +it("looks manage.py up again when the index had none yet", async () => { + ipc.files = []; + expect(await runManageLine("manage.py migrate", () => {})).toBe(false); + ipc.files = ["/p/manage.py"]; + const run = vi.fn(); + expect(await runManageLine("manage.py migrate", run)).toBe(true); + expect(run.mock.calls[0]![0]).toMatchObject({ args: ["manage.py", "migrate"], cwd: "/p" }); +}); + +it("runs a line while the command list is still being read", async () => { + const at = await locateManage(); + void loadCommands(at.manage!, at.python!); + const run = vi.fn(); + expect(await runManageLine("manage.py check", run)).toBe(true); + expect(run).toHaveBeenCalledOnce(); + await answer(HELP); + await vi.waitFor(() => expect(useManage.getState().commands["/p/manage.py"]).toHaveLength(2)); +}); + +it("uses the manage.py of the active file's project", async () => { + ipc.files = ["/p/a/manage.py", "/p/b/manage.py"]; + ipc.active = "/p/b/shop/views.py"; + expect((await locateManage()).manage).toBe("/p/b/manage.py"); +}); + +it("looks manage.py up again in Run Anything when another project's file is active", async () => { + ipc.files = ["/p/a/manage.py", "/p/b/manage.py"]; + ipc.active = "/p/a/x.py"; + expect((await locateManage()).manage).toBe("/p/a/manage.py"); + ipc.active = "/p/b/x.py"; + manageRunAnything(() => {}).items("manage.py "); + await vi.waitFor(() => expect(useManage.getState().manage).toBe("/p/b/manage.py")); +}); + +it("reports a failed help and reads it again only when asked", async () => { + const read = loadCommands("/p/manage.py", "/py"); + await answer("Traceback…\nModuleNotFoundError: No module named 'django'\n", "stderr"); + await read; + expect(ipc.notify).toHaveBeenCalledWith( + expect.objectContaining({ title: "Cannot list the manage.py commands", body: expect.stringContaining("django") }), + ); + await loadCommands("/p/manage.py", "/py"); + expect(ipc.helps).toHaveLength(0); + const again = loadCommands("/p/manage.py", "/py", true); + await answer(HELP); + await again; + expect(useManage.getState().commands["/p/manage.py"]).toHaveLength(2); + expect(useManage.getState().failed).toEqual({}); +}); + +it("drops what a load for the previous project read", async () => { + const read = loadCommands("/old/manage.py", "/py"); + resetManage(); + await answer(HELP); + await read; + expect(useManage.getState().commands).toEqual({}); +}); diff --git a/src/features/django/manage.test.ts b/src/features/django/manage.test.ts index a6907b58c..5f3825099 100644 --- a/src/features/django/manage.test.ts +++ b/src/features/django/manage.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { commandItems, manageArgs, manageConfig, parseHelp, pickManage } from "./manage"; +import { commandItems, manageArgs, manageConfig, parseHelp } from "./manage"; const HELP = ` Type 'manage.py help ' for help on a specific subcommand. @@ -37,17 +37,16 @@ describe("manage.py tasks", () => { expect(manageArgs("manage.py migrate polls 0001")).toEqual(["migrate", "polls", "0001"]); expect(manageArgs("python manage.py shell -c 'print(1)'")).toEqual(["shell", "-c", "print(1)"]); expect(manageArgs("./manage.py ")).toEqual([]); + expect(manageArgs("py manage.py check")).toEqual(["check"]); + expect(manageArgs("python3.12 manage.py check")).toEqual(["check"]); + expect(manageArgs("py -3.12 manage.py check")).toEqual(["check"]); + expect(manageArgs("python.exe .\\manage.py check", true)).toEqual(["check"]); + // Windows: backslashes in paths stay. + expect(manageArgs("manage.py loaddata C:\\x\\a.json", true)).toEqual(["loaddata", "C:\\x\\a.json"]); expect(manageArgs("manage.pyx migrate")).toBeNull(); expect(manageArgs("ls")).toBeNull(); }); - it("picks the project's own manage.py", () => { - expect( - pickManage(["/p/.venv/lib/python3.12/site-packages/x/manage.py", "/p/site/sub/manage.py", "/p/site/manage.py"]), - ).toBe("/p/site/manage.py"); - expect(pickManage([])).toBeNull(); - }); - it("runs the line in manage.py's directory in a terminal", () => { const c = manageConfig("/p/.venv/bin/python", "/p/site/manage.py", ["migrate", "--plan"]); expect(c).toMatchObject({ diff --git a/src/features/django/manage.ts b/src/features/django/manage.ts index a4fe70718..5843d4e25 100644 --- a/src/features/django/manage.ts +++ b/src/features/django/manage.ts @@ -16,8 +16,15 @@ import { type RunConfig, type RunId, } from "@/platform/ipc"; +import { findManage } from "@/platform/django"; +import { usePlatform } from "@/platform/platformInfo"; import { dirname } from "@/platform/project"; -import type { RunAnythingItem, RunAnythingProvider } from "@/workbench/contributions"; +import { + maybeEditorService, + notifications, + type RunAnythingItem, + type RunAnythingProvider, +} from "@/workbench/contributions"; export interface ManageCommand { name: string; @@ -28,13 +35,13 @@ export interface ManageCommand { /** The script name, as typed in command lines. */ const MANAGE = "manage.py"; -/** `manage.py migrate`, `./manage.py migrate`, `python manage.py migrate`. */ -const LINE = /^(?:python3?\s+)?(?:\.\/)?manage\.py(?:\s+|$)/; +/** `manage.py migrate`, `./manage.py` / `.\manage.py`, `python`, `python3.12`, `python.exe`, `py`, `py -3.12`. */ +const LINE = /^(?:(?:py(?:\s+-[\d.]+)?|python[\d.]*(?:\.exe)?)\s+)?(?:\.[\\/])?manage\.py(?:\s+|$)/; /** The arguments after `manage.py`, or null when `line` isn't a manage.py command line. */ -export function manageArgs(line: string): string[] | null { +export function manageArgs(line: string, windows = usePlatform.getState().os === "windows"): string[] | null { const head = LINE.exec(line.trim()); - return head ? parseArgs(line.trim().slice(head[0].length)) : null; + return head ? parseArgs(line.trim().slice(head[0].length), windows) : null; } /** Commands listed by `manage.py help`: `[app]` headings, each followed by indented command names. */ @@ -50,12 +57,6 @@ export function parseHelp(text: string): ManageCommand[] { return out; } -/** The project's `manage.py`: the shallowest one outside installed packages. */ -export function pickManage(paths: readonly string[]): string | null { - const own = paths.filter((p) => !/\/(?:site-packages|node_modules|\.venv|venv)\//.test(p)); - return own.sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b))[0] ?? null; -} - export function manageConfig(python: string, manage: string, args: readonly string[]): RunConfig { const line = ["manage.py", ...args].join(" "); return { @@ -75,22 +76,34 @@ export function manageConfig(python: string, manage: string, args: readonly stri } interface ManageState { + /** The manage.py (and its interpreter) the last lookup found. */ manage: string | null; python: string | null; - commands: ManageCommand[]; - /** Commands are read once per project, on the first manage.py line. */ - loaded: "no" | "loading" | "yes"; + /** Commands by manage.py, read once each. */ + commands: Record; + /** manage.py files whose `help` failed: not read again until Run manage.py Task asks. */ + failed: Record; } -export const useManage = create(() => ({ manage: null, python: null, commands: [], loaded: "no" })); +const empty = (): ManageState => ({ manage: null, python: null, commands: {}, failed: {} }); +export const useManage = create(empty); -export const resetManage = () => useManage.setState({ manage: null, python: null, commands: [], loaded: "no" }); +/** Bumped by each reset: work started for an earlier project doesn't write into the store. */ +let epoch = 0; +const reading = new Map>(); -/** Stdout of a short process on the Run process host (no Run tab). */ -async function capture(config: RunConfig, timeoutMs = 30_000): Promise { +export function resetManage() { + epoch++; + reading.clear(); + useManage.setState(empty()); +} + +/** Output of a short process on the Run process host (no Run tab). */ +async function capture(config: RunConfig, timeoutMs = 30_000): Promise<{ out: string; err: string }> { await ideEventsReady(); let id: RunId | undefined; let out = ""; + let err = ""; const exits = new Set(); let finish!: () => void; const exited = new Promise((resolve) => (finish = resolve)); @@ -101,50 +114,77 @@ async function capture(config: RunConfig, timeoutMs = 30_000): Promise { const channel = new Channel(); channel.onmessage = (chunk) => { if (chunk.kind === "stdout" && out.length < 1_000_000) out += chunk.text; + if (chunk.kind === "stderr" && err.length < 100_000) err += chunk.text; }; const timer = setTimeout(() => id !== undefined && void call(commands.runStop(id)).catch(() => {}), timeoutMs); try { id = (await call(commands.runStart(config, channel, null))).id; if (exits.has(id)) finish(); await exited; - return out; + return { out, err }; } finally { clearTimeout(timer); off(); } } -/** The project's manage.py and the interpreter it runs with. */ +/** The file the lookup starts from: the active editor's, so a monorepo uses that project's manage.py. */ +const near = () => maybeEditorService()?.activePath() ?? null; +/** The file the last lookup started from: another active file may belong to another project. */ +let lookedUpFrom: string | null = null; + +/** The manage.py of the active file's project and its interpreter (looked up each time: the index may still be building). */ export async function locateManage(): Promise<{ manage: string | null; python: string | null }> { - const manage = pickManage((await call(commands.findFilesNamed("manage.py"))).map(String)); - const python = manage && (await call(commands.sdkPythonEffective(dirname(manage)))); - return { manage, python: python || null }; -} - -/** Finds manage.py and the interpreter, then lists the commands (each once per project). */ -export async function loadManage(): Promise { - if (useManage.getState().loaded !== "no") return; - useManage.setState({ loaded: "loading" }); - try { - const { manage, python } = await locateManage(); + const mine = epoch; + const from = near(); + const manage = await findManage(from); + const python = (manage && (await call(commands.sdkPythonEffective(dirname(manage))))) || null; + if (mine === epoch) { + lookedUpFrom = from; useManage.setState({ manage, python }); - if (manage && python) { - const config = { ...manageConfig(python, manage, ["help"]), id: `django.manage.help:${crypto.randomUUID()}` }; - useManage.setState({ commands: parseHelp(await capture({ ...config, emulateTerminal: false })) }); - } - } catch (e) { - console.warn("manage.py help failed", e); - } finally { - if (useManage.getState().loaded === "loading") useManage.setState({ loaded: "yes" }); } + return { manage, python }; } -/** Runs a manage.py line in the Run tool window; false when it isn't one or there's no manage.py. */ +/** Reads the commands of `manage` with `manage.py help`, once (again after a failure only with `retry`). */ +export function loadCommands(manage: string, python: string, retry = false): Promise { + const s = useManage.getState(); + if (s.commands[manage] || (s.failed[manage] && !retry)) return Promise.resolve(); + const pending = reading.get(manage); + if (pending) return pending; + const mine = epoch; + const config = { ...manageConfig(python, manage, ["help"]), id: `django.manage.help:${crypto.randomUUID()}` }; + const read = capture({ ...config, emulateTerminal: false }) + .then(({ out, err }) => { + if (mine !== epoch) return; + const list = parseHelp(out); + useManage.setState((st) => { + const failed = { ...st.failed }; + delete failed[manage]; + if (list.length) return { commands: { ...st.commands, [manage]: list }, failed }; + return { failed: { ...failed, [manage]: true } }; + }); + if (!list.length) + notifications().notify({ + level: "warning", + title: "Cannot list the manage.py commands", + body: err.trim().split("\n").slice(-5).join("\n") || undefined, + key: `django.manage.help:${manage}`, + }); + }) + .catch((e) => console.warn("manage.py help failed", e)) + .finally(() => { + if (reading.get(manage) === read) reading.delete(manage); + }); + reading.set(manage, read); + return read; +} + +/** Runs a manage.py line in the Run tool window (not waiting for the command list); false when it isn't one or there's no manage.py. */ export async function runManageLine(line: string, run: (config: RunConfig) => unknown): Promise { const args = manageArgs(line); if (!args) return false; - await loadManage(); - const { manage, python } = useManage.getState(); + const { manage, python } = await locateManage(); if (!manage || !python) return false; await run(manageConfig(python, manage, args)); return true; @@ -172,6 +212,8 @@ export function commandItems( })); } +let locating: Promise | null = null; + export function manageRunAnything(run: (config: RunConfig) => unknown): RunAnythingProvider { return { id: "django.manage", @@ -179,10 +221,17 @@ export function manageRunAnything(run: (config: RunConfig) => unknown): RunAnyth order: 25, items(query) { if (!manageArgs(query)) return []; - void loadManage(); - return commandItems(query, useManage.getState().commands, (line) => void runManageLine(line, run)); + const { manage, python, commands: lists } = useManage.getState(); + if (!manage || !python || near() !== lookedUpFrom) { + // One lookup at a time while typing; the rows come when it (and `help`) answers. + locating ??= locateManage() + .then((at) => void (at.manage && at.python && loadCommands(at.manage, at.python))) + .finally(() => (locating = null)); + } else void loadCommands(manage, python); + return commandItems(query, (manage && lists[manage]) || [], (line) => void runManageLine(line, run)); }, execute: (line) => runManageLine(line, run), - subscribe: (listener) => useManage.subscribe((s, prev) => s.commands !== prev.commands && listener()), + subscribe: (listener) => + useManage.subscribe((s, prev) => (s.commands !== prev.commands || s.manage !== prev.manage) && listener()), }; } diff --git a/src/features/django/models.test.ts b/src/features/django/models.test.ts index b94349a3a..80fbd9883 100644 --- a/src/features/django/models.test.ts +++ b/src/features/django/models.test.ts @@ -1,11 +1,26 @@ -import { describe, expect, it } from "vitest"; -import { lookupAt, lookupOptions, modelFields, parseModels } from "./models"; +import { CompletionContext } from "@codemirror/autocomplete"; +import { EditorState } from "@codemirror/state"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -const MODELS = `from django.db import models +const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); +const ipc = vi.hoisted(() => ({ files: {} as Record })); +vi.mock("@/platform/ipc", async (importOriginal) => ({ + ...(await importOriginal()), + commands: { + findFilesNamed: () => ok(Object.keys(ipc.files)), + fsReadText: (path: string) => ok(ipc.files[path]), + }, +})); + +const { forgetModels, lookupAt, lookupCompletion, lookupOptions, modelFields, parseModels, projectModels } = + await import("./models"); + +const SHOP = `from django.db import models class Stamped(models.Model): created = models.DateTimeField(auto_now_add=True) + owner = models.ForeignKey("blog.Author", related_name="%(class)s_items", on_delete=models.CASCADE) class Meta: abstract = True @@ -13,60 +28,138 @@ class Stamped(models.Model): class Category(Stamped): name = models.CharField(max_length=50) - parent = models.ForeignKey("self", null=True, on_delete=models.CASCADE) +# a comment at column 0 doesn't end the class + parent = models.ForeignKey( + "self", + null=True, + on_delete=models.CASCADE, + ) class Coffee(Stamped): name: str = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) category = models.ForeignKey(Category, related_name="coffees", on_delete=models.CASCADE) - roaster = models.ForeignKey("shop.Roaster", on_delete=models.CASCADE) - - def __str__(self): - return self.name + tags = models.ManyToManyField("Tag", related_name="+") + roaster = models.ForeignKey("blog.Author", related_query_name="roasted", on_delete=models.CASCADE) -class Roaster(models.Model): +class Tag(models.Model): + label = models.CharField(max_length=10) +`; +const BLOG = `from django.db import models + + +class Author(models.Model): name = models.CharField(max_length=50) + + +class Tag(models.Model): + slug = models.SlugField() `; -const fields = modelFields(parseModels(MODELS)); -const labels = (model: string, path: string[]) => lookupOptions(fields, model, path).map((o) => o.label); +const fields = modelFields([...parseModels(SHOP, "shop"), ...parseModels(BLOG, "blog")]); +const labels = (key: string, path: string[]) => lookupOptions(fields, key, path).map((o) => o.label); describe("Django field lookups", () => { - it("reads model fields, relations and inherited fields", () => { - expect(parseModels(MODELS).find((m) => m.name === "Coffee")?.fields).toEqual([ - { name: "name", type: "CharField" }, - { name: "price", type: "DecimalField" }, - { name: "category", type: "ForeignKey", to: "Category", related: "coffees" }, - { name: "roaster", type: "ForeignKey", to: "Roaster" }, + it("reads fields: annotated, multi-line, any indentation, past a comment at column 0", () => { + const shop = parseModels(SHOP, "shop"); + expect(shop.map((m) => [m.key, m.abstract])).toEqual([ + ["shop.Stamped", true], + ["shop.Category", false], + ["shop.Coffee", false], + ["shop.Tag", false], ]); - expect(labels("Coffee", [])).toEqual(["pk", "id", "created", "name", "price", "category", "roaster"]); - // Reverse relations: related_name, else the model's lowercase name; "self" is the model itself. - expect(labels("Category", [])).toEqual(["pk", "id", "created", "name", "parent", "category", "coffees"]); - expect(labels("Roaster", [])).toContain("coffee"); + expect(shop[1]!.fields).toEqual([ + { name: "name", type: "CharField" }, + { name: "parent", type: "ForeignKey", to: "self" }, + ]); + expect(labels("shop.Tag", [])).toEqual(["pk", "id", "label"]); }); - it("follows relations and offers lookups after a plain field", () => { - expect(labels("Coffee", ["category"])).toContain("parent"); - expect(labels("Coffee", ["category", "coffees", "roaster"])).toContain("name"); - expect(labels("Coffee", ["name"])).toContain("icontains"); - expect(labels("Coffee", ["created"])).toEqual(expect.arrayContaining(["year", "hour", "gte"])); - expect(labels("Coffee", ["price"])).not.toContain("year"); - expect(labels("Coffee", ["nope"])).toEqual([]); - expect(labels("Unknown", [])).toEqual([]); + it("offers inherited fields, _id, and reverse relations by their query name", () => { + expect(labels("shop.Coffee", [])).toEqual([ + "pk", + "id", + "created", + "owner", + "owner_id", + "name", + "price", + "category", + "category_id", + "tags", + "roaster", + "roaster_id", + ]); + // related_name, "%(class)s" per concrete model, related_query_name; none for "+" nor for the abstract model. + expect(labels("shop.Category", [])).toContain("coffees"); + expect(labels("blog.Author", [])).toEqual(["pk", "id", "name", "category_items", "coffee_items", "roasted"]); + expect(labels("shop.Tag", [])).not.toContain("coffee"); }); - it("finds the keyword being typed in a Model.objects query", () => { + it("points a concrete parent's relations back from the parent alone (multi-table inheritance)", () => { + const mti = modelFields( + parseModels( + `class User(models.Model):\n name = models.CharField()\n\n\nclass Place(models.Model):\n owner = models.ForeignKey(User, related_name="places", on_delete=models.CASCADE)\n host = models.ForeignKey(User, on_delete=models.CASCADE)\n\n\nclass Restaurant(Place):\n stars = models.IntegerField()\n`, + "a", + ), + ); + expect( + mti + .get("a.User")! + .filter((f) => f.type === "reverse") + .map((f) => f.name), + ).toEqual(["places", "place"]); + // The child still queries the parent's fields. + expect(lookupOptions(mti, "a.Restaurant", []).map((o) => o.label)).toContain("owner"); + }); + + it("resolves models per app", () => { + // "Tag" in shop's models is shop's own Tag, not blog's. + expect(labels("shop.Coffee", ["tags"])).toContain("label"); + expect(labels("shop.Coffee", ["owner"])).toContain("name"); + }); + + it("offers lookups after a field and after a relation", () => { + expect(labels("shop.Coffee", ["category"])).toEqual(expect.arrayContaining(["parent", "isnull", "in", "exact"])); + expect(labels("shop.Coffee", ["category", "coffees", "price"])).toContain("gte"); + expect(labels("shop.Coffee", ["name"])).toContain("icontains"); + expect(labels("shop.Coffee", ["created"])).toEqual(expect.arrayContaining(["year", "hour", "gte"])); + expect(labels("shop.Coffee", ["price"])).not.toContain("year"); + expect(labels("shop.Coffee", ["nope"])).toEqual([]); + }); + + it("finds the keyword being typed in a query, Q() included", () => { expect(lookupAt(`qs = Coffee.objects.filter(`)).toEqual({ model: "Coffee", path: [], word: "" }); - expect(lookupAt(`Coffee.objects.exclude(price__gt=1).filter(name="x", category__na`)).toEqual({ + expect(lookupAt(`Coffee.objects.exclude(Q(price__gt=1)).filter(name="x", category__na`)).toEqual({ model: "Coffee", path: ["category"], word: "na", }); - expect(lookupAt(`Coffee.objects.get(name__`)).toEqual({ model: "Coffee", path: ["name"], word: "" }); - // A value, not a keyword. + expect(lookupAt(`Coffee.objects.filter(Q(name="a") | Q(tags__`)).toMatchObject({ path: ["tags"] }); + expect(lookupAt(`Coffee.objects.filter(name=F("x"), pr`)).toMatchObject({ word: "pr" }); + expect(lookupAt(`Coffee.objects.all().get(\n name__`)).toMatchObject({ path: ["name"] }); + // A value, a string, and not a query. expect(lookupAt(`Coffee.objects.filter(name=na`)).toBeNull(); + expect(lookupAt(`Coffee.objects.filter(name="a, b`)).toBeNull(); expect(lookupAt(`coffees.filter(name`)).toBeNull(); + expect(lookupAt(`print(Q(name`)).toBeNull(); + }); +}); + +describe("project models", () => { + beforeEach(forgetModels); + + it("asks the index again when it had no models.py yet, and completes the whole keyword", async () => { + ipc.files = {}; + expect((await projectModels()).size).toBe(0); + await Promise.resolve(); + ipc.files = { "/p/shop/models.py": SHOP, "/p/blog/models.py": BLOG }; + expect((await projectModels()).has("shop.Coffee")).toBe(true); + const state = EditorState.create({ doc: `Coffee.objects.filter(category__na` }); + const result = await lookupCompletion("/p/shop/views.py")(new CompletionContext(state, state.doc.length, true)); + expect(result?.from).toBe(22); + expect(result?.options.map((o) => o.label)).toContain("category__name"); }); }); diff --git a/src/features/django/models.ts b/src/features/django/models.ts index a81a38e12..63f72d6c6 100644 --- a/src/features/django/models.ts +++ b/src/features/django/models.ts @@ -1,27 +1,34 @@ /** - * Django field lookups in Python code: in `Coffee.objects.filter(` (and `exclude`, `get`, …) the - * keyword completes the model's fields, `__` follows a relation to its model's fields, and after a - * plain field come its lookups (`name__icontains`). Models are read from the project's `models.py` - * files; fields and managers on instances come from basedpyright with django-types. + * Django field lookups in Python code: in `Coffee.objects.filter(` (and `exclude`, `get`, `Q(` + * inside them, …) the keyword completes the model's fields, `__` follows a relation to its model's + * fields, and after a field come its lookups (`name__icontains`). Models are read from the + * project's `models.py` files; fields and managers on instances come from basedpyright with + * django-types. */ import type { CompletionContext, CompletionResult } from "@codemirror/autocomplete"; import { EditorState, type Extension } from "@codemirror/state"; import type { EditorDocContext } from "@/editor/api"; import { call, commands } from "@/platform/ipc"; +import { callArgs, masks, pyString } from "./pyscan"; export interface ModelField { name: string; - /** `CharField`, `ForeignKey`… */ + /** `CharField`, `ForeignKey`, `reverse`… */ type: string; - /** Model name a relation points to (a reverse relation too). */ + /** The model a relation points to: as written in a parsed model (`Category`, `"shop.Category"`, `"self"`), a key in `modelFields`. */ to?: string; - /** A relation's `related_name`. */ + /** A relation's `related_name` / `related_query_name`. */ related?: string; + relatedQuery?: string; } export interface Model { + /** `app.Model`, the app being the folder of its models.py. */ + key: string; name: string; + app: string; bases: string[]; + abstract: boolean; fields: ModelField[]; } @@ -45,77 +52,206 @@ const LOOKUPS = [ "regex", "iregex", ]; +/** What follows a relation besides the related model's fields. */ +const RELATION_LOOKUPS = ["exact", "in", "isnull", "gt", "gte", "lt", "lte"]; const DATE_LOOKUPS = ["date", "year", "iso_year", "month", "day", "week", "week_day", "iso_week_day", "quarter"]; const TIME_LOOKUPS = ["time", "hour", "minute", "second"]; +const QUERIES = new Set(["filter", "exclude", "get", "get_or_create", "update_or_create"]); -/** Model classes of a models.py: `class X(…Model…):` and the fields assigned in its body. */ -export function parseModels(text: string): Model[] { +const indent = (line: string) => line.length - line.trimStart().length; + +/** Model classes of a models.py (of app `app`): `class X(…):` and the fields assigned in its body. */ +export function parseModels(text: string, app = ""): Model[] { + const { code, bare } = masks(text); const models: Model[] = []; let current: Model | null = null; - for (const line of text.split("\n")) { + let body = 0; + let offset = 0; + for (const line of code.split("\n")) { + const at = offset; + offset += line.length + 1; + // Comments are blanked: a comment at column 0 doesn't end a class. + if (!line.trim()) continue; const cls = /^class\s+(\w+)\s*\(([^)]*)\)\s*:/.exec(line); if (cls) { const bases = cls[2]!.split(",").map((b) => b.trim().split(".").pop()!); - current = { name: cls[1]!, bases, fields: [] }; + current = { key: `${app}.${cls[1]}`, name: cls[1]!, app, bases, abstract: false, fields: [] }; models.push(current); + body = 0; continue; } - if (/^\S/.test(line)) current = null; - const field = - current && /^ {4}(\w+)\s*(?::[^=]+)?=\s*(?:[\w.]+\.)?(\w+(?:Field|Key))\(\s*(?:(["']?)([\w.]+)\3)?/.exec(line); - if (!current || !field) continue; - const [, name, type, , target] = field; - const to = RELATIONS.has(type!) ? (target === "self" ? current.name : target?.split(".").pop()) : undefined; - const related = /related_name\s*=\s*["'](\w+)["']/.exec(line)?.[1]; - current.fields.push({ name: name!, type: type!, ...(to && { to }), ...(related && { related }) }); + if (!current) continue; + if (!indent(line)) { + current = null; + continue; + } + body ||= indent(line); + if (indent(line) > body) { + if (/^\s*abstract\s*=\s*True\b/.test(line)) current.abstract = true; + continue; + } + const field = /^\s*(\w+)\s*(?::[^=]+)?=\s*(?:[\w.]+\.)?(\w+(?:Field|Key))\s*\(/.exec(line); + if (!field) continue; + const [, name, type] = field; + const args = callArgs(code, bare, at + field[0].length - 1); + const kw = (key: string) => { + const arg = args.find((a) => a.key === key); + return (arg && pyString(arg.value)) ?? undefined; + }; + const first = args.find((a) => !a.key)?.value; + const to = RELATIONS.has(type!) && first ? (pyString(first) ?? (/^[\w.]+$/.test(first) ? first : null)) : null; + const related = kw("related_name"); + const relatedQuery = kw("related_query_name"); + current.fields.push({ + name: name!, + type: type!, + ...(to && { to }), + ...(related && { related }), + ...(relatedQuery && { relatedQuery }), + }); } return models; } +/** The key of the model `ref` names from `from` (`"self"`, `"app.Model"`, `Model`: same app first). */ +function resolve(byKey: Map, ref: string, from: Model): string | null { + if (ref === "self") return from.key; + if (ref.includes(".")) return byKey.has(ref) ? ref : null; + if (byKey.has(`${from.app}.${ref}`)) return `${from.app}.${ref}`; + return [...byKey.values()].find((m) => m.name === ref)?.key ?? null; +} + /** - * Fields by model name, with what a model inherits from project models and the reverse relations - * other models point at it with (`related_name`, else the lowercase model name). + * Fields by model key: `pk`, `id`, what a model inherits from project models, `_id`, and the + * reverse relations concrete models point at it with (`related_query_name`, `related_name`, else + * the lowercase model name; none for a name ending in `+`). */ export function modelFields(models: readonly Model[]): Map { - const byName = new Map(models.map((m) => [m.name, m])); + const byKey = new Map(models.map((m) => [m.key, m])); const own = (m: Model, seen = new Set()): ModelField[] => { - if (seen.has(m.name)) return []; - seen.add(m.name); - const inherited = m.bases.flatMap((b) => (byName.has(b) ? own(byName.get(b)!, seen) : [])); + if (seen.has(m.key)) return []; + seen.add(m.key); + const inherited = m.bases.flatMap((b) => { + const key = resolve(byKey, b, m); + return key ? own(byKey.get(key)!, seen) : []; + }); return [...inherited, ...m.fields]; }; + // A model's own relations: its fields and what abstract bases copy into it, not those of a + // concrete parent (multi-table inheritance), which point back from the parent alone. + const declared = (m: Model, seen = new Set()): ModelField[] => { + if (seen.has(m.key)) return []; + seen.add(m.key); + const copied = m.bases.flatMap((b) => { + const key = resolve(byKey, b, m); + const base = key ? byKey.get(key)! : null; + return base?.abstract ? declared(base, seen) : []; + }); + return [...copied, ...m.fields]; + }; const out = new Map(); - for (const m of models) - out.set(m.name, [{ name: "pk", type: "AutoField" }, { name: "id", type: "AutoField" }, ...own(m)]); - for (const m of models) - for (const f of own(m)) { - const target = f.to && out.get(f.to); - if (target && f.related !== "+") - target.push({ name: f.related ?? m.name.toLowerCase(), type: "reverse", to: m.name }); + for (const m of models) { + const fields = own(m).flatMap((f): ModelField[] => { + if (!f.to) return [f]; + const to = resolve(byKey, f.to, m) ?? undefined; + const field: ModelField = { ...f, to }; + if (!to) delete field.to; + return f.type === "ManyToManyField" ? [field] : [field, { name: `${f.name}_id`, type: "AutoField" }]; + }); + out.set(m.key, [{ name: "pk", type: "AutoField" }, { name: "id", type: "AutoField" }, ...fields]); + } + for (const m of models) { + if (m.abstract) continue; + for (const f of declared(m)) { + const to = f.to && resolve(byKey, f.to, m); + const target = to ? out.get(to) : undefined; + const name = (f.relatedQuery ?? f.related ?? m.name.toLowerCase()) + .replace("%(class)s", m.name.toLowerCase()) + .replace("%(app_label)s", m.app); + if (target && !name.endsWith("+")) target.push({ name, type: "reverse", to: m.key }); } + } return out; } -const QUERY = - /\b([A-Z]\w*)\.objects(?:\.\w+\([^()]*\))*\.(?:filter|exclude|get|get_or_create|update_or_create)\(([^()]*)$/; - -/** The model and the lookup typed so far, when the caret is at a keyword of a `Model.objects.filter(` call. */ -export function lookupAt(before: string): { model: string; path: string[]; word: string } | null { - const m = QUERY.exec(before); - if (!m) return null; - const kw = /(?:^|,)\s*(\w*)$/.exec(m[2]!); - if (!kw) return null; - const parts = kw[1]!.split("__"); - return { model: m[1]!, path: parts.slice(0, -1), word: parts[parts.length - 1]! }; +/** The model key a `Model.objects` query in `app` means: that app's own model of the name first. */ +export function modelKey(fields: Map, name: string, app: string): string | null { + if (fields.has(`${app}.${name}`)) return `${app}.${name}`; + return [...fields.keys()].find((k) => k.slice(k.lastIndexOf(".") + 1) === name) ?? null; } -/** What may follow `path` on `model`: fields (of the model the path leads to) or a field's lookups. */ +/** The model of `Model.objects[.method(…)…].query(` whose `(` is at `open` in `bare`. */ +function queryModel(bare: string, open: number): string | null { + let i = open; + const word = () => { + const m = /(\w+)\s*$/.exec(bare.slice(0, i)); + if (!m) return null; + i -= m[0].length; + return m[1]!; + }; + const dot = () => { + const m = /\.\s*$/.exec(bare.slice(0, i)); + if (m) i -= m[0].length; + return !!m; + }; + if (!QUERIES.has(word() ?? "")) return null; + for (let steps = 0; steps < 20 && dot(); steps++) { + while (i > 0 && /\s/.test(bare[i - 1]!)) i--; + if (bare[i - 1] === ")") { + // An earlier call of the chain: `.exclude(Q(a=1)).filter(`. + let depth = 0; + for (i--; i >= 0; i--) { + if (bare[i] === ")") depth++; + else if (bare[i] === "(" && --depth === 0) break; + } + if (i < 0 || !word()) return null; + continue; + } + if (word() !== "objects" || !dot()) return null; + const model = word(); + return model && /^[A-Z]/.test(model) ? model : null; + } + return null; +} + +/** The model and the lookup typed so far, when the caret is at a keyword of a query (or of a `Q(` inside one). */ +export function lookupAt(before: string): { model: string; path: string[]; word: string } | null { + const { bare, inString } = masks(before); + if (inString) return null; + const opens: number[] = []; + const commas: number[] = []; + let comma = -1; + for (let i = 0; i < bare.length; i++) { + const c = bare[i]; + if (c === "(" || c === "[" || c === "{") { + opens.push(i); + commas.push(comma); + comma = -1; + } else if ((c === ")" || c === "]" || c === "}") && opens.length) { + opens.pop(); + comma = commas.pop()!; + } else if (c === ",") comma = i; + } + const open = opens.at(-1); + if (open === undefined || bare[open] !== "(") return null; + const kw = /^\s*(\w*)$/.exec(before.slice(Math.max(comma, open) + 1)); + if (!kw) return null; + // `Q(` may sit in a query's arguments: the query is the nearest enclosing call. + const callee = /(\w+)\s*$/.exec(bare.slice(0, open))?.[1]; + const candidates = callee === "Q" ? opens.slice(0, -1).reverse() : [open]; + const model = candidates.map((o) => (bare[o] === "(" ? queryModel(bare, o) : null)).find(Boolean); + if (!model) return null; + const parts = kw[1]!.split("__"); + return { model, path: parts.slice(0, -1), word: parts[parts.length - 1]! }; +} + +/** What may follow `path` on model `key`: fields of the model the path leads to (and the lookups of a relation), or a field's lookups. */ export function lookupOptions( fields: Map, - model: string, + key: string, path: readonly string[], ): Array<{ label: string; detail?: string; field: boolean }> { - let current = fields.get(model); + let current = fields.get(key); let last: ModelField | null = null; for (const name of path) { if (!current) return []; @@ -123,48 +259,64 @@ export function lookupOptions( if (!last) return []; current = last.to ? fields.get(last.to) : undefined; } - if (current) return current.map((f) => ({ label: f.name, detail: f.to ?? f.type, field: true })); - if (!last || last.to) return []; + const lookups = (names: readonly string[]) => names.map((l) => ({ label: l, field: false })); + if (current) { + const own = current.map((f) => ({ label: f.name, detail: f.to?.split(".").pop() ?? f.type, field: true })); + return last ? [...own, ...lookups(RELATION_LOOKUPS)] : own; + } + if (!last) return []; + if (last.to) return lookups(RELATION_LOOKUPS); const extra = /^Date/.test(last.type) ? DATE_LOOKUPS : []; const time = /^(?:DateTime|Time)Field$/.test(last.type) ? TIME_LOOKUPS : []; - return [...LOOKUPS, ...extra, ...time].map((l) => ({ label: l, field: false })); + return lookups([...LOOKUPS, ...extra, ...time]); } +/** The app a file belongs to: the folder of its models.py (`shop/models.py`, `shop/views.py` → `shop`). */ +export const appOf = (path: string) => path.split("/").at(-2) ?? ""; + let cache: Promise> | null = null; -/** Fields of the project's models (read once, until a models.py changes). */ +/** Fields of the project's models (read once, until a models.py changes or indexing ends). */ export function projectModels(): Promise> { - cache ??= (async () => { + const read = (cache ??= (async () => { const paths = (await call(commands.findFilesNamed("models.py"))) .map(String) .filter((p) => !/\/(?:site-packages|node_modules|\.venv|venv)\//.test(p)); const texts = await Promise.all(paths.map((p) => call(commands.fsReadText(p)).catch(() => ""))); - return modelFields(texts.flatMap((t) => parseModels(t))); - })().catch(() => new Map()); - return cache; + return modelFields(texts.flatMap((t, i) => parseModels(t, appOf(paths[i]!)))); + })().catch(() => new Map())); + // Nothing found (the index may still be building): ask again next time. + void read.then((models) => !models.size && cache === read && (cache = null)); + return read; } export const forgetModels = () => void (cache = null); -async function completion(ctx: CompletionContext): Promise { - const at = lookupAt(ctx.state.sliceDoc(Math.max(0, ctx.pos - 500), ctx.pos)); - if (!at) return null; - const options = lookupOptions(await projectModels(), at.model, at.path); - if (ctx.aborted || !options.length) return null; - // The whole keyword (`category__name`), so the list merges with sources completing the word. - const prefix = at.path.map((p) => `${p}__`).join(""); - return { - from: ctx.pos - prefix.length - at.word.length, - options: options.map((o) => ({ - label: prefix + o.label, - detail: o.detail, - type: o.field ? "property" : "keyword", - })), +export function lookupCompletion(path: string) { + return async (ctx: CompletionContext): Promise => { + const at = lookupAt(ctx.state.sliceDoc(Math.max(0, ctx.pos - 1000), ctx.pos)); + if (!at) return null; + const fields = await projectModels(); + const key = modelKey(fields, at.model, appOf(path)); + const options = key ? lookupOptions(fields, key, at.path) : []; + if (ctx.aborted || !options.length) return null; + // The whole keyword (`category__name`), so the list merges with sources completing the word. + const prefix = at.path.map((p) => `${p}__`).join(""); + return { + from: ctx.pos - prefix.length - at.word.length, + options: options.map((o) => ({ + label: prefix + o.label, + detail: o.detail, + type: o.field ? "property" : "keyword", + // Above the language server's names (auto-imports) at a query keyword. + boost: 50, + })), + }; }; } export function lookupCompletionExtension(doc: EditorDocContext): Extension { return doc.language === "python" && !doc.virtual && !doc.readOnly - ? EditorState.languageData.of(() => [{ openideaCompletion: completion }]) + ? EditorState.languageData.of(() => [{ openideaCompletion: lookupCompletion(doc.path) }]) : []; } diff --git a/src/features/django/pyscan.ts b/src/features/django/pyscan.ts new file mode 100644 index 000000000..a5d721b08 --- /dev/null +++ b/src/features/django/pyscan.ts @@ -0,0 +1,109 @@ +/** Just enough Python scanning for Django files: strings, comments and bracket nesting. */ + +/** + * `src` with comments blanked (`code`) and also string contents blanked (`bare`), same length: + * brackets and names found in `bare` are code, never text in a string or a comment. + */ +export function masks(src: string): { code: string; bare: string; inString: boolean } { + let code = ""; + let bare = ""; + let inString = false; + for (let i = 0; i < src.length;) { + const c = src[i]!; + if (c === "#") { + const end = src.indexOf("\n", i); + const n = (end < 0 ? src.length : end) - i; + code += " ".repeat(n); + bare += " ".repeat(n); + i += n; + } else if (c === '"' || c === "'") { + const quote = src.startsWith(c.repeat(3), i) ? c.repeat(3) : c; + let j = i + quote.length; + while (j < src.length && !src.startsWith(quote, j) && (quote.length === 3 || src[j] !== "\n")) + j += src[j] === "\\" ? 2 : 1; + inString = j >= src.length; + j = Math.min(src.length, j + quote.length); + code += src.slice(i, j); + bare += quote + src.slice(i + quote.length, j - quote.length).replace(/[^\n]/g, " ") + quote; + i = j; + } else { + code += c; + bare += c; + i++; + } + } + return { code, bare: bare.slice(0, src.length), inString }; +} + +export interface PyArg { + /** The keyword of `key=value`, else null. */ + key: string | null; + /** The value's source text (comments blanked). */ + value: string; + /** Offset of `value` in the source. */ + from: number; +} + +export interface PyCall { + name: string; + /** Offset of the name. */ + from: number; + args: PyArg[]; +} + +/** The top-level arguments of the call whose `(` is at `open` (offsets into the masked source). */ +export function callArgs(code: string, bare: string, open: number): PyArg[] { + const args: PyArg[] = []; + let depth = 0; + let start = open + 1; + const push = (end: number) => { + const raw = code.slice(start, end); + const kw = /^(\s*)(\w+)\s*=(?!=)\s*/.exec(raw); + const lead = kw ? kw[0].length : raw.length - raw.trimStart().length; + const value = raw.slice(lead).trimEnd(); + if (value) args.push({ key: kw ? kw[2]! : null, value, from: start + lead }); + }; + for (let i = open + 1; i < bare.length; i++) { + const c = bare[i]; + if (c === "(" || c === "[" || c === "{") depth++; + else if (c === ")" || c === "]" || c === "}") { + if (depth === 0) { + push(i); + break; + } + depth--; + } else if (c === "," && depth === 0) { + push(i); + start = i + 1; + } + } + return args; +} + +/** Calls of `names` (`path`, `include`…) with their top-level arguments. */ +export function pyCalls(src: string, names: readonly string[]): PyCall[] { + const { code, bare } = masks(src); + const head = new RegExp(String.raw`(?:^|[^\w.])(${names.join("|")})\s*\(`, "g"); + // The match starts with the character before the name, when there is one. + return [...bare.matchAll(head)].map((m) => ({ + name: m[1]!, + from: m.index + m[0].indexOf(m[1]!), + args: callArgs(code, bare, m.index + m[0].length - 1), + })); +} + +/** The text of a plain string literal (`"x"`, `r'x'`), else null. */ +export function pyString(value: string): string | null { + return /^[rRuU]?(["'])([^"'\\\n]*)\1$/.exec(value.trim())?.[2] ?? null; +} + +/** 0-based line and UTF-16 column of `offset` in `text`. */ +export function position(text: string, offset: number): { line: number; col: number } { + let line = 0; + let start = 0; + for (let i = text.indexOf("\n"); i >= 0 && i < offset; i = text.indexOf("\n", i + 1)) { + line++; + start = i + 1; + } + return { line, col: offset - start }; +} diff --git a/src/features/django/stubs.test.ts b/src/features/django/stubs.test.ts index 06bb797aa..a7029dee2 100644 --- a/src/features/django/stubs.test.ts +++ b/src/features/django/stubs.test.ts @@ -1,7 +1,54 @@ -import { expect, it, vi } from "vitest"; +import { beforeEach, expect, it, vi } from "vitest"; + +const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); +const ipc = vi.hoisted(() => ({ + packages: ["django"] as string[], + envFiles: ["/p/.venv/pyvenv.cfg"] as string[], + pip: vi.fn(), + restart: vi.fn(), + notify: vi.fn(), + gate: null as null | Promise, + /** Per interpreter: holds its package list back. */ + gates: {} as Record>, +})); vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} })); -const { needsStubs } = await import("./stubs"); +vi.mock("@/workbench/tasks", () => ({ upsertTask: () => {} })); +vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: ipc.notify }) })); +vi.mock("@/platform/ipc", async (importOriginal) => ({ + ...(await importOriginal()), + nextRequestId: () => 1, + commands: { + cancelRequest: () => ok(null), + fsEntryKind: (path: string) => + ipc.envFiles.includes(path) ? ok("file") : Promise.resolve({ status: "error", error: { message: "missing" } }), + sdkPythonPackages: async (python: string) => { + await ipc.gate; + await ipc.gates[python]; + return ok(ipc.packages.map((name) => ({ name, version: "1" }))); + }, + sdkPythonPip: (python: string, requirement: string) => { + ipc.pip(python, requirement); + ipc.packages.push(requirement); + return ok(null); + }, + lspRestartNamed: (name: string) => { + ipc.restart(name); + return ok(null); + }, + }, +})); + +const { checkStubs, install, needsStubs, resetStubs, useStubs } = await import("./stubs"); + +beforeEach(() => { + resetStubs(); + ipc.packages = ["django"]; + ipc.envFiles = ["/p/.venv/pyvenv.cfg"]; + ipc.gate = null; + ipc.pip.mockClear(); + ipc.restart.mockClear(); +}); it("asks for stubs when Django has none", () => { expect(needsStubs(["django", "asgiref"])).toBe(true); @@ -9,3 +56,50 @@ it("asks for stubs when Django has none", () => { expect(needsStubs(["django", "django-stubs"])).toBe(false); expect(needsStubs(["flask"])).toBe(false); }); + +it("offers the install only for a virtual environment", async () => { + await checkStubs("/p/.venv/bin/python"); + expect(useStubs.getState()).toMatchObject({ python: "/p/.venv/bin/python", missing: true }); + await checkStubs("/usr/bin/python3"); + expect(useStubs.getState().missing).toBe(false); + ipc.envFiles = ["/opt/conda/envs/site/conda-meta"]; + await checkStubs("/opt/conda/envs/site/bin/python"); + expect(useStubs.getState().missing).toBe(true); + // Windows: a venv's Scripts\python.exe, and a conda env's python.exe at its root. + ipc.envFiles = ["C:/p/.venv/pyvenv.cfg", "C:/conda/envs/site/conda-meta"]; + await checkStubs("C:\\p\\.venv\\Scripts\\python.exe"); + expect(useStubs.getState().missing).toBe(true); + resetStubs(); + await checkStubs("C:\\conda\\envs\\site\\python.exe"); + expect(useStubs.getState().missing).toBe(true); +}); + +it("installs into the checked interpreter, restarts the type checker and checks again", async () => { + await checkStubs("/p/.venv/bin/python"); + await install(); + expect(ipc.pip).toHaveBeenCalledWith("/p/.venv/bin/python", "django-types"); + expect(ipc.restart).toHaveBeenCalledWith("basedpyright"); + expect(useStubs.getState()).toMatchObject({ missing: false, installing: false }); +}); + +it("drops a check that ends after the project changed", async () => { + let release!: () => void; + ipc.gate = new Promise((resolve) => (release = resolve)); + const old = checkStubs("/old/.venv/bin/python"); + resetStubs(); + release(); + await old; + expect(useStubs.getState().python).toBeNull(); +}); + +it("keeps the latest check when the interpreter changes during a slower one", async () => { + let release!: () => void; + ipc.gates = { "/old/.venv/bin/python": new Promise((resolve) => (release = resolve)) }; + ipc.envFiles = ["/old/.venv/pyvenv.cfg", "/new/.venv/pyvenv.cfg"]; + const old = checkStubs("/old/.venv/bin/python"); + await checkStubs("/new/.venv/bin/python"); + release(); + await old; + expect(useStubs.getState().python).toBe("/new/.venv/bin/python"); + ipc.gates = {}; +}); diff --git a/src/features/django/stubs.ts b/src/features/django/stubs.ts index e34c097ab..eacce8418 100644 --- a/src/features/django/stubs.ts +++ b/src/features/django/stubs.ts @@ -23,18 +23,47 @@ interface StubsState { const initial = (): StubsState => ({ python: null, missing: false, installing: false, ignored: false }); export const useStubs = create(initial); -export const resetStubs = () => useStubs.setState(initial()); + +/** Bumped by each reset: a check started for the previous project doesn't write into the store. */ +let epoch = 0; +/** Bumped by each check: only the latest one (another interpreter's, say) writes. */ +let latest = 0; +export function resetStubs() { + epoch++; + useStubs.setState(initial()); +} /** Django without django-types or django-stubs. */ export const needsStubs = (packages: readonly string[]) => packages.includes("django") && !packages.some((p) => p === STUBS || p === "django-stubs"); -export async function checkStubs(python: string): Promise { - const packages = await call(commands.sdkPythonPackages(python, false, nextRequestId())).catch(() => []); - useStubs.setState({ python, missing: needsStubs(packages.map((p) => p.name.toLowerCase().replace(/_/g, "-"))) }); +/** A virtual environment (venv, virtualenv, conda), the only kind the banner installs into: not the system Python. */ +async function isEnvironment(python: string): Promise { + const parts = python.replace(/\\/g, "/").split("/"); + // `env/bin/python`, `env\Scripts\python.exe`, and a Windows conda env's `env\python.exe`. + const roots = [parts.slice(0, -2).join("/"), parts.slice(0, -1).join("/")]; + const kinds = await Promise.all( + roots.flatMap((root) => + ["pyvenv.cfg", "conda-meta"].map((name) => call(commands.fsEntryKind(`${root}/${name}`)).catch(() => null)), + ), + ); + return kinds.some(Boolean); } -async function install() { +export async function checkStubs(python: string): Promise { + const mine = epoch; + const check = ++latest; + const missing = + (await isEnvironment(python)) && + needsStubs( + (await call(commands.sdkPythonPackages(python, false, nextRequestId())).catch(() => [])).map((p) => + p.name.toLowerCase().replace(/_/g, "-"), + ), + ); + if (mine === epoch && check === latest) useStubs.setState({ python, missing }); +} + +export async function install() { const { python, installing } = useStubs.getState(); if (!python || installing) return; useStubs.setState({ installing: true }); @@ -63,7 +92,7 @@ export function useStubsBanner(path: string): EditorBanner | null { const show = useStubs((s) => s.missing && !s.ignored && !s.installing); if (!show || !path.endsWith(".py")) return null; return { - text: "Install django-types to complete Django model fields and managers", + text: "Install django-types into this project's virtual environment to complete Django model fields and managers", actions: [ { label: "Install", run: () => void install() }, { label: "Ignore", run: () => useStubs.setState({ ignored: true }) }, diff --git a/src/features/django/urls.test.ts b/src/features/django/urls.test.ts index e559dfa10..ffc2c3e79 100644 --- a/src/features/django/urls.test.ts +++ b/src/features/django/urls.test.ts @@ -1,39 +1,118 @@ -import { describe, expect, it } from "vitest"; -import { urlNameAt, urlNames } from "./urls"; +import { CompletionContext } from "@codemirror/autocomplete"; +import { EditorState } from "@codemirror/state"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -const URLS = `from django.urls import path +const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); +const ipc = vi.hoisted(() => ({ files: {} as Record, invalidate: vi.fn() })); +vi.mock("@/editor/navigationProviders", () => ({ invalidateNavigationProviders: ipc.invalidate })); +vi.mock("@/platform/ipc", async (importOriginal) => ({ + ...(await importOriginal()), + commands: { + findFilesNamed: () => ok(Object.keys(ipc.files)), + fsReadText: (path: string) => ok(ipc.files[path]), + }, +})); + +const { forgetUrlNames, parseUrls, projectUrlNames, resolveUrlNames, urlCompletion, urlNameAt, urlNavigation } = + await import("./urls"); + +const SHOP = `from django.urls import include, path app_name = "shop" urlpatterns = [ path("", views.product_list, name="products"), path("products//", views.product_detail, name='product'), + # path("old/", views.old, name="old"), + path("api/", include("shop.api.urls")), +] +special = Product.objects.filter(name="not-a-url") +`; +const API = `app_name = "api" +urlpatterns = [path("items/", views.items, name="item")] +`; +const ROOT = `urlpatterns = [ + path("", include("shop.urls")), + path("v2/", include("shop.urls", namespace="shop-v2")), + path("blog/", include(("blog.urls", "blog"))), + path("", home, name="home"), ] `; +const BLOG = `urlpatterns = [path("", index, name="index")]\n`; + +const names = (files: Record) => + resolveUrlNames(Object.entries(files).map(([p, t]) => parseUrls(p, t))) + .map((u) => u.name) + .sort(); + +beforeEach(() => { + forgetUrlNames(); + ipc.invalidate.mockClear(); +}); describe("URL names", () => { - it("reads the names of a urls.py under its app_name", () => { - expect(urlNames("/p/shop/urls.py", URLS)).toEqual([ - { - name: "shop:products", - path: "/p/shop/urls.py", - range: { start: { line: 5, col: 39 }, end: { line: 5, col: 47 } }, - }, - { - name: "shop:product", - path: "/p/shop/urls.py", - range: { start: { line: 6, col: 62 }, end: { line: 6, col: 69 } }, - }, + it("reads named patterns: not comments, not other calls' name=", () => { + const shop = parseUrls("/p/shop/urls.py", SHOP); + expect(shop.app).toBe("shop"); + expect(shop.names).toEqual([ + { name: "products", range: { start: { line: 5, col: 39 }, end: { line: 5, col: 47 } } }, + { name: "product", range: { start: { line: 6, col: 62 }, end: { line: 6, col: 69 } } }, ]); - expect(urlNames("/p/urls.py", `urlpatterns = [path("", home, name="home")]`).map((u) => u.name)).toEqual(["home"]); + expect(shop.includes).toEqual([{ module: "shop.api.urls", namespace: null, app: null }]); }); - it("finds the name in reverse() and the like", () => { + it("nests namespaces along includes", () => { + expect(names({ "/p/shop/urls.py": SHOP, "/p/shop/api/urls.py": API })).toEqual([ + "shop:api:item", + "shop:product", + "shop:products", + ]); + // From the root URLconf: app namespace, instance namespace, the tuple form, and none. + expect( + names({ "/p/site/urls.py": ROOT, "/p/shop/urls.py": SHOP, "/p/shop/api/urls.py": API, "/p/blog/urls.py": BLOG }), + ).toEqual([ + "blog:index", + "home", + "shop-v2:api:item", + "shop-v2:product", + "shop-v2:products", + "shop:api:item", + "shop:product", + "shop:products", + ]); + }); + + it("finds the name in reverse() and the like, also when the call starts a line above", () => { const line = ` return redirect("shop:product", slug=p.slug) or reverse_lazy('home')`; - const at = line.indexOf("shop:") + 3; - expect(urlNameAt(line, at)).toEqual({ name: "shop:product", from: 21, to: 33 }); + expect(urlNameAt(line, line.indexOf("shop:") + 3)).toEqual({ name: "shop:product", from: 21, to: 33 }); expect(urlNameAt(line, line.indexOf("home"))).toMatchObject({ name: "home" }); + const split = `url = reverse(\n "shop:product",\n)`; + expect(urlNameAt(split, split.indexOf("product"))).toMatchObject({ name: "shop:product" }); expect(urlNameAt(`render(request, "shop/list.html")`, 20)).toBeNull(); expect(urlNameAt(`reverse("a", args=["b"])`, 20)).toBeNull(); }); + + it("navigates to the pattern and completes the names", async () => { + ipc.files = { "/p/shop/urls.py": SHOP }; + const text = `x = 1\nurl = reverse(\n "shop:product")`; + const match = await urlNavigation(text.slice(4), 4, text.indexOf("product")); + expect(match).toMatchObject({ + from: text.indexOf("shop:"), + targets: [{ path: "/p/shop/urls.py", name: "shop:product" }], + }); + const state = EditorState.create({ doc: `reverse("shop:pr` }); + const result = await urlCompletion(new CompletionContext(state, state.doc.length, true)); + expect(result?.from).toBe(9); + expect(result?.options.map((o) => o.label)).toEqual(["shop:products", "shop:product"]); + }); + + it("asks the index again when it had no urls.py yet, and drops navigation's hits when names change", async () => { + ipc.files = {}; + expect(await projectUrlNames()).toEqual([]); + await Promise.resolve(); + ipc.files = { "/p/shop/urls.py": SHOP }; + expect((await projectUrlNames()).map((u) => u.name)).toContain("shop:product"); + forgetUrlNames(); + expect(ipc.invalidate).toHaveBeenCalled(); + }); }); diff --git a/src/features/django/urls.ts b/src/features/django/urls.ts index 19d255d4e..a272cbc56 100644 --- a/src/features/django/urls.ts +++ b/src/features/django/urls.ts @@ -6,36 +6,101 @@ import type { CompletionContext, CompletionResult } from "@codemirror/autocomplete"; import { EditorState, type Extension } from "@codemirror/state"; import type { EditorDocContext } from "@/editor/api"; -import type { NavigationMatch } from "@/editor/navigationProviders"; +import { invalidateNavigationProviders, type NavigationMatch } from "@/editor/navigationProviders"; import { call, commands, type Range } from "@/platform/ipc"; import { useProject } from "@/platform/project"; +import { masks, position, pyCalls, pyString } from "./pyscan"; export interface UrlName { - /** With the module's `app_name` namespace: `shop:product`. */ + /** With its namespaces: `shop:product`, `shop:api:item`. */ name: string; path: string; /** The name inside its quotes (0-based line, UTF-16 column). */ range: Range; } -const CALL = /\b(?:reverse|reverse_lazy|redirect|resolve_url)\(\s*$/; - -/** The URL names a urls.py defines: `name="…"` arguments, under the module's `app_name`. */ -export function urlNames(path: string, text: string): UrlName[] { - const app = /^app_name\s*=\s*["']([^"'\n]+)["']/m.exec(text)?.[1]; - return [...text.matchAll(/\bname\s*=\s*(["'])([^"'\n]+)\1/g)].map((m) => { - const from = m.index + m[0].length - m[2]!.length - 1; - const line = text.slice(0, from).split("\n").length - 1; - const col = from - text.lastIndexOf("\n", from - 1) - 1; - return { - name: app ? `${app}:${m[2]}` : m[2]!, - path, - range: { start: { line, col }, end: { line, col: col + m[2]!.length } }, - }; - }); +/** What a urls.py says: its `app_name`, its named patterns and the URL modules it includes. */ +export interface UrlModule { + path: string; + app: string | null; + names: Array<{ name: string; range: Range }>; + /** `include("x.urls", namespace=…)`, `include(("x.urls", "app"))`. */ + includes: Array<{ module: string; namespace: string | null; app: string | null }>; } -/** The URL name string under `offset`, when it is the first argument of `reverse(` and the like. */ +const CALL = /\b(?:reverse|reverse_lazy|redirect|resolve_url)\(\s*$/; + +export function parseUrls(path: string, text: string): UrlModule { + const { code } = masks(text); + const app = /^app_name\s*=\s*["']([^"'\n]+)["']/m.exec(code)?.[1] ?? null; + const names: UrlModule["names"] = []; + const includes: UrlModule["includes"] = []; + for (const c of pyCalls(text, ["path", "re_path", "url", "include"])) { + const kw = (key: string) => c.args.find((a) => a.key === key); + if (c.name === "include") { + const first = c.args[0]; + const tuple = first && !first.key && /^\(\s*(.+?)\s*,\s*(.+?)\s*,?\s*\)$/s.exec(first.value); + const module = first && !first.key && pyString(tuple ? tuple[1]! : first.value); + const ns = kw("namespace"); + if (module) + includes.push({ module, namespace: ns ? pyString(ns.value) : null, app: tuple ? pyString(tuple[2]!) : null }); + continue; + } + const arg = kw("name"); + const name = arg && pyString(arg.value); + if (!arg || !name) continue; + const from = arg.from + arg.value.indexOf(name); + const start = position(text, from); + names.push({ name, range: { start, end: { line: start.line, col: start.col + name.length } } }); + } + return { path, app, names, includes }; +} + +/** + * Full URL names: a module's names under the namespaces of the includes that reach it, nested + * (`shop:api:item`). An include's namespace is its instance namespace (`namespace=`) or the + * application namespace (the tuple's, else the included module's `app_name`); `reverse` takes + * either. A module no other one includes keeps its own `app_name`. + */ +export function resolveUrlNames(modules: readonly UrlModule[]): UrlName[] { + const byModule = (dotted: string) => { + const tail = `/${dotted.replace(/\./g, "/")}.py`; + return modules.find((m) => m.path.endsWith(tail)) ?? null; + }; + const parents = new Map>(); + for (const m of modules) + for (const inc of m.includes) { + const target = byModule(inc.module); + if (!target) continue; + const app = inc.app ?? target.app; + const spaces = [...new Set([inc.namespace ?? app, app].filter((x): x is string => !!x))]; + parents.set(target, [...(parents.get(target) ?? []), { from: m, spaces }]); + } + const chains = (m: UrlModule, seen: Set): string[][] => { + const up = parents.get(m); + if (!up) return [m.app ? [m.app] : []]; + if (seen.has(m)) return []; + const next = new Set(seen).add(m); + return up + .flatMap(({ from, spaces }) => + chains(from, next).flatMap((c) => (spaces.length ? spaces.map((s) => [...c, s]) : [c])), + ) + .slice(0, 20); + }; + const out = new Map(); + for (const m of modules) + for (const chain of chains(m, new Set())) + for (const { name, range } of m.names) { + const full = [...chain, name].join(":"); + out.set(`${full}\0${m.path}\0${range.start.line}`, { name: full, path: m.path, range }); + } + return [...out.values()]; +} + +/** + * The URL name string under `offset`, when it is the first argument of `reverse(` and the like + * (the call may start on an earlier line of `text`). + */ export function urlNameAt(text: string, offset: number): { name: string; from: number; to: number } | null { const start = text.lastIndexOf("\n", offset - 1) + 1; const end = text.indexOf("\n", offset); @@ -43,35 +108,42 @@ export function urlNameAt(text: string, offset: number): { name: string; from: n for (const m of line.matchAll(/(["'])([\w:.-]*)\1/g)) { const from = start + m.index + 1; const to = from + m[2]!.length; - if (offset >= from && offset <= to && CALL.test(line.slice(0, m.index))) return { name: m[2]!, from, to }; + if (offset >= from && offset <= to && CALL.test(text.slice(Math.max(0, from - 201), from - 1))) + return { name: m[2]!, from, to }; } return null; } let cache: Promise | null = null; -/** Every URL name of the project's own urls.py files (read once, until one changes). */ +/** Every URL name of the project's own urls.py files (read once, until one changes or indexing ends). */ export function projectUrlNames(): Promise { - cache ??= (async () => { + const read = (cache ??= (async () => { const paths = (await call(commands.findFilesNamed("urls.py"))) .map(String) .filter((p) => !/\/(?:site-packages|node_modules|\.venv|venv)\//.test(p)); const texts = await Promise.all(paths.map((p) => call(commands.fsReadText(p)).catch(() => ""))); - return paths.flatMap((p, i) => urlNames(p, texts[i]!)); - })().catch(() => []); - return cache; + return resolveUrlNames(paths.map((p, i) => parseUrls(p, texts[i]!))); + })().catch(() => [])); + // Nothing found (the index may still be building): ask again next time. + void read.then((names) => !names.length && cache === read && (cache = null)); + return read; } -export const forgetUrlNames = () => void (cache = null); +/** Drops the names read, and what navigation remembers of them. */ +export function forgetUrlNames() { + cache = null; + invalidateNavigationProviders(); +} -/** `line`: the text of the line at `offset`, which starts at `lineFrom`. */ -export async function urlNavigation(line: string, lineFrom: number, offset: number): Promise { - const at = urlNameAt(line, offset - lineFrom); +/** `text`: the document from `base` on, around `offset` (with the lines before it, for a call that starts there). */ +export async function urlNavigation(text: string, base: number, offset: number): Promise { + const at = urlNameAt(text, offset - base); if (!at?.name) return null; const names = (await projectUrlNames()).filter((u) => u.name === at.name); if (!names.length) return null; const targets = names.map(({ path, range, name }) => ({ path, range, name })); - return { from: lineFrom + at.from, to: lineFrom + at.to, targets }; + return { from: base + at.from, to: base + at.to, targets }; } function where(path: string): string { @@ -79,7 +151,7 @@ function where(path: string): string { return root && path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path; } -async function completion(ctx: CompletionContext): Promise { +export async function urlCompletion(ctx: CompletionContext): Promise { const before = ctx.state.sliceDoc(Math.max(0, ctx.pos - 200), ctx.pos); const m = /(["'])([\w:.-]*)$/.exec(before); if (!m || !CALL.test(before.slice(0, m.index))) return null; @@ -95,6 +167,6 @@ async function completion(ctx: CompletionContext): Promise [{ openideaCompletion: completion }]) + ? EditorState.languageData.of(() => [{ openideaCompletion: urlCompletion }]) : []; } diff --git a/src/features/python-console/console.py b/src/features/python-console/console.py index c04cbaf46..a54bb4e11 100644 --- a/src/features/python-console/console.py +++ b/src/features/python-console/console.py @@ -27,6 +27,8 @@ def _variables(namespace): for name, value in list(namespace.items()): if name.startswith("_") or name in _hidden or isinstance(value, types.ModuleType): continue + if name in _auto and _auto[name] is value: + continue try: text = _repr.repr(value) except Exception as error: # a broken __repr__ must not break the console @@ -82,10 +84,15 @@ except ImportError: ready = {"version": sys.version.split()[0], "ipython": flavour} +# Names `manage.py shell` imports, hidden from the variables while they keep their value. +_auto = {} # A Django project (PyCharm's Django Console): set Django up and import what `manage.py shell` does. -if os.environ.get("OPENIDEA_DJANGO_SETTINGS"): - if not os.environ.get("DJANGO_SETTINGS_MODULE"): # as manage.py: the environment's own wins - os.environ["DJANGO_SETTINGS_MODULE"] = os.environ["OPENIDEA_DJANGO_SETTINGS"] +if os.environ.get("OPENIDEA_DJANGO_DIR"): + if os.environ["OPENIDEA_DJANGO_DIR"] not in sys.path: + sys.path.insert(0, os.environ["OPENIDEA_DJANGO_DIR"]) # where manage.py imports the settings from + if not os.environ.get("DJANGO_SETTINGS_MODULE") and os.environ.get("OPENIDEA_DJANGO_SETTINGS"): + os.environ["DJANGO_SETTINGS_MODULE"] = os.environ["OPENIDEA_DJANGO_SETTINGS"] # as manage.py: the environment's wins +if os.environ.get("OPENIDEA_DJANGO_DIR") and os.environ.get("DJANGO_SETTINGS_MODULE"): try: import django @@ -94,11 +101,11 @@ if os.environ.get("OPENIDEA_DJANGO_SETTINGS"): try: from django.core.management.commands.shell import Command - imports = Command().get_namespace() # Django 5.2+: the models and common utilities + # Django 5.2+: the models; 6.0+ also settings, timezone, models, functions… + _auto = Command().get_namespace() except Exception: - imports = {} - namespace.update(imports) - _hidden.update(imports) + pass + namespace.update(_auto) except Exception: import traceback diff --git a/src/features/python-console/console.test.ts b/src/features/python-console/console.test.ts index b71934d4f..a86113b45 100644 --- a/src/features/python-console/console.test.ts +++ b/src/features/python-console/console.test.ts @@ -71,23 +71,62 @@ it.skipIf(!IPYTHON)("ends at exit() under IPython", () => { expect([text, messages.length, status]).toEqual(["", 2, 0]); }); -it.skipIf(!DJANGO)("sets Django up and imports the models like manage.py shell", () => { - const cwd = mkdtempSync(join(tmpdir(), "console-django-")); - writeFileSync( - join(cwd, "site_settings.py"), - 'SECRET_KEY = "x"\nINSTALLED_APPS = ["django.contrib.contenttypes", "django.contrib.auth"]\n' + - 'DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}\n', - ); - // As the IDE runs it: `-c`, so the working directory (manage.py's) is on sys.path. - const result = spawnSync(DJANGO!, ["-u", "-c", readFileSync(DRIVER, "utf8")], { - cwd, - input: request("User._meta.label, settings.SECRET_KEY"), - encoding: "utf8", - env: { ...process.env, OPENIDEA_DJANGO_SETTINGS: "site_settings", DJANGO_SETTINGS_MODULE: "" }, - }); - const { text, messages } = stdoutParser()(result.stdout); - expect(messages[0]).toMatchObject({ ready: { django: expect.stringMatching(/^\d/) } }); - expect(text).toContain("('auth.User', 'x')"); - // The imports are the console's own, not the user's variables. - expect(variables(messages)[0]).toEqual([]); -}); +it.skipIf(!DJANGO)( + "sets Django up and imports the models like manage.py shell", + () => { + const site = mkdtempSync(join(tmpdir(), "console-django-")); + writeFileSync( + join(site, "site_settings.py"), + 'SECRET_KEY = "x"\nINSTALLED_APPS = ["django.contrib.contenttypes", "django.contrib.auth"]\n' + + 'DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}\n', + ); + // As the IDE runs it: `-c`, in the project root, with manage.py's folder given apart. + const result = spawnSync(DJANGO!, ["-u", "-c", readFileSync(DRIVER, "utf8")], { + cwd: tmpdir(), + input: [ + "User._meta.label", + "import django\ndjango.VERSION >= (6,) and settings.SECRET_KEY", + "x = 1", + "User = 'mine'", + ] + .map(request) + .join(""), + encoding: "utf8", + env: { + ...process.env, + OPENIDEA_DJANGO_DIR: site, + OPENIDEA_DJANGO_SETTINGS: "site_settings", + DJANGO_SETTINGS_MODULE: "", + }, + }); + const { text, messages } = stdoutParser()(result.stdout); + expect(result.stderr).toBe(""); + expect(messages[0]).toMatchObject({ ready: { django: expect.stringMatching(/^\d/) } }); + // 5.2+ imports the models; 6.0+ also `settings` (False on 5.2). + expect(text).toMatch(/^'auth\.User'\n('x'|False)\n/); + // The imports are the console's own, not the user's variables, until the user assigns one. + expect(variables(messages)[2]).toEqual(["x: int = 1"]); + expect(variables(messages)[3]).toEqual(["User: str = 'mine'", "x: int = 1"]); + }, + 30_000, +); + +it.skipIf(!DJANGO)( + "uses DJANGO_SETTINGS_MODULE from the environment when manage.py names none", + () => { + const site = mkdtempSync(join(tmpdir(), "console-django-")); + writeFileSync(join(site, "env_settings.py"), 'SECRET_KEY = "x"\nINSTALLED_APPS = []\n'); + const ready = (env: Record) => { + const result = spawnSync(DJANGO!, ["-u", "-c", readFileSync(DRIVER, "utf8")], { + cwd: tmpdir(), + input: "", + encoding: "utf8", + env: { ...process.env, OPENIDEA_DJANGO_DIR: site, ...env }, + }); + return stdoutParser()(result.stdout).messages[0]; + }; + expect(ready({ DJANGO_SETTINGS_MODULE: "env_settings" })).toMatchObject({ ready: { django: expect.any(String) } }); + expect(ready({ DJANGO_SETTINGS_MODULE: "" })).not.toHaveProperty("ready.django"); + }, + 30_000, +); diff --git a/src/features/python-console/store.test.ts b/src/features/python-console/store.test.ts index df27b6e6c..4991cfd36 100644 --- a/src/features/python-console/store.test.ts +++ b/src/features/python-console/store.test.ts @@ -89,5 +89,12 @@ it("reads the settings module manage.py sets", () => { expect(settingsModule(` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")`)).toBe( "config.settings", ); + expect(settingsModule(`os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'`)).toBe("site.settings"); + expect( + settingsModule( + `# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "old")\nos.environ.setdefault("DJANGO_SETTINGS_MODULE", "new")`, + ), + ).toBe("new"); + expect(settingsModule(`os.environ.setdefault("DJANGO_SETTINGS_MODULE", f"{SITE}.settings")`)).toBeNull(); expect(settingsModule("print('hi')")).toBeNull(); }); diff --git a/src/features/python-console/store.ts b/src/features/python-console/store.ts index 690384218..ddc57ebf7 100644 --- a/src/features/python-console/store.ts +++ b/src/features/python-console/store.ts @@ -1,9 +1,9 @@ /** The Python Console's process: the project interpreter running console.py on the Run process host. */ import { Channel } from "@tauri-apps/api/core"; import { create } from "zustand"; -import { pickManage } from "@/features/django/manage"; import { call, commands, onIdeEvent, type OutputChunk, type RunConfig, type RunId } from "@/platform/ipc"; import { windowLabel } from "@/platform/auxWindow"; +import { findManage } from "@/platform/django"; import { dirname, useProject } from "@/platform/project"; import { tx } from "@/platform/i18n"; import { AnsiStream, appendSpans, type Span } from "@/ui/ansi"; @@ -88,18 +88,20 @@ function onMessage(message: ConsoleMessage) { /** Run ids of this window's consoles: a reloaded page finds the ones its previous load left running. */ const PREFIX = `python-console:${windowLabel()}:`; -/** The settings module `manage.py` sets as DJANGO_SETTINGS_MODULE. */ +/** The settings module `manage.py` sets as DJANGO_SETTINGS_MODULE (`setdefault(…)` or `os.environ[…] =`). */ export const settingsModule = (manage: string) => - /DJANGO_SETTINGS_MODULE["']\s*,\s*["']([\w.]+)["']/.exec(manage)?.[1] ?? null; + /^[^#\n]*DJANGO_SETTINGS_MODULE["']\s*(?:,|\]\s*=)\s*["']([\w.]+)["']/m.exec(manage)?.[1] ?? null; -/** In a Django project the console runs where manage.py is, with Django set up (PyCharm's Django Console). */ -async function django(): Promise<{ cwd: string; settings: string } | null> { - const manage = pickManage((await call(commands.findFilesNamed("manage.py")).catch(() => [])).map(String)); - const settings = manage && settingsModule((await call(commands.fsReadText(manage)).catch(() => null)) ?? ""); - return manage && settings ? { cwd: dirname(manage), settings } : null; +/** Environment that has the driver set Django up (PyCharm's Django Console), in a project with a manage.py. */ +async function djangoEnv(near: string | null): Promise> { + const manage = await findManage(near).catch(() => null); + if (!manage) return {}; + const settings = settingsModule((await call(commands.fsReadText(manage)).catch(() => null)) ?? ""); + // Without a literal settings module, Django is set up only if the environment names one. + return { OPENIDEA_DJANGO_DIR: dirname(manage), ...(settings && { OPENIDEA_DJANGO_SETTINGS: settings }) }; } -function config(python: string, cwd: string, settings?: string): RunConfig { +function config(python: string, cwd: string, env: Record): RunConfig { return { id: `${PREFIX}${crypto.randomUUID()}`, name: "Python Console", @@ -108,7 +110,7 @@ function config(python: string, cwd: string, settings?: string): RunConfig { command: python, args: ["-u", "-c", DRIVER], cwd, - env: settings ? { OPENIDEA_DJANGO_SETTINGS: settings } : {}, + env, detected: true, isTest: false, debugAdapter: null, @@ -148,9 +150,9 @@ export async function startConsole() { } // "system" chunks echo the command line, which is the driver's source here. }; - const site = await django(); + const env = await djangoEnv(active); if (mine !== generation) return; - const info = await call(commands.runStart(config(python, site?.cwd ?? root, site?.settings), channel, null)); + const info = await call(commands.runStart(config(python, root, env), channel, null)); if (mine !== generation) void call(commands.runStop(info.id)).catch(() => {}); else { runId = info.id; diff --git a/src/platform/django.test.ts b/src/platform/django.test.ts new file mode 100644 index 000000000..8fdac5b7a --- /dev/null +++ b/src/platform/django.test.ts @@ -0,0 +1,18 @@ +import { expect, it } from "vitest"; +import { pickManage } from "./django"; + +const PATHS = [ + "/p/.venv/lib/python3.12/site-packages/x/manage.py", + "/p/shop/manage.py", + "/p/blog/manage.py", + "/p/blog/admin/manage.py", +]; + +it("picks the manage.py of the file's own Django project", () => { + expect(pickManage(PATHS, "/p/shop/shop/views.py")).toBe("/p/shop/manage.py"); + expect(pickManage(PATHS, "/p/blog/admin/urls.py")).toBe("/p/blog/admin/manage.py"); + // Elsewhere (or no file): the shallowest, by name among equals; never an installed one. + expect(pickManage(PATHS, "/p/README.md")).toBe("/p/blog/manage.py"); + expect(pickManage(PATHS)).toBe("/p/blog/manage.py"); + expect(pickManage(PATHS.slice(0, 1))).toBeNull(); +}); diff --git a/src/platform/django.ts b/src/platform/django.ts new file mode 100644 index 000000000..52a0ab888 --- /dev/null +++ b/src/platform/django.ts @@ -0,0 +1,23 @@ +/** Django projects: the `manage.py` a file belongs to. */ +import { call, commands } from "./ipc"; + +const INSTALLED = /\/(?:site-packages|node_modules|\.venv|venv)\//; +const depth = (path: string) => path.split("/").length; + +/** + * The `manage.py` for `near` (a file or folder): the deepest one whose folder contains it, else + * the project's shallowest. Copies inside installed packages and virtualenvs don't count. + */ +export function pickManage(paths: readonly string[], near?: string | null): string | null { + const own = paths.filter((p) => !INSTALLED.test(p)); + const containing = near ? own.filter((p) => near.startsWith(p.slice(0, p.lastIndexOf("/") + 1))) : []; + const sorted = containing.length + ? containing.sort((a, b) => depth(b) - depth(a)) + : own.sort((a, b) => depth(a) - depth(b) || a.localeCompare(b)); + return sorted[0] ?? null; +} + +/** Looks the project's `manage.py` files up in the index (none while it is still building). */ +export async function findManage(near?: string | null): Promise { + return pickManage((await call(commands.findFilesNamed("manage.py"))).map(String), near); +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 048a594dc..dd3d99c3b 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4409,7 +4409,6 @@ "Run manage.py Task…": "Run manage.py Task…", "No manage.py in this project": "No manage.py in this project", "manage.py Tasks": "manage.py Tasks", - "Install django-types to complete Django model fields and managers": "Install django-types to complete Django model fields and managers", "Installing django-types": "Installing django-types", "Cannot install django-types": "Cannot install django-types", "Gutter": "Gutter", @@ -4437,5 +4436,7 @@ "Keep Key": "Keep Key", "Drop Index": "Drop Index", "Keep Index": "Keep Index", - "SQLite cannot drop the index of a primary key or unique constraint.": "SQLite cannot drop the index of a primary key or unique constraint." + "SQLite cannot drop the index of a primary key or unique constraint.": "SQLite cannot drop the index of a primary key or unique constraint.", + "Cannot list the manage.py commands": "Cannot list the manage.py commands", + "Install django-types into this project's virtual environment to complete Django model fields and managers": "Install django-types into this project's virtual environment to complete Django model fields and managers" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 4d3fcebda..2123190d1 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10943,7 +10943,6 @@ "Run manage.py Task…": "运行 manage.py 任务…", "No manage.py in this project": "此项目中没有 manage.py", "manage.py Tasks": "manage.py 任务", - "Install django-types to complete Django model fields and managers": "安装 django-types 以补全 Django 模型字段和管理器", "Installing django-types": "正在安装 django-types", "Cannot install django-types": "无法安装 django-types", "{formatted} credits": "{formatted} 积分", @@ -10968,5 +10967,7 @@ "Keep Key": "保留键", "Drop Index": "删除索引", "Keep Index": "保留索引", - "SQLite cannot drop the index of a primary key or unique constraint.": "SQLite 无法删除主键或唯一约束的索引。" + "SQLite cannot drop the index of a primary key or unique constraint.": "SQLite 无法删除主键或唯一约束的索引。", + "Cannot list the manage.py commands": "无法列出 manage.py 命令", + "Install django-types into this project's virtual environment to complete Django model fields and managers": "将 django-types 安装到此项目的虚拟环境,以补全 Django 模型字段和管理器" }