mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-21 08:03:38 +00:00
feat(python): create a Conda environment by name in conda's envs directory (#3839)
The Add Python Interpreter dialog asks for a Conda environment's name (the project folder's by default) instead of a location. The backend runs `conda create -n <name>` for a bare name, refuses a name conda already lists, and finds the new prefix from `conda env list`; a path still creates the environment at that prefix with `-p`.
This commit is contained in:
@@ -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<PathBuf> {
|
||||
pub(crate) fn conda_env_list_prefixes(output: &str) -> Vec<PathBuf> {
|
||||
output
|
||||
.lines()
|
||||
.map(|l| l.trim_start_matches(['#', '*', ' ']).trim_end())
|
||||
|
||||
@@ -26,7 +26,7 @@ pub enum VenvTool {
|
||||
Uv,
|
||||
/// `poetry env use <base>` in the project, then `poetry env info --path`.
|
||||
Poetry,
|
||||
/// `conda create -p <location> -y` (conda must be on PATH).
|
||||
/// `conda create -n <name> -y` for a bare name, else `-p <location>` (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 <location> -y` builds an environment at the requested prefix.
|
||||
/// `conda create -n <name> -y` builds a named environment in conda's envs directory when
|
||||
/// `location` is a bare name, `conda create -p <location> -y` one at that prefix otherwise.
|
||||
/// `base` pins the Python version (`python=<major.minor>`) 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<Sdk> {
|
||||
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::<Vec<_>>().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 <name>` for a bare name, `-p <prefix>` for a path, with the base's `major.minor` Python.
|
||||
pub(crate) fn conda_create_args(location: &Path, version: Option<&str>) -> Vec<String> {
|
||||
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::<Vec<_>>().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
|
||||
|
||||
@@ -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 <name>` makes <root>/envs/<name> 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();
|
||||
|
||||
@@ -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 <location> --python <base>` (uv must be on `PATH`).
|
||||
- **Poetry Environment**: `poetry env use <base>` in the project.
|
||||
- **Conda Environment**: `conda create -p <location>`, with the base interpreter's Python version.
|
||||
- **Conda Environment**: `conda create -n <name>` 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.
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
|
||||
- **Virtualenv 环境**:用你选的基础解释器执行 `python -m venv`。
|
||||
- **uv 环境**:执行 `uv venv <location> --python <base>`(`PATH` 上需要有 uv)。
|
||||
- **Poetry 环境**:在项目中执行 `poetry env use <base>`。
|
||||
- **Conda 环境**:执行 `conda create -p <location>`,Python 版本与基础解释器一致。
|
||||
- **Conda 环境**:执行 `conda create -n <名称>`,环境建在 conda 的 envs 目录中,Python 版本为所选版本。
|
||||
|
||||
也可以直接选择已有的解释器或环境目录。新解释器会成为项目解释器。
|
||||
|
||||
|
||||
+1
-1
@@ -11531,7 +11531,7 @@ export type VenvTool =
|
||||
"uv" |
|
||||
/** `poetry env use <base>` in the project, then `poetry env info --path`. */
|
||||
"poetry" |
|
||||
/** `conda create -p <location> -y` (conda must be on PATH). */
|
||||
/** `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH). */
|
||||
"conda";
|
||||
|
||||
/** What a view or custom editor shows. */
|
||||
|
||||
@@ -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" }));
|
||||
|
||||
@@ -37,6 +37,8 @@ export function AddInterpreterDialog({
|
||||
const bases = useMemo(() => list.filter((s) => s.source !== "venv"), [list]);
|
||||
const [base, setBase] = useState<string | null>(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<string | null>(null);
|
||||
const [browsed, setBrowsed] = useState<Sdk[]>([]);
|
||||
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 “<base> -m venv <location>”; the new interpreter becomes the project interpreter."),
|
||||
conda: tx(
|
||||
"Runs “conda create -p <location> python=<version>”: a new environment with only Python in it; the new interpreter becomes the project interpreter.",
|
||||
"Runs “conda create -n <name> python=<version>”: 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 <location> --python <base>”; the new interpreter becomes the project interpreter."),
|
||||
poetry: tx(
|
||||
@@ -191,28 +194,43 @@ export function AddInterpreterDialog({
|
||||
</div>
|
||||
{mode === "new" ? (
|
||||
<>
|
||||
<label htmlFor={ids.location}>
|
||||
<T>Location:</T>
|
||||
</label>
|
||||
<div className={styles.pathRow}>
|
||||
<Input
|
||||
id={ids.location}
|
||||
className={styles.pathInput}
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
disabled={kind === "poetry"}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
disabled={kind === "poetry"}
|
||||
onClick={async () => {
|
||||
const p = await choosePath({ directory: true, title: "Virtualenv Location", defaultPath: root });
|
||||
if (p) setLocation(p);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{kind === "conda" ? (
|
||||
<>
|
||||
<label htmlFor={ids.location}>
|
||||
<T>Name:</T>
|
||||
</label>
|
||||
<Input id={ids.location} value={envName} onChange={(e) => setEnvName(e.target.value)} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<label htmlFor={ids.location}>
|
||||
<T>Location:</T>
|
||||
</label>
|
||||
<div className={styles.pathRow}>
|
||||
<Input
|
||||
id={ids.location}
|
||||
className={styles.pathInput}
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
disabled={kind === "poetry"}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
disabled={kind === "poetry"}
|
||||
onClick={async () => {
|
||||
const p = await choosePath({
|
||||
directory: true,
|
||||
title: "Virtualenv Location",
|
||||
defaultPath: root,
|
||||
});
|
||||
if (p) setLocation(p);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<label htmlFor={ids.base}>{kind === "conda" ? <T>Python version:</T> : <T>Base interpreter:</T>}</label>
|
||||
<div className={styles.pathRow}>
|
||||
<Select
|
||||
|
||||
@@ -2327,5 +2327,6 @@
|
||||
"When off, Settings opens as a dialog in the project window, which is faster": "When off, Settings opens as a dialog in the project window, which is faster",
|
||||
"Run code inside the Java applications you start": "Run code inside the Java applications you start",
|
||||
"Java agents of {list} were not added: they load only in local projects.": "Java agents of {list} were not added: they load only in local projects.",
|
||||
"Java agent": "Java agent"
|
||||
"Java agent": "Java agent",
|
||||
"Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.": "Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter."
|
||||
}
|
||||
|
||||
@@ -5322,7 +5322,7 @@
|
||||
"{count} modified action": "已修改 {count} 个操作",
|
||||
"{count} modified actions": "已修改 {count} 个操作",
|
||||
"Runs “<base> -m venv <location>”; the new interpreter becomes the project interpreter.": "运行“<base> -m venv <location>”;新的解释器将成为项目解释器。",
|
||||
"Runs “conda create -p <location> python=<version>”: a new environment with only Python in it; the new interpreter becomes the project interpreter.": "运行“conda create -p <location> python=<version>”:新建一个只包含 Python 的环境;新的解释器将成为项目解释器。",
|
||||
"Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.": "运行“conda create -n <name> python=<version>”:在 conda 的 envs 目录中新建一个只包含 Python 的环境;新的解释器将成为项目解释器。",
|
||||
"Python version": "Python 版本",
|
||||
"Python {short}": "Python {short}",
|
||||
"Runs “poetry env use <base>” in the project; poetry keeps the environment under its own cache directory.": "在项目中运行“poetry env use <base>”;Poetry 会将环境保存在其自己的缓存目录下。",
|
||||
|
||||
Reference in New Issue
Block a user