feat(run): choose the Python interpreter of a run configuration from a list (#6382)

Python and Django test run configurations get an Interpreter dropdown: Project default, each detected interpreter (minus those removed on All Interpreters), or Custom command, which shows the Command field for runners such as uv or poetry. The chosen interpreter's path is stored as the command, so command lines, the backend and .run.xml import are unchanged; existing configurations open with the choice their command stands for, and a missing interpreter is shown as not found. With a run-target project interpreter only Project default and Custom command are offered. RunConfigTypeField gains an optional set(value, params) so a select can stand for other params.

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-27 15:17:30 +08:00
1 джерело 661124d0d4
коміт be83458161
7 files changed
+240 -11

No files matched your search

+9 -5
Переглянути файл
@@ -618,7 +618,9 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
params={params}
all={all}
invalid={!!errors[f.key]}
onChange={(v) => setParam(f.key, v)}
onChange={(v) =>
f.set ? onChange(withParams(config, f.set(v, params), type)) : setParam(f.key, v)
}
/>
</Field>
))
@@ -971,24 +973,26 @@ function TypeField({
const root = useProject((s) => s.project?.root ?? null);
const listId = `run-field-${field.key}`;
const [loaded, setLoaded] = useState<ReadonlyArray<{ value: string; label: string; detail?: string }>>([]);
// A select that stands for other params shows the value worked out from them.
const shown = field.control === "select" && field.value ? field.value(params) : value;
useEffect(() => {
let live = true;
void field
.loadOptions?.()
.loadOptions?.(shown)
.then((options) => live && setLoaded(options))
.catch(() => {});
return () => {
live = false;
};
}, [field]);
}, [field, shown]);
if (field.control === "output") return <OutputField label={field.label} text={field.value?.(params) ?? ""} />;
if (field.control === "select") {
// Loaded options are detected data (JDKs, build modules), not catalog text.
const options: SelectOption[] = [...(field.options ?? []), ...loaded.map((o) => ({ ...o, verbatim: true }))];
if (value && !options.some((o) => o.value === value)) options.push({ value, label: value, verbatim: true });
if (shown && !options.some((o) => o.value === shown)) options.push({ value: shown, label: shown, verbatim: true });
return (
<Select
value={value || (options[0]?.value ?? "")}
value={shown || (options[0]?.value ?? "")}
options={options}
onChange={onChange}
aria-label={field.label}
+3
Переглянути файл
@@ -7,6 +7,7 @@
import type { RunConfig } from "@/platform/ipc";
import type { RunConfigTypeContribution } from "@/workbench/contributions";
import { formatArgs, parseArgs } from "./configs";
import { customCommandVisible, interpreterField } from "./pythonTypes";
/** A Django project: it has a Django tests configuration (detected from `manage.py`, or made in the form). */
export const hasDjangoTests = (configs: readonly RunConfig[]) => configs.some((c) => c.kind === "django-test");
@@ -61,6 +62,7 @@ export const djangoTestType: RunConfigTypeContribution = {
defaults: { command: "python3" },
debugAdapter: "debugpy",
fields: [
interpreterField,
{
key: "command",
label: "Command",
@@ -68,6 +70,7 @@ export const djangoTestType: RunConfigTypeContribution = {
placeholder: "python3",
required: true,
hint: "e.g. python3, .venv/bin/python, uv, poetry",
visible: customCommandVisible,
},
{
key: "runnerArgs",
+128
Переглянути файл
@@ -0,0 +1,128 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
const ipc = vi.hoisted(() => ({
detect: vi.fn(),
probe: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/platform/ipc")>();
return {
...actual,
commands: {
...actual.commands,
sdkDetect: (kind: string) => Promise.resolve({ status: "ok", data: ipc.detect(kind) }),
sdkPythonInterpreter: (path: string) => Promise.resolve({ status: "ok", data: ipc.probe(path) }),
},
};
});
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { ConfigForm } from "./ConfigForm";
import {
chooseInterpreter,
CUSTOM_INTERPRETER,
interpreterChoice,
interpreterOptions,
pythonType,
} from "./pythonTypes";
import { formParams, newConfigOfType, withParams } from "./types";
const VENV = "/work/app/.venv/bin/python";
const PYPY = "/opt/pypy/bin/pypy3";
const sdk = (path: string, name: string) => ({ path, name, version: null, source: "venv", home: null, extra: null });
afterEach(() => {
cleanup();
useProject.setState({ settings: null } as never);
ipc.detect.mockReset();
ipc.probe.mockReset();
});
describe("Python run configuration interpreter", () => {
it("opens configurations made before the dropdown with the choice their command means", () => {
expect(interpreterChoice({ command: "python3" })).toBe("");
expect(interpreterChoice({ command: "python.exe" })).toBe("");
expect(interpreterChoice({})).toBe("");
expect(interpreterChoice({ command: VENV })).toBe(VENV);
expect(interpreterChoice({ command: "C:\\envs\\app\\Scripts\\python.exe" })).toBe(
"C:\\envs\\app\\Scripts\\python.exe",
);
// A runner, a relative path or another executable keeps its command.
expect(interpreterChoice({ command: "uv" })).toBe(CUSTOM_INTERPRETER);
expect(interpreterChoice({ command: ".venv/bin/python" })).toBe(CUSTOM_INTERPRETER);
expect(interpreterChoice({ command: "/usr/local/bin/uv" })).toBe(CUSTOM_INTERPRETER);
});
it("stores the chosen interpreter's path as the command, so the command line is the same as typing it", () => {
const python = pythonType;
const before = { mode: "script", script: "main.py", runnerArgs: "-u", command: "uv" };
const picked = chooseInterpreter(PYPY, before);
expect(picked).toEqual({ ...before, interpreter: PYPY, command: PYPY });
// Not named `python…`: the recorded choice keeps it selected.
expect(interpreterChoice(picked)).toBe(PYPY);
expect(python.commandLine(picked)).toEqual({ command: PYPY, args: ["-u", "main.py"] });
const custom = chooseInterpreter(CUSTOM_INTERPRETER, picked);
expect(interpreterChoice(custom)).toBe(CUSTOM_INTERPRETER);
// Typing an interpreter's path as the custom command keeps the Custom command choice.
expect(interpreterChoice({ ...custom, command: VENV })).toBe(CUSTOM_INTERPRETER);
const fallback = chooseInterpreter("", { ...custom, command: "uv" });
expect(fallback).not.toHaveProperty("interpreter");
expect(interpreterChoice(fallback)).toBe("");
expect(python.commandLine(fallback)?.command).toMatch(/^python3?$/);
});
it("leaves the command line of an existing configuration unchanged", () => {
const python = pythonType;
for (const command of ["python", "python3", ".venv/bin/python", VENV, "uv"]) {
const config: RunConfig = { ...newConfigOfType(python, []), command, args: ["main.py"], params: undefined };
const params = formParams(config, python)!;
expect(python.commandLine(params)).toEqual({ command, args: ["main.py"] });
}
});
it("lists detected interpreters, minus removed ones, and marks a chosen one that is gone", async () => {
useProject.setState({ settings: { languages: { python: { hiddenInterpreters: ["/usr/bin/python3"] } } } } as never);
ipc.detect.mockReturnValue([sdk(VENV, "Python 3.12 (app)"), sdk("/usr/bin/python3", "Python 3.9")]);
ipc.probe.mockImplementation((path: string) => (path === PYPY ? sdk(PYPY, "PyPy 3.10") : null));
expect(await interpreterOptions("")).toEqual([{ value: VENV, label: "Python 3.12 (app)", detail: VENV }]);
expect((await interpreterOptions(PYPY)).at(-1)).toEqual({ value: PYPY, label: "PyPy 3.10", detail: PYPY });
expect((await interpreterOptions("/gone/bin/python")).at(-1)).toMatchObject({
value: "/gone/bin/python",
label: "/gone/bin/python (not found)",
});
});
it("offers no local interpreter when the project interpreter is a run target's", async () => {
useProject.setState({ settings: { languages: { python: { interpreter: "target:docker-app" } } } } as never);
ipc.detect.mockReturnValue([sdk(VENV, "Python 3.12 (app)")]);
expect(await interpreterOptions(VENV)).toEqual([]);
});
it("shows the Command field only for Custom command", async () => {
ipc.detect.mockReturnValue([sdk(VENV, "Python 3.12 (app)")]);
const type = pythonType;
const base = newConfigOfType(type, []);
const config = withParams(base, { ...base.params, script: "main.py", command: "uv", runnerArgs: "run python" });
const changed = vi.fn();
render(<ConfigForm config={config} all={[config]} type={type} errors={{}} onChange={changed} modifyRequest={0} />);
expect(screen.getByRole("button", { name: "Interpreter" })).toHaveTextContent("Custom command");
expect(screen.getByRole("textbox", { name: "Command" })).toHaveValue("uv");
fireEvent.click(screen.getByRole("button", { name: "Interpreter" }));
fireEvent.click(await screen.findByRole("option", { name: /Python 3\.12 \(app\)/ }));
const next = changed.mock.lastCall![0] as RunConfig;
expect(next).toMatchObject({ command: VENV, args: ["run", "python", "main.py"] });
cleanup();
render(<ConfigForm config={next} all={[next]} type={type} errors={{}} onChange={changed} modifyRequest={0} />);
// Named once the detected interpreters are in.
await waitFor(() =>
expect(screen.getByRole("button", { name: "Interpreter" })).toHaveTextContent("Python 3.12 (app)"),
);
expect(screen.queryByRole("textbox", { name: "Command" })).toBeNull();
});
});
+81 -1
Переглянути файл
@@ -4,13 +4,91 @@
* the runner args its leading arguments (`run python` for uv / poetry, `-u`). A plain
* `python` / `python3` runs on the project interpreter: the backend swaps it at launch.
*/
import type { RunConfigTypeContribution } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import type { RunConfigTypeContribution, RunConfigTypeField } from "@/workbench/contributions";
import { formatArgs, parseArgs } from "./configs";
import { isWindows } from "./jvmTypes";
/** `python` on Windows (where `python3` is not a command), `python3` elsewhere. */
export const systemPython = () => (isWindows() ? "python" : "python3");
/** The Interpreter choice that shows the Command field (`uv`, `poetry`, a relative path). */
export const CUSTOM_INTERPRETER = "custom";
const isPlainPython = (command: string) => /^python3?(\.exe)?$/i.test(command);
const isAbsolute = (path: string) => /^([A-Za-z]:[\\/]|[\\/])/.test(path);
/** The executable names the backend runs as an interpreter of its own (`python`, `python3`, `python3.12`). */
const isPythonExecutable = (path: string) => /(^|[\\/])python(3(\.\d+)?)?(\.exe)?$/i.test(path);
/**
* The Interpreter dropdown's value: `""` (Project default), an interpreter's path, or
* {@link CUSTOM_INTERPRETER}. The command is what runs; `params.interpreter` only records a
* choice the command cannot tell (Custom command, an interpreter not named `python…`), so
* configurations made before the dropdown open with the choice their command means.
*/
export function interpreterChoice(params: Readonly<Record<string, string>>): string {
const command = params.command?.trim() ?? "";
const chosen = params.interpreter;
if (chosen === CUSTOM_INTERPRETER || (chosen && chosen === command)) return chosen;
if (!command || isPlainPython(command)) return "";
return isAbsolute(command) && isPythonExecutable(command) ? command : CUSTOM_INTERPRETER;
}
/** `params` after choosing `choice` in the Interpreter dropdown. */
export function chooseInterpreter(choice: string, params: Readonly<Record<string, string>>): Record<string, string> {
const { interpreter: _previous, ...rest } = params;
if (choice === CUSTOM_INTERPRETER) return { ...rest, interpreter: CUSTOM_INTERPRETER };
if (!choice) return { ...rest, command: systemPython() };
return { ...rest, interpreter: choice, command: choice };
}
/**
* The detected interpreters (those removed on All Interpreters left out), and the chosen one
* when detection doesn't list it: by its name if it still runs, else marked as not found.
* None when the project interpreter is a run target's: a local path would not run there.
*/
export async function interpreterOptions(
chosen: string,
): Promise<Array<{ value: string; label: string; detail?: string }>> {
const python = useProject.getState().settings?.languages?.python;
if (python?.interpreter?.trim().startsWith("target:")) return [];
const key = (path: string) => path.replace(/\\/g, "/").replace(/\/+$/, "");
const hidden = new Set((python?.hiddenInterpreters ?? []).map(key));
const sdks = await call(commands.sdkDetect("python"));
const out = sdks
.filter((sdk) => !hidden.has(key(String(sdk.path))))
.map((sdk) => ({ value: String(sdk.path), label: sdk.name || String(sdk.path), detail: String(sdk.path) }));
if (chosen && chosen !== CUSTOM_INTERPRETER && !out.some((o) => o.value === chosen)) {
const sdk = await call(commands.sdkPythonInterpreter(chosen)).catch(() => null);
out.push(
sdk
? { value: chosen, label: sdk.name || chosen, detail: chosen }
: { value: chosen, label: tx`${chosen} (not found)`, detail: tx("The interpreter does not exist") },
);
}
return out;
}
/** PyCharm's Python Interpreter: Project default, a detected interpreter, or a command of its own. */
export const interpreterField: RunConfigTypeField = {
key: "interpreter",
label: "Interpreter",
control: "select",
options: [
{ value: "", label: "Project default" },
{ value: CUSTOM_INTERPRETER, label: "Custom command" },
],
loadOptions: interpreterOptions,
value: interpreterChoice,
set: chooseInterpreter,
};
/** The Command field, shown for the Custom command choice. */
export const customCommandVisible = (p: Readonly<Record<string, string>>) =>
interpreterChoice(p) === CUSTOM_INTERPRETER;
export const pythonType: RunConfigTypeContribution = {
id: "python",
label: "Python",
@@ -49,6 +127,7 @@ export const pythonType: RunConfigTypeContribution = {
visible: (p) => p.mode === "module",
},
{ key: "args", label: "Arguments", mono: true, placeholder: "Space separated; quote with ' or \"" },
interpreterField,
{
key: "command",
label: "Command",
@@ -56,6 +135,7 @@ export const pythonType: RunConfigTypeContribution = {
placeholder: "python3",
required: true,
hint: "e.g. python3, .venv/bin/python, uv, poetry",
visible: customCommandVisible,
},
{
key: "runnerArgs",
+4 -1
Переглянути файл
@@ -4232,5 +4232,8 @@
"Export to Text File…": "Export to Text File…",
"Export to Text File": "Export to Text File",
"Save the Find Usages results as a text file": "Save the Find Usages results as a text file",
"Cannot export the usages": "Cannot export the usages"
"Cannot export the usages": "Cannot export the usages",
"Custom command": "Custom command",
"{chosen} (not found)": "{chosen} (not found)",
"The interpreter does not exist": "The interpreter does not exist"
}
+4 -1
Переглянути файл
@@ -10695,5 +10695,8 @@
"Export to Text File…": "导出到文本文件…",
"Export to Text File": "导出到文本文件",
"Save the Find Usages results as a text file": "将查找用法的结果保存为文本文件",
"Cannot export the usages": "无法导出用法"
"Cannot export the usages": "无法导出用法",
"Custom command": "自定义命令",
"{chosen} (not found)": "{chosen}(未找到)",
"The interpreter does not exist": "解释器不存在"
}
+11 -3
Переглянути файл
@@ -1842,14 +1842,22 @@ export interface RunConfigTypeField {
rows?: number;
placeholder?: string;
options?: ReadonlyArray<{ value: string; label: string; detail?: string }>;
/** A `select`'s further options, read when the form shows it (installed JDKs, build modules). */
loadOptions?(): Promise<ReadonlyArray<{ value: string; label: string; detail?: string }>>;
/**
* A `select`'s further options, read when the form shows it and when its value changes
* (installed JDKs, build modules); `value` is the current one.
*/
loadOptions?(value: string): Promise<ReadonlyArray<{ value: string; label: string; detail?: string }>>;
/** Values offered while typing (e.g. the scripts of detected configurations). */
suggestions?(configs: readonly RunConfig[], params: Readonly<Record<string, string>>): string[];
required?: boolean;
visible?(params: Readonly<Record<string, string>>): boolean;
/** An `output` field's text. */
/**
* An `output` field's text; for a `select`, the value it shows when that is worked out
* from other params (with `set` writing them back).
*/
value?(params: Readonly<Record<string, string>>): string;
/** The params after choosing `value`, for a field that stands for other params (see `value`). */
set?(value: string, params: Readonly<Record<string, string>>): Record<string, string>;
/** Why a non-empty value is invalid, or null. */
validate?(value: string, params: Readonly<Record<string, string>>): string | null;
/** Shown under the control. */