diff --git a/crates/ide-sdk/src/discover.rs b/crates/ide-sdk/src/discover.rs index b4fe49a1d..8f463a958 100644 --- a/crates/ide-sdk/src/discover.rs +++ b/crates/ide-sdk/src/discover.rs @@ -116,7 +116,7 @@ fn is_python_name(name: &str) -> bool { /// Prefixes named by `conda env list`: `base * /opt/conda`, `myenv /opt/conda/envs/myenv`, /// a `--prefix` env shown as a bare path, comment lines skipped (#2240). -fn conda_env_list_prefixes(output: &str) -> Vec { +pub(crate) fn conda_env_list_prefixes(output: &str) -> Vec { output .lines() .map(|l| l.trim_start_matches(['#', '*', ' ']).trim_end()) diff --git a/crates/ide-sdk/src/python.rs b/crates/ide-sdk/src/python.rs index 729a9c2e6..98466971b 100644 --- a/crates/ide-sdk/src/python.rs +++ b/crates/ide-sdk/src/python.rs @@ -26,7 +26,7 @@ pub enum VenvTool { Uv, /// `poetry env use ` in the project, then `poetry env info --path`. Poetry, - /// `conda create -p -y` (conda must be on PATH). + /// `conda create -n -y` for a bare name, else `-p ` (conda must be on PATH). Conda, } @@ -121,7 +121,8 @@ fn create_poetry_env( .ok_or_else(|| IdeError::internal(format!("{} was not created", python.display()))) } -/// `conda create -p -y` builds an environment at the requested prefix. +/// `conda create -n -y` builds a named environment in conda's envs directory when +/// `location` is a bare name, `conda create -p -y` one at that prefix otherwise. /// `base` pins the Python version (`python=`) when it reports one, so the /// created env matches the interpreter the user picked rather than conda's default. fn create_conda_env( @@ -131,7 +132,9 @@ fn create_conda_env( cancel: &CancellationToken, on_line: &dyn Fn(String), ) -> IdeResult { - if location.join("conda-meta").is_dir() { + // A bare name is a named environment in conda's own envs directory (`conda create -n`). + let name = conda_env_name(location); + if name.is_none() && location.join("conda-meta").is_dir() { return Err(IdeError::new( ide_core::error::ErrorKind::AlreadyExists, format!("{} already contains a conda environment", location.display()), @@ -139,28 +142,60 @@ fn create_conda_env( } let conda = which("conda") .ok_or_else(|| IdeError::unavailable("conda is not installed (install it from https://docs.conda.io)"))?; - if let Some(parent) = location.parent() { + let prefixes = || { + query_in(&conda, &["env", "list"], None, &[], Duration::from_secs(15)) + .map(|list| crate::discover::conda_env_list_prefixes(&list)) + .unwrap_or_default() + }; + if let Some(name) = name { + if prefixes().iter().any(|p| p.file_name().is_some_and(|n| n == name)) { + return Err(IdeError::new( + ide_core::error::ErrorKind::AlreadyExists, + format!("A conda environment named {name} already exists"), + )); + } + } else if let Some(parent) = location.parent() { std::fs::create_dir_all(parent)?; } - let mut args = vec!["create".to_owned(), "-p".to_owned(), location.to_string_lossy().into_owned(), "-y".to_owned()]; - if let Some(version) = query_in(base, &["--version"], None, &[], Duration::from_secs(15)) - .and_then(|v| v.strip_prefix("Python ").map(str::to_owned)) - { - let short = version.split('.').take(2).collect::>().join("."); - if !short.is_empty() { - args.push(format!("python={short}")); - } - } - stream(&conda, &args, None, &[], cancel, on_line)?; + let version = query_in(base, &["--version"], None, &[], Duration::from_secs(15)) + .and_then(|v| v.strip_prefix("Python ").map(str::to_owned)); + stream(&conda, &conda_create_args(location, version.as_deref()), None, &[], cancel, on_line)?; + let prefix = match name { + Some(name) => prefixes() + .into_iter() + .find(|p| p.file_name().is_some_and(|n| n == name)) + .ok_or_else(|| IdeError::internal(format!("conda did not report the environment {name}")))?, + None => location.to_path_buf(), + }; // Conda keeps `python.exe` at the prefix root on Windows, not under Scripts/. - let python = [location.join(exe("python")), location.join(bin_dir()).join(exe("python"))] + let python = [prefix.join(exe("python")), prefix.join(bin_dir()).join(exe("python"))] .into_iter() .find(|p| p.is_file()) - .unwrap_or_else(|| location.join(bin_dir()).join(exe("python"))); - crate::discover::python_sdk(&python, "conda", location.parent().and_then(Path::parent)) + .unwrap_or_else(|| prefix.join(bin_dir()).join(exe("python"))); + crate::discover::python_sdk(&python, "conda", prefix.parent().and_then(Path::parent)) .ok_or_else(|| IdeError::internal(format!("{} was not created", python.display()))) } +/// The environment name when `location` is a bare name rather than a path. +fn conda_env_name(location: &Path) -> Option<&str> { + let text = location.to_str()?; + (!text.is_empty() && !text.contains(['/', '\\', ':']) && text != "." && text != "..").then_some(text) +} + +/// `conda create -n ` for a bare name, `-p ` for a path, with the base's `major.minor` Python. +pub(crate) fn conda_create_args(location: &Path, version: Option<&str>) -> Vec { + let mut args = match conda_env_name(location) { + Some(name) => vec!["create".to_owned(), "-n".to_owned(), name.to_owned()], + None => vec!["create".to_owned(), "-p".to_owned(), location.to_string_lossy().into_owned()], + }; + args.push("-y".to_owned()); + let short = version.map(|v| v.split('.').take(2).collect::>().join(".")).unwrap_or_default(); + if !short.is_empty() { + args.push(format!("python={short}")); + } + args +} + /// Arguments of `base -m venv location`. `-I` (isolated mode) keeps the working /// directory off `sys.path`: a project's `logging.py` or `typing.py` there would /// otherwise shadow the standard library modules venv imports. (`-P` does just diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index 72a8c6e6c..6608e3b94 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -1319,6 +1319,59 @@ fn an_existing_conda_environment_is_not_recreated() { assert!(err.message.contains("already contains a conda environment"), "{}", err.message); } +#[test] +fn conda_creates_named_environments_in_its_envs_directory() { + use crate::python::conda_create_args; + use std::path::Path; + assert_eq!(conda_create_args(Path::new("demo"), Some("3.12.4")), ["create", "-n", "demo", "-y", "python=3.12"]); + assert_eq!(conda_create_args(Path::new("/work/app/.conda"), None), ["create", "-p", "/work/app/.conda", "-y"]); + for path in [r"C:\envs\demo", "envs/demo", "D:demo", ".."] { + assert_eq!(conda_create_args(Path::new(path), None)[1], "-p", "{path}"); + } +} + +#[test] +#[cfg(unix)] +fn a_named_conda_environment_is_found_where_conda_put_it() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("miniconda3"); + let conda = tmp.path().join("conda"); + // `create -n ` makes /envs/ with a copy of the base python; `env list` names every env. + let python = tmp.path().join("python"); + std::fs::write(&python, "#!/bin/sh\necho 'Python 3.12.1'\n").unwrap(); + std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::write( + &conda, + format!( + "#!/bin/sh\nroot='{root}'\nif [ \"$1\" = env ]; then echo '# conda environments:'; echo \"base $root\"; \ + for e in \"$root\"/envs/*/; do [ -d \"$e\" ] && echo \"$(basename \"$e\") ${{e%/}}\"; done; exit 0; fi\n\ + [ \"$1 $2\" = 'create -n' ] || exit 2\nmkdir -p \"$root/envs/$3/bin\"\ncp '{python}' \"$root/envs/$3/bin/python\"\necho created\n", + root = root.display(), + python = python.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&conda, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::create_dir_all(&root).unwrap(); + let base = python.clone(); + let which = |tool: &str| (tool == "conda").then(|| conda.clone()); + let create = || { + crate::python::create_venv_with( + crate::python::VenvTool::Conda, + &base, + Path::new("ds"), + which, + &Default::default(), + &|_| {}, + ) + }; + let sdk = create().unwrap(); + assert_eq!(&*sdk.path, root.join("envs/ds/bin/python").as_path()); + let again = create().unwrap_err(); + assert!(again.message.contains("named ds already exists"), "{}", again.message); +} + #[test] fn neutral_dir_is_fresh_and_empty() { let a = crate::python::neutral_dir().unwrap(); diff --git a/docs/en/languages/python.mdx b/docs/en/languages/python.mdx index 07e950438..d249d3707 100644 --- a/docs/en/languages/python.mdx +++ b/docs/en/languages/python.mdx @@ -67,7 +67,7 @@ On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add - **Virtualenv Environment**: `python -m venv` from the base interpreter you pick. - **uv Environment**: `uv venv --python ` (uv must be on `PATH`). - **Poetry Environment**: `poetry env use ` in the project. -- **Conda Environment**: `conda create -p `, with the base interpreter's Python version. +- **Conda Environment**: `conda create -n ` in conda's envs directory, with the chosen Python version. You can also select an existing interpreter or environment folder. The new interpreter becomes the project interpreter. diff --git a/docs/zh/languages/python.mdx b/docs/zh/languages/python.mdx index 958adbb1a..9a5d1d156 100644 --- a/docs/zh/languages/python.mdx +++ b/docs/zh/languages/python.mdx @@ -67,7 +67,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml` - **Virtualenv 环境**:用你选的基础解释器执行 `python -m venv`。 - **uv 环境**:执行 `uv venv --python `(`PATH` 上需要有 uv)。 - **Poetry 环境**:在项目中执行 `poetry env use `。 -- **Conda 环境**:执行 `conda create -p `,Python 版本与基础解释器一致。 +- **Conda 环境**:执行 `conda create -n <名称>`,环境建在 conda 的 envs 目录中,Python 版本为所选版本。 也可以直接选择已有的解释器或环境目录。新解释器会成为项目解释器。 diff --git a/src/bindings.ts b/src/bindings.ts index 17c0a0a5c..853c6c545 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -11531,7 +11531,7 @@ export type VenvTool = "uv" | /** `poetry env use ` in the project, then `poetry env info --path`. */ "poetry" | -/** `conda create -p -y` (conda must be on PATH). */ +/** `conda create -n -y` for a bare name, else `-p ` (conda must be on PATH). */ "conda"; /** What a view or custom editor shows. */ diff --git a/src/features/settings/__tests__/addInterpreter.test.tsx b/src/features/settings/__tests__/addInterpreter.test.tsx index d9bf63082..39e612f99 100644 --- a/src/features/settings/__tests__/addInterpreter.test.tsx +++ b/src/features/settings/__tests__/addInterpreter.test.tsx @@ -94,21 +94,32 @@ describe("Add Python Interpreter", () => { mocks.createVenv.mockImplementation(() => new Promise((r) => (finish = r))); open(); await waitFor(() => expect(screen.getByRole("button", { name: "Base interpreter" })).toBeInTheDocument()); - for (const [label, tool] of [ - ["uv Environment", "uv"], - ["Conda Environment", "conda"], + // Conda asks for a name (the project's by default) and keeps the env in its envs directory. + for (const [label, tool, target] of [ + ["uv Environment", "uv", "/project/.venv"], + ["Conda Environment", "conda", "project"], ] as const) { fireEvent.click(screen.getByRole("button", { name: label })); fireEvent.click(screen.getByRole("button", { name: "OK" })); expect(mocks.createVenv).toHaveBeenLastCalledWith( tool, "/usr/bin/python3", - "/project/.venv", + target, expect.anything(), expect.anything(), ); await act(async () => finish(ok(VENV))); } + fireEvent.change(screen.getByLabelText("Name:"), { target: { value: " ds " } }); + fireEvent.click(screen.getByRole("button", { name: "OK" })); + expect(mocks.createVenv).toHaveBeenLastCalledWith( + "conda", + "/usr/bin/python3", + "ds", + expect.anything(), + expect.anything(), + ); + await act(async () => finish(ok(VENV))); fireEvent.click(screen.getByRole("button", { name: "Poetry Environment" })); await waitFor(() => expect(screen.getByLabelText("Location:")).toBeDisabled()); fireEvent.click(screen.getByRole("button", { name: "OK" })); diff --git a/src/features/settings/languages/AddInterpreterDialog.tsx b/src/features/settings/languages/AddInterpreterDialog.tsx index cfee5da91..9cc0a1f01 100644 --- a/src/features/settings/languages/AddInterpreterDialog.tsx +++ b/src/features/settings/languages/AddInterpreterDialog.tsx @@ -37,6 +37,8 @@ export function AddInterpreterDialog({ const bases = useMemo(() => list.filter((s) => s.source !== "venv"), [list]); const [base, setBase] = useState(null); const [location, setLocation] = useState(`${root}/.venv`); + // Conda keeps named environments in its own envs directory, so only a name is asked for. + const [envName, setEnvName] = useState(() => root.replaceAll("\\", "/").split("/").filter(Boolean).at(-1) ?? "env"); const [existing, setExisting] = useState(null); const [browsed, setBrowsed] = useState([]); const [busy, setBusy] = useState<{ cancel: () => void } | null>(null); @@ -92,6 +94,7 @@ export function AddInterpreterDialog({ }); }; + const target = (kind === "conda" ? envName : location).trim(); const ok = () => { if (busy) return; setError(null); @@ -103,9 +106,9 @@ export function AddInterpreterDialog({ }); return; } - if (!baseValue || !location.trim()) return; + if (!baseValue || !target) return; setLog([]); - const job = createVenv(kind, baseValue, location.trim(), (line) => setLog((l) => [...l.slice(-200), line])); + const job = createVenv(kind, baseValue, target, (line) => setLog((l) => [...l.slice(-200), line])); setBusy({ cancel: job.cancel }); job.promise .then((sdk) => { @@ -116,11 +119,11 @@ export function AddInterpreterDialog({ .finally(() => setBusy(null)); }; - const canOk = !busy && (mode === "new" ? !!baseValue && !!location.trim() : !!existing?.trim()); + const canOk = !busy && (mode === "new" ? !!baseValue && !!target : !!existing?.trim()); const note = { venv: tx("Runs “ -m venv ”; the new interpreter becomes the project interpreter."), conda: tx( - "Runs “conda create -p python=”: a new environment with only Python in it; the new interpreter becomes the project interpreter.", + "Runs “conda create -n python=”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.", ), uv: tx("Runs “uv venv --python ”; the new interpreter becomes the project interpreter."), poetry: tx( @@ -191,28 +194,43 @@ export function AddInterpreterDialog({ {mode === "new" ? ( <> - -
- setLocation(e.target.value)} - disabled={kind === "poetry"} - /> - { - const p = await choosePath({ directory: true, title: "Virtualenv Location", defaultPath: root }); - if (p) setLocation(p); - }} - /> -
+ {kind === "conda" ? ( + <> + + setEnvName(e.target.value)} /> + + ) : ( + <> + +
+ setLocation(e.target.value)} + disabled={kind === "poetry"} + /> + { + const p = await choosePath({ + directory: true, + title: "Virtualenv Location", + defaultPath: root, + }); + if (p) setLocation(p); + }} + /> +
+ + )}