feat(python): create and detect Hatch environments (#5450)

"Add Python Interpreter" has a new **Hatch Environment** type. It lists the environments the project defines (`hatch env show --json`, without Hatch's internal `hatch-*` ones), runs `hatch env create <env>` with the chosen base interpreter as `HATCH_PYTHON`, and the result becomes the project interpreter. Hatch keeps an environment that already exists, whatever `HATCH_PYTHON` says. So if it was built on another Python version, nothing is changed and the dialog says so, rather than reporting it as created. The project's Hatch environments are also detected, with their own icon: `default` is listed as `Python 3.13 (Hatch: <project>)` and the others as `Python 3.13 (Hatch: <project>:<env>)`. The `default` one is the project interpreter when none is configured (after a `.venv` or pixi environment in the project, before the mise/asdf pin).
Until now Hatch was only a run wrapper (`hatch run`), and its data directory was not searched, so its environments never appeared. Detection does not start hatch:
- Hatch keeps environments at `<data>/env/virtual/<project name>/<project id>/<env>`, where the id is the first 8 characters of the URL-safe base64 SHA-256 of the project path.
- On Windows and macOS Hatch case-folds the path first (`ß` becomes `ss`); the IDE does the same for the letters a path is likely to hold.
- The project is the nearest folder, the opened one or above, with a `pyproject.toml` or `setup.py`, as for Hatch.
- The data directory is `HATCH_DATA_DIR` or the platform default.

Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
LU XIANGRUI
2026-11-24 05:24:23 +08:00
committed by GitHub
co-authored by wildcatDownstairs
parent b5bff2fdfa
commit fe9ee6a7a7
18 changed files with 812 additions and 67 deletions
+15 -2
View File
@@ -379,8 +379,20 @@ pub async fn sdk_locate_tools(
.map_err(join_err)
}
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry` / `pipenv`); output streams through
/// `on_output`. `install_packages` also installs what the project's `Pipfile` declares (pipenv).
/// The environments the window's project defines for Hatch, `default` first (hatch must be on PATH).
#[command(trust = outside_restricted)]
pub async fn sdk_python_hatch_envs(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<String>> {
host.require_trust_if_project(window)?;
let root = host.project(window)?.root.clone();
let cancel = host.begin_project_request(window, request);
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::hatch_envs(&root, &cancel)).await.map_err(join_err);
host.end_request(request);
result?
}
/// Creates a Python environment and streams its output through `on_output`.
/// With Pipenv, `install_packages` also installs the packages declared in the project's `Pipfile`.
#[allow(clippy::too_many_arguments)]
#[command(trust = outside_restricted)]
pub async fn sdk_python_create_venv(
@@ -664,6 +676,7 @@ ide_command::domain!(
sdk_project_libraries,
sdk_python_create_venv,
sdk_python_effective,
sdk_python_hatch_envs,
sdk_python_interpreter,
sdk_python_packages,
sdk_python_pip,
+2 -2
View File
@@ -66,8 +66,8 @@ pub fn ruff_configuration(root: &Path, configured: &str) -> IdeResult<Option<Pat
/// The project interpreter: the configured one, else a project virtualenv
/// (`.venv`, `venv`, …) or pixi environment (`.pixi/envs/<env>`) in the project
/// root, else the project's Pipenv environment, else the Python the project pins
/// for mise / asdf. A configured interpreter whose executable is gone (uninstalled,
/// root, else the project's Pipenv environment, else its `default` Hatch environment,
/// else the Python the project pins for mise / asdf. A configured interpreter whose executable is gone (uninstalled,
/// moved) is skipped like PyCharm's "Invalid" SDKs, so runs fall back instead of
/// failing on a dead path.
/// `None` when the project interpreter is a run target's (see [`crate::container_python`]).
+337 -14
View File
@@ -1,10 +1,11 @@
//! Finding installed interpreters and toolchains.
use crate::exec::{executables_in, query, search_path, which};
use crate::python::hatch_env_paths;
use crate::{Sdk, SdkKind, bin_dir, exe, home_dir, pinned, venv_of};
use ide_core::process::{host_var_os, host_var_os_in};
use ide_core::version_managers::{self, Tool};
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::time::Duration;
@@ -19,7 +20,7 @@ const CONDA_ENV_LIST_TIMEOUT: Duration = Duration::from_secs(12);
/// `--version` queries in parallel.
pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
let mut out = match kind {
SdkKind::Python => python(root),
SdkKind::Python => python(root, which),
SdkKind::Node => node(),
SdkKind::Php => php(),
SdkKind::PackageManager => package_managers(),
@@ -55,7 +56,7 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
fn pinned_first(sdks: &mut Vec<Sdk>, kind: SdkKind, root: &Path) {
let Some((dir, _)) = tool_of(kind).and_then(|t| pinned::pinned_install(root, t)) else { return };
let Some(i) = sdks.iter().position(|s| s.path.starts_with(&dir)) else { return };
let at = sdks.iter().take_while(|s| matches!(s.source.as_str(), "venv" | "pipenv")).count().min(i);
let at = sdks.iter().take_while(|s| matches!(s.source.as_str(), "venv" | "pipenv" | "hatch")).count().min(i);
let sdk = sdks.remove(i);
sdks.insert(at, sdk);
}
@@ -82,7 +83,7 @@ fn dedupe_by_real_path(paths: Vec<(PathBuf, &'static str)>) -> Vec<(PathBuf, &'s
pub(crate) const PROJECT_VENVS: [&str; 4] = [".venv", "venv", "env", ".env"];
/// `<root>/<venv>/bin/python` of the first project virtualenv or pixi environment, else the
/// interpreter of the project's Pipenv environment.
/// interpreter of the project's Pipenv environment or its `default` Hatch environment, in that order.
pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
PROJECT_VENVS
.iter()
@@ -96,6 +97,7 @@ pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
})
})
.or_else(|| pipenv_env_python(root))
.or_else(|| hatch_default_python(root))
}
/// Pipenv's active workon home first, followed by the other conventional location.
@@ -278,6 +280,138 @@ fn poetry_venv_dirs(host: Host, home: &Path, env: impl Fn(&str) -> Option<OsStri
var("POETRY_VIRTUALENVS_PATH").into_iter().chain([cache.join("virtualenvs")]).collect()
}
/// Hatch's name for the environment every project has.
const DEFAULT_HATCH_ENV: &str = "default";
/// Where Hatch keeps virtual environments: `env/virtual` in its data directory, which is
/// `HATCH_DATA_DIR`, else `%LOCALAPPDATA%\hatch` (Windows), `~/Library/Application Support/hatch`
/// (macOS) or `$XDG_DATA_HOME/hatch` / `~/.local/share/hatch`.
fn hatch_env_dir(host: Host, home: &Path, env: impl Fn(&str) -> Option<OsString>) -> PathBuf {
let var = |key: &str| env(key).filter(|v| !v.is_empty()).map(PathBuf::from);
let data = var("HATCH_DATA_DIR").unwrap_or_else(|| match host {
Host::Windows => var("LOCALAPPDATA").unwrap_or_else(|| home.join("AppData").join("Local")).join("hatch"),
Host::Mac => home.join("Library/Application Support/hatch"),
Host::Unix => var("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share")).join("hatch"),
});
data.join("env").join("virtual")
}
/// The folder name Hatch derives from a project's path: the first 8 characters of the URL-safe
/// base64 SHA-256 of the path, which it case-folds on Windows and macOS.
fn hatch_project_id(host: Host, root: &Path) -> String {
use base64::Engine;
use sha2::Digest;
let path = root.to_string_lossy();
let path = if matches!(host, Host::Unix) { path.into_owned() } else { casefold(&path) };
let mut id = base64::engine::general_purpose::URL_SAFE.encode(sha2::Sha256::digest(path.as_bytes()));
id.truncate(8);
id
}
/// Python's `str.casefold()` for the letters a path is likely to hold: lower case, with the
/// letters that case-fold to more than their lower case expanded (`ß` → `ss`). `ponytail:` the
/// rest of Unicode's full case folding (Cherokee, Greek symbol variants, iota subscripts) is
/// lower-cased only; a project path with them gets no default environment picked.
fn casefold(text: &str) -> String {
text.chars().fold(String::with_capacity(text.len()), |mut out, c| {
match c {
'ß' | 'ẞ' => out.push_str("ss"),
'ſ' => out.push('s'),
'ς' => out.push('σ'),
'µ' => out.push('μ'),
'ff' => out.push_str("ff"),
'fi' => out.push_str("fi"),
'fl' => out.push_str("fl"),
'ffi' => out.push_str("ffi"),
'ffl' => out.push_str("ffl"),
'ſt' | 'st' => out.push_str("st"),
_ => out.extend(c.to_lowercase()),
}
out
})
}
/// The Hatch project and environment a virtualenv is, told by where it lives:
/// `…/env/virtual/<project name>/<project id>/<environment>`, the `default` environment being
/// the one named after the project. `None` for Hatch's internal environments (`hatch-test.py3.12`, …).
fn hatch_env(venv: &Path) -> Option<(String, String)> {
let project = venv.parent()?.parent()?;
if !project.parent()?.ends_with("env/virtual") {
return None;
}
let (name, project) = (venv.file_name()?.to_string_lossy(), project.file_name()?.to_string_lossy());
if name == project {
return Some((project.into_owned(), DEFAULT_HATCH_ENV.to_owned()));
}
(!name.starts_with("hatch-")).then(|| (project.into_owned(), name.into_owned()))
}
/// The folder Hatch takes as the project for `root`: the nearest one, `root` or above it, with a
/// `pyproject.toml` or `setup.py`, else `root` itself when it has a `hatch.toml`.
fn hatch_project_root(root: &Path) -> Option<PathBuf> {
root.ancestors()
.find(|dir| dir.join("pyproject.toml").is_file() || dir.join("setup.py").is_file())
.or_else(|| root.join("hatch.toml").is_file().then_some(root))
.map(Path::to_path_buf)
}
pub(crate) fn hatch_project_config(root: &Path) -> Option<(PathBuf, toml::Value)> {
fn read(path: &Path) -> Option<toml::Value> {
if !path.is_file() {
return None;
}
toml::from_str(&std::fs::read_to_string(path).ok()?).ok()
}
let project = hatch_project_root(root)?;
let config = project.join("hatch.toml");
let settings = if config.is_file() {
read(&config)?
} else {
let metadata = read(&project.join("pyproject.toml"))?;
metadata.get("tool")?.get("hatch").filter(|config| config.is_table())?.clone()
};
Some((project, settings))
}
/// Resolve the default when applying a runtime or language server without starting Hatch.
fn hatch_default_python(root: &Path) -> Option<PathBuf> {
let (project, config) = hatch_project_config(root)?;
let custom = host_var_os_in(&project, "HATCH_ENV_TYPE_VIRTUAL_PATH").filter(|p| !p.is_empty()).or_else(|| {
config.get("envs")?.get(DEFAULT_HATCH_ENV)?.get("path")?.as_str().filter(|p| !p.is_empty()).map(Into::into)
});
if let Some(home) = custom {
let home = PathBuf::from(home);
let home = if home.is_absolute() { home } else { dunce::canonicalize(project.join(home)).ok()? };
let python = home.join(bin_dir()).join(exe("python"));
return (home.join("pyvenv.cfg").is_file() && python.is_file()).then_some(python);
}
stored_hatch_env_pythons(&project)
.into_iter()
.find(|p| venv_of(p).and_then(|v| hatch_env(&v)).is_some_and(|(_, env)| env == DEFAULT_HATCH_ENV))
}
fn stored_hatch_env_pythons(project: &Path) -> Vec<PathBuf> {
let Some(home) = home_dir() else { return Vec::new() };
hatch_envs_in(project, &hatch_env_dir(Host::current(), &home, |key| host_var_os(key)), Host::current())
}
fn hatch_envs_in(root: &Path, storage: &Path, host: Host) -> Vec<PathBuf> {
// Hatch hashes the path it was started in, which may or may not have its symlinks resolved.
let mut ids: Vec<String> = [Some(root.to_path_buf()), dunce::canonicalize(root).ok()]
.into_iter()
.flatten()
.map(|path| hatch_project_id(host, &path))
.collect();
ids.dedup();
subdirs(storage)
.iter()
.flat_map(|project| ids.iter().flat_map(|id| subdirs(&project.join(id))))
.filter(|env| hatch_env(env).is_some())
.map(|env| env.join(bin_dir()).join(exe("python")))
.filter(|python| python.is_file())
.collect()
}
/// Where uv installs Pythons (`uv python dir`): `UV_PYTHON_INSTALL_DIR`, else `python` in its
/// data dir — `%APPDATA%\uv` on Windows (`%APPDATA%\uv\data` when an older uv made it), else
/// `$XDG_DATA_HOME/uv` / `~/.local/share/uv` (older uv on macOS: `~/Library/Application Support/uv`).
@@ -302,9 +436,21 @@ fn uv_python(install: &Path) -> Option<PathBuf> {
[install.join(exe("python")), install.join("bin").join(exe("python3"))].into_iter().find(|p| p.is_file())
}
fn python(root: Option<&Path>) -> Vec<Sdk> {
fn python(root: Option<&Path>, which_hatch: impl Fn(&str) -> Option<PathBuf>) -> Vec<Sdk> {
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
let hatch_project = root.and_then(hatch_project_config).map(|(project, _)| project);
let mut hatch_names = HashMap::new();
if let Some(root) = root {
if let Some(project) = &hatch_project {
if let Some(envs) = which_hatch("hatch").and_then(|hatch| hatch_env_paths(project, &hatch)) {
for (path, name) in envs {
hatch_names.entry(path.clone()).or_insert(name);
found.push((path, "venv"));
}
} else {
found.extend(stored_hatch_env_pythons(project).into_iter().map(|p| (p, "venv")));
}
}
for v in PROJECT_VENVS {
let dir = root.join(v);
if dir.join("pyvenv.cfg").is_file() {
@@ -343,6 +489,12 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
for v in subdirs(&pyenv.join("versions")) {
found.push((v.join(bin_dir()).join(exe("python")), "pyenv"));
}
// Hatch environments of every project: `<project name>/<project id>/<environment>`.
for project in subdirs(&hatch_env_dir(Host::current(), &home, var)) {
for env in subdirs(&project).iter().flat_map(|id| subdirs(id)).filter(|env| hatch_env(env).is_some()) {
found.push((env.join(bin_dir()).join(exe("python")), "venv"));
}
}
for dir in uv_python_dirs(Host::current(), &home, var) {
found.extend(subdirs(&dir).iter().filter_map(|v| uv_python(v)).map(|p| (p, "uv")));
}
@@ -431,7 +583,8 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
.filter(|(p, _)| p.is_file() && usable(p))
.filter(|(p, source)| {
if *source == "venv" || venv_of(p).is_some() {
seen_venv.insert(venv_of(p).unwrap_or_else(|| p.clone()))
let home = venv_of(p).unwrap_or_else(|| p.clone());
seen_venv.insert(dunce::canonicalize(&home).unwrap_or(home))
} else {
seen_real.insert(p.canonicalize().unwrap_or_else(|_| p.clone()))
}
@@ -442,7 +595,10 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
},
)
.collect();
par_map(&candidates, |(path, source)| python_sdk(path, source, root))
par_map(&candidates, |(path, source)| match (*source, &hatch_project, hatch_names.get(path)) {
("venv", Some(project), Some(name)) => hatch_sdk(path, project, name),
_ => python_sdk(path, source, root),
})
}
/// A runnable Python executable or virtualenv folder, named like detected SDKs.
@@ -475,26 +631,53 @@ pub fn python_interpreter_sdk(path: &Path, root: Option<&Path>) -> Option<Sdk> {
} else {
"system"
};
Some(python_sdk_with_version(&path, source, root, version))
Some(python_sdk_with_version(&path, source, root, version, None))
}
pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Option<Sdk> {
let version = query(path, &["--version"], VERSION_TIMEOUT)
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned))
.or_else(|| pyvenv_version(path))?;
Some(python_sdk_with_version(path, source, root, version))
Some(python_sdk_with_version(path, source, root, python_version(path)?, None))
}
fn python_sdk_with_version(path: &Path, source: &str, root: Option<&Path>, version: String) -> Sdk {
pub(crate) fn hatch_sdk(path: &Path, project: &Path, name: &str) -> Option<Sdk> {
let owner = venv_of(path)
.and_then(|home| hatch_env(&home))
.map(|(owner, _)| owner)
.unwrap_or_else(|| project.file_name().unwrap_or_default().to_string_lossy().into_owned());
Some(python_sdk_with_version(path, "venv", Some(project), python_version(path)?, Some((owner, name.to_owned()))))
}
fn python_version(path: &Path) -> Option<String> {
query(path, &["--version"], VERSION_TIMEOUT)
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned))
.or_else(|| pyvenv_version(path))
}
fn python_sdk_with_version(
path: &Path,
source: &str,
root: Option<&Path>,
version: String,
hatch: Option<(String, String)>,
) -> Sdk {
let short = version.split('.').take(2).collect::<Vec<_>>().join(".");
let venv = venv_of(path);
let pipenv = if source == "pipenv" {
root.and_then(pipfile_dir)
} else if source == "venv" && hatch.is_none() {
venv.as_deref().and_then(pipenv_project)
} else {
venv.as_deref().filter(|_| source == "venv").and_then(pipenv_project)
None
};
let source = if pipenv.is_some() { "pipenv" } else { source };
let hatch = hatch.or_else(|| venv.as_deref().filter(|_| source == "venv").and_then(hatch_env));
let source = if hatch.is_some() { "hatch" } else { source };
let label = match (&venv, source) {
// Every project has a `default`: the project names it, as Pipenv's are named.
(_, "hatch") => match hatch {
Some((project, env)) if env != DEFAULT_HATCH_ENV => format!("Python {short} (Hatch: {project}:{env})"),
Some((project, _)) => format!("Python {short} (Hatch: {project})"),
None => format!("Python {short} (Hatch)"),
},
(_, "pipenv") => {
let project = pipenv.as_deref().and_then(Path::file_name).unwrap_or_default().to_string_lossy();
format!("Python {short} (Pipenv: {project})")
@@ -1247,6 +1430,123 @@ mod pixi_tests {
}
}
#[cfg(test)]
mod hatch_tests {
use super::*;
fn venv(home: &Path) -> PathBuf {
let python = home.join(bin_dir()).join(exe("python"));
std::fs::create_dir_all(python.parent().unwrap()).unwrap();
std::fs::write(&python, "").unwrap();
std::fs::write(home.join("pyvenv.cfg"), "version = 3.12.1\n").unwrap();
python
}
#[test]
fn the_project_id_is_hatchs_hash_of_the_path() {
// `base64.urlsafe_b64encode(sha256(path)).decode()[:8]`, the path case-folded on Windows and macOS.
let root = Path::new("/Users/Me/Shop");
assert_eq!(hatch_project_id(Host::Unix, root), "nrZdKLu1");
assert_eq!(hatch_project_id(Host::Mac, root), "6jvy1__M");
assert_eq!(hatch_project_id(Host::Windows, root), "6jvy1__M");
// `"Straße".casefold()` is `strasse`, where lower-casing keeps the `ß`.
assert_eq!(hatch_project_id(Host::Mac, Path::new("/Users/me/Straße/shop")), "uZq42xD1");
assert_eq!(casefold("ẞſfiΣς"), "sssfiσσ");
}
#[test]
fn a_default_hatch_environment_at_a_custom_path_is_used_after_pipenv() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("shop");
let subdir = project.join("src");
std::fs::create_dir_all(&subdir).unwrap();
let external = venv(&tmp.path().join("custom default"));
std::fs::write(project.join("pyproject.toml"), "[tool.hatch.envs.default]\npath = '../custom default'\n")
.unwrap();
std::fs::write(project.join("Pipfile"), "").unwrap();
let pipenv = venv(&project.join(".venv"));
assert_eq!(project_venv_python(&subdir), Some(pipenv));
std::fs::remove_dir_all(project.join(".venv")).unwrap();
assert_eq!(project_venv_python(&subdir), Some(dunce::canonicalize(external).unwrap()));
}
#[cfg(unix)]
#[test]
fn sdk_detection_uses_hatch_find_for_existing_custom_environments() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("shop");
std::fs::create_dir(&project).unwrap();
std::fs::write(project.join("hatch.toml"), "").unwrap();
let external = tmp.path().join("custom docs");
let docs = venv(&external);
let hatch = tmp.path().join("hatch");
std::fs::write(
&hatch,
format!(
"#!/bin/sh\ncase \"$3 $4 $6\" in\n\
'env show ') echo '{{\"default\":{{}},\"docs\":{{}},\"hatch-build\":{{}}}}';;\n\
'env find docs') echo 'Looking up environment'; echo '{external}';;\n\
'env find default') echo '{missing}';;\n\
*) exit 1;;\nesac\n",
external = external.display(),
missing = tmp.path().join("missing").display(),
),
)
.unwrap();
std::fs::set_permissions(&hatch, std::fs::Permissions::from_mode(0o755)).unwrap();
let sdks = python(Some(&project), |tool| (tool == "hatch").then(|| hatch.clone()));
let sdk = sdks.iter().find(|sdk| &*sdk.path == docs.as_path()).unwrap();
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Hatch: shop:docs)", "hatch"));
}
#[test]
fn the_project_is_the_nearest_folder_with_a_pyproject() {
let tmp = tempfile::tempdir().unwrap();
let shop = tmp.path().join("shop");
std::fs::create_dir_all(shop.join("src/pkg")).unwrap();
assert_eq!(hatch_project_root(&shop), None);
std::fs::write(shop.join("hatch.toml"), "").unwrap();
assert_eq!(hatch_project_root(&shop), Some(shop.clone()));
std::fs::write(shop.join("pyproject.toml"), "").unwrap();
assert_eq!(hatch_project_root(&shop.join("src/pkg")), Some(shop));
}
#[test]
fn a_projects_environments_are_the_ones_under_its_id() {
let tmp = tempfile::tempdir().unwrap();
let (shop, other) = (tmp.path().join("shop"), tmp.path().join("elsewhere").join("shop"));
std::fs::create_dir_all(&shop).unwrap();
let storage = tmp.path().join("data").join("env").join("virtual");
let id = hatch_project_id(Host::current(), &dunce::canonicalize(&shop).unwrap());
let ours = storage.join("shop").join(id);
// Another project of the same name keeps its environments under its own id.
let theirs = storage.join("shop").join(hatch_project_id(Host::current(), &other));
let (default, docs) = (venv(&ours.join("shop")), venv(&ours.join("docs")));
let theirs = venv(&theirs.join("shop"));
std::fs::create_dir_all(ours.join("half-made")).unwrap();
// Hatch's own test environments live beside the project's.
let internal = venv(&ours.join("hatch-test.py3.12"));
assert_eq!(hatch_envs_in(&shop, &storage, Host::current()), [docs.clone(), default.clone()]);
assert_eq!(hatch_env(internal.parent().unwrap().parent().unwrap()), None);
assert!(hatch_envs_in(&other, &tmp.path().join("missing"), Host::current()).is_empty());
let sdk = python_sdk(&default, "venv", Some(&shop)).unwrap();
// Named by their project, as every project has a `default`.
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Hatch: shop)", "hatch"));
assert_eq!(python_sdk(&docs, "venv", None).unwrap().name, "Python 3.12 (Hatch: shop:docs)");
assert_eq!(python_sdk(&theirs, "venv", None).unwrap().name, "Python 3.12 (Hatch: shop)");
// A project whose name starts like Hatch's internal environments keeps its `default`.
let named = venv(&storage.join("hatch-shop").join("abcdefgh").join("hatch-shop"));
assert_eq!(python_sdk(&named, "venv", None).unwrap().name, "Python 3.12 (Hatch: hatch-shop)");
// A virtualenv that merely sits three folders deep is no Hatch environment.
let plain = venv(&tmp.path().join("a").join("b").join("c"));
assert_eq!(python_sdk(&plain, "venv", None).unwrap().source, "venv");
}
}
#[cfg(test)]
mod pipenv_tests {
use super::*;
@@ -1489,6 +1789,29 @@ mod env_manager_dir_tests {
);
}
#[test]
fn hatch_environments_follow_each_platforms_data_dir() {
let home = Path::new("/home/me");
let virtual_in = |data: PathBuf| data.join("env").join("virtual");
assert_eq!(
hatch_env_dir(Host::Windows, home, env(&[("LOCALAPPDATA", "C:/Users/me/AppData/Local")])),
virtual_in(Path::new("C:/Users/me/AppData/Local").join("hatch"))
);
assert_eq!(
hatch_env_dir(Host::Mac, home, env(&[])),
virtual_in(home.join("Library").join("Application Support").join("hatch"))
);
assert_eq!(hatch_env_dir(Host::Unix, home, env(&[])), virtual_in(home.join(".local/share").join("hatch")));
assert_eq!(
hatch_env_dir(Host::Unix, home, env(&[("XDG_DATA_HOME", "/xdg/data")])),
virtual_in(Path::new("/xdg/data").join("hatch"))
);
assert_eq!(
hatch_env_dir(Host::Mac, home, env(&[("HATCH_DATA_DIR", "/hatch"), ("XDG_DATA_HOME", "/xdg/data")])),
virtual_in(PathBuf::from("/hatch"))
);
}
#[test]
fn workon_homes_follow_pipenv_and_virtualenvwrapper() {
let home = Path::new("/home/me");
+154 -24
View File
@@ -33,11 +33,14 @@ pub enum VenvTool {
Conda,
/// `pipenv --python <base>` in the project (pipenv must be on PATH).
Pipenv,
/// `hatch env create <env>` in the project (hatch must be on PATH).
Hatch,
}
/// Creates a virtualenv at `location` with `tool` and returns its interpreter.
/// `base` is the interpreter uv / venv build on, or the one poetry's / pipenv's env uses.
/// `base` is the interpreter uv / venv build on, or the one poetry's / pipenv's / hatch's env uses.
/// `install` also installs the packages the project declares, for the tool that reads them (pipenv).
/// For Hatch, `location` is `<project>/<environment name>`: Hatch decides where the environment goes.
pub fn create_venv(
tool: VenvTool,
base: &Path,
@@ -95,9 +98,157 @@ pub(crate) fn create_venv_with(
VenvTool::Poetry => create_poetry_env(base, location, &which, cancel, on_line),
VenvTool::Conda => create_conda_env(base, location, &which, cancel, on_line),
VenvTool::Pipenv => create_pipenv_env(base, location, install, &which, cancel, on_line),
VenvTool::Hatch => create_hatch_env(base, location, &which, cancel, on_line),
}
}
const HATCH_MISSING: &str = "Hatch is not installed (install it from https://hatch.pypa.io)";
const HATCH_SHOW_ARGS: [&str; 5] = ["--no-color", "--no-interactive", "env", "show", "--json"];
/// Hatch's own environments (`hatch-build`, `hatch-test.py3.12`, `hatch-static-analysis`, …).
fn is_internal_hatch_env(name: &str) -> bool {
name.starts_with("hatch-")
}
/// The environments the project at `root` defines for Hatch (`hatch env show --json`), `default`
/// first, without Hatch's internal ones. Unconfigured projects return an empty list.
pub fn hatch_envs(root: &Path, cancel: &CancellationToken) -> IdeResult<Vec<String>> {
// Hatch first installs the environment plugins the project requires, which can take a while.
hatch_envs_with(root, which, Duration::from_secs(120), cancel)
}
pub(crate) fn hatch_envs_with(
root: &Path,
which: impl Fn(&str) -> Option<PathBuf>,
timeout: Duration,
cancel: &CancellationToken,
) -> IdeResult<Vec<String>> {
let Some((project, _)) = crate::discover::hatch_project_config(root) else { return Ok(Vec::new()) };
let hatch = which("hatch").ok_or_else(|| IdeError::unavailable(HATCH_MISSING))?;
let args = HATCH_SHOW_ARGS.map(str::to_owned);
// Cancelled when the caller cancels, or when `timeout` passes first.
let token = cancel.child_token();
let (done, finished) = std::sync::mpsc::channel::<()>();
let watchdog = token.clone();
std::thread::spawn(move || {
if finished.recv_timeout(timeout) == Err(std::sync::mpsc::RecvTimeoutError::Timeout) {
watchdog.cancel();
}
});
let out = stream(&hatch, &args, Some(&project), &[], &token, &|_| {});
drop(done);
match out {
Err(_) if token.is_cancelled() && !cancel.is_cancelled() => Err(IdeError::new(
ide_core::error::ErrorKind::TimedOut,
format!("`hatch env show` did not finish within {} seconds", timeout.as_secs()),
)),
out => parse_hatch_envs(&out?),
}
}
fn hatch_find_args(name: &str) -> [&str; 6] {
["--no-color", "--no-interactive", "env", "find", "--", name]
}
fn hatch_output_home(output: &str) -> Option<PathBuf> {
output
.lines()
.rev()
.map(|line| PathBuf::from(line.trim()))
.find(|home| home.is_absolute() && home.join("pyvenv.cfg").is_file())
}
/// Existing project virtualenvs, including custom locations resolved by Hatch itself.
pub(crate) fn hatch_env_paths(root: &Path, hatch: &Path) -> Option<Vec<(PathBuf, String)>> {
const TIMEOUT: Duration = Duration::from_secs(4);
let output = query_in(hatch, &HATCH_SHOW_ARGS, Some(root), &[], TIMEOUT)?;
let names = parse_hatch_envs(&output).ok()?;
Some(
names
.chunks(4)
.flat_map(|names| {
crate::discover::par_map(names, |name| {
let output = query_in(hatch, &hatch_find_args(name), Some(root), &[], TIMEOUT)?;
let python = hatch_output_home(&output)?.join(bin_dir()).join(exe("python"));
python.is_file().then(|| (python, name.clone()))
})
})
.collect(),
)
}
pub(crate) fn parse_hatch_envs(out: &str) -> IdeResult<Vec<String>> {
// Skip anything Hatch prints before the JSON object (warnings, the echoed command line).
let json = out.lines().find(|l| l.trim_start().starts_with('{')).unwrap_or("{}");
let envs: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(json).map_err(|e| IdeError::internal(format!("unexpected hatch output: {e}")))?;
let mut names: Vec<String> = envs.into_iter().map(|(name, _)| name).filter(|n| !is_internal_hatch_env(n)).collect();
names.sort_by_key(|name| name != "default");
Ok(names)
}
/// An environment that already exists is reused rather than rebuilt. If `base` is another
/// Python version than the environment's, nothing is changed and the error says how to go on.
fn reuse_existing_env(home: &Path, base: &Path, remove: &str) -> IdeResult<()> {
let short = |version: &str| version.split('.').take(2).collect::<Vec<_>>().join(".");
let existing = crate::discover::pyvenv_version(&home.join(bin_dir()).join(exe("python")));
let wanted = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned));
match (existing.as_deref().map(short), wanted.as_deref().map(short)) {
(Some(existing), Some(wanted)) if existing != wanted => Err(IdeError::new(
ide_core::error::ErrorKind::AlreadyExists,
format!(
"{} already holds a Python {existing} environment, not Python {wanted} like the base interpreter. \
Select it under Existing environment, or remove it first with `{remove}`.",
home.display()
),
)),
_ => Ok(()),
}
}
/// `hatch env create <env>` in the project directory, with `base` as the Python the environment
/// is built on (`HATCH_PYTHON`; an environment that pins its own `python` keeps it). Hatch keeps
/// an environment that exists, whatever `base` is: one on another Python version is refused
/// instead. Then `hatch run` in it prints its prefix, after bringing an environment that already
/// existed up to date: one left half-made by an interrupted creation has no dependencies yet.
fn create_hatch_env(
base: &Path,
location: &Path,
which: &dyn Fn(&str) -> Option<PathBuf>,
cancel: &CancellationToken,
on_line: &dyn Fn(String),
) -> IdeResult<Sdk> {
let project = location
.parent()
.filter(|p| p.is_dir())
.ok_or_else(|| IdeError::invalid("Hatch environments need an open project directory"))?;
let (project, _) = crate::discover::hatch_project_config(project)
.ok_or_else(|| IdeError::invalid("This project has no Hatch configuration"))?;
let hatch = which("hatch").ok_or_else(|| IdeError::unavailable(HATCH_MISSING))?;
let env = location
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.ok_or_else(|| IdeError::invalid("select a Hatch environment"))?;
let hatch_python = [("HATCH_PYTHON".to_owned(), base.to_string_lossy().into_owned())];
let run = |args: &[&str]| {
let args: Vec<String> =
["--no-color", "--no-interactive"].iter().chain(args).map(|a| (*a).to_owned()).collect();
stream(&hatch, &args, Some(&project), &hatch_python, cancel, on_line)
};
let existing = query_in_cancellable(&hatch, &hatch_find_args(&env), &project, &[], Duration::from_secs(30), cancel)
.and_then(|out| hatch_output_home(&out));
if let Some(home) = existing {
reuse_existing_env(&home, base, &format!("hatch env remove {env}"))?;
}
run(&["env", "create", &env])?;
let out = run(&["--env", &env, "run", "python", "-c", "import sys; print(sys.prefix)"])?;
let home = hatch_output_home(&out).ok_or_else(|| IdeError::internal("hatch created no environment".to_owned()))?;
let python = home.join(bin_dir()).join(exe("python"));
crate::discover::hatch_sdk(&python, &project, &env)
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
/// `poetry env use <base>` in the project directory (the parent of `location`, which the
/// dialog fills with `<root>/.venv` only as a hint — poetry keeps its envs under its own
/// cache), then `poetry env info --path` for the interpreter it made or reused.
@@ -126,31 +277,10 @@ fn create_poetry_env(
.map(PathBuf::from)
.ok_or_else(|| IdeError::internal("poetry created no environment".to_owned()))?;
let python = home.join(bin_dir()).join(exe("python"));
crate::discover::python_sdk(&python, "pipenv", Some(project))
crate::discover::python_sdk(&python, "venv", Some(project))
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
/// An environment that already exists is reused rather than rebuilt: the tools replace one
/// built on another Python without asking, losing its packages. If `base` is another Python
/// version than the environment's, nothing is changed and the error says how to go on.
fn reuse_existing_env(home: &Path, base: &Path, remove: &str) -> IdeResult<()> {
let short = |version: &str| version.split('.').take(2).collect::<Vec<_>>().join(".");
let existing = crate::discover::pyvenv_version(&home.join(bin_dir()).join(exe("python")));
let wanted = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned));
match (existing.as_deref().map(short), wanted.as_deref().map(short)) {
(Some(existing), Some(wanted)) if existing != wanted => Err(IdeError::new(
ide_core::error::ErrorKind::AlreadyExists,
format!(
"{} already holds a Python {existing} environment, not Python {wanted} like the base interpreter. \
Select it under Existing environment, or remove it first with `{remove}`.",
home.display()
),
)),
_ => Ok(()),
}
}
/// Pipenv's environment for the project (`location` is a hint inside it, as for Poetry: pipenv
/// keeps its envs under `WORKON_HOME`). `pipenv --python <base>` creates it when `pipenv --venv`
/// finds none, writing a `Pipfile` (from `requirements.txt` if there is one) when the project
@@ -199,7 +329,7 @@ fn create_pipenv_env(
let _ = std::fs::write(record, owner.to_string_lossy().as_bytes());
}
let python = home.join(bin_dir()).join(exe("python"));
crate::discover::python_sdk(&python, "venv", Some(project))
crate::discover::python_sdk(&python, "pipenv", Some(project))
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
+125 -1
View File
@@ -12,6 +12,7 @@ use ide_language::LanguageServerConfig;
use ide_run::RunConfig;
use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;
fn fake_venv(root: &Path, name: &str) -> std::path::PathBuf {
let venv = root.join(name);
@@ -1602,6 +1603,21 @@ fn env_tools_are_reported_missing_before_they_run() {
)
.unwrap_err();
assert!(pipenv.message.contains("Pipenv is not installed"), "{}", pipenv.message);
std::fs::write(dir.path().join("hatch.toml"), "").unwrap();
let hatch = crate::python::create_venv_with(
crate::python::VenvTool::Hatch,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
)
.unwrap_err();
assert!(hatch.message.contains("Hatch is not installed"), "{}", hatch.message);
let listed =
crate::python::hatch_envs_with(dir.path(), none, Duration::from_secs(5), &Default::default()).unwrap_err();
assert!(listed.message.contains("Hatch is not installed"), "{}", listed.message);
// An existing environment is refused before any tool runs.
std::fs::create_dir_all(&location).unwrap();
std::fs::write(location.join("pyvenv.cfg"), "home = /python").unwrap();
@@ -1702,7 +1718,7 @@ fn pipenv_creates_the_projects_environment_and_never_replaces_one() {
let tmp = tempfile::tempdir().unwrap();
let tmp = dunce::canonicalize(tmp.path()).unwrap();
let project = tmp.join("shop");
let home = tmp.join("workon").join(crate::discover::pipenv_env_name(&project));
let home = tmp.join("workon/custom-shop");
std::fs::create_dir_all(&project).unwrap();
let python = tmp.join("python");
std::fs::write(&python, "#!/bin/sh\necho 'Python 3.12.1'\n").unwrap();
@@ -1754,6 +1770,114 @@ fn pipenv_creates_the_projects_environment_and_never_replaces_one() {
assert_eq!(calls().lines().count(), 2);
}
#[test]
fn hatch_lists_the_projects_own_environments_default_first() {
use crate::python::parse_hatch_envs;
let out = r#"{"docs":{"type":"virtual"},"default":{"type":"virtual"},"hatch-build":{"builder":true},"hatch-test.py3.12":{"python":"3.12"},"test.py3.12":{"python":"3.12"}}"#;
assert_eq!(parse_hatch_envs(out).unwrap(), ["default", "docs", "test.py3.12"]);
assert_eq!(parse_hatch_envs(&format!("a warning\n{out}\n")).unwrap().len(), 3);
assert!(parse_hatch_envs("not json").unwrap().is_empty());
assert!(parse_hatch_envs("{broken").is_err());
}
#[test]
fn hatch_environment_choices_require_hatch_configuration() {
use crate::python::hatch_envs_with;
let tmp = tempfile::tempdir().unwrap();
let pyproject = tmp.path().join("pyproject.toml");
let no_lookup = |_: &str| panic!("Hatch must not run for an unconfigured project");
let timeout = Duration::from_secs(5);
assert!(hatch_envs_with(tmp.path(), no_lookup, timeout, &Default::default()).unwrap().is_empty());
std::fs::write(&pyproject, "[build-system]\nbuild-backend = 'hatchling.build'\n").unwrap();
assert!(hatch_envs_with(tmp.path(), no_lookup, timeout, &Default::default()).unwrap().is_empty());
let missing = |_: &str| None;
std::fs::write(&pyproject, "[tool.hatch.envs.docs]\n").unwrap();
assert!(hatch_envs_with(tmp.path(), missing, timeout, &Default::default()).is_err());
std::fs::remove_file(pyproject).unwrap();
std::fs::write(tmp.path().join("hatch.toml"), "[envs.docs]\n").unwrap();
assert!(hatch_envs_with(tmp.path(), missing, timeout, &Default::default()).is_err());
}
#[test]
#[cfg(unix)]
fn listing_hatch_environments_gives_up_after_the_timeout() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("hatch.toml"), "").unwrap();
// Stuck installing an environment plugin, say.
let hatch = tmp.path().join("hatch");
std::fs::write(&hatch, "#!/bin/sh\nsleep 30\n").unwrap();
std::fs::set_permissions(&hatch, std::fs::Permissions::from_mode(0o755)).unwrap();
let which = |tool: &str| (tool == "hatch").then(|| hatch.clone());
let started = std::time::Instant::now();
let err =
crate::python::hatch_envs_with(tmp.path(), which, Duration::from_millis(300), &Default::default()).unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::TimedOut, "{}", err.message);
assert!(started.elapsed() < Duration::from_secs(10));
}
#[test]
#[cfg(unix)]
fn hatch_creates_the_selected_environment_on_the_base_interpreter() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("shop");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(project.join("hatch.toml"), "").unwrap();
let storage = tmp.path().join("data/env/virtual/shop/abcdefgh");
std::fs::create_dir_all(&storage).unwrap();
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();
// `env create <name>` builds the environment with $HATCH_PYTHON in Hatch's data directory (the
// default one is named after the project); `--env <name> run` installs what it lacks and runs in it.
let hatch = tmp.path().join("hatch");
std::fs::write(
&hatch,
format!(
"#!/bin/sh\nwhile [ \"${{1#--}}\" != \"$1\" ]; do [ \"$1\" = --env ] && {{ name=$2; shift; }}; shift; done\n\
[ \"$1 $2\" = 'env create' ] && name=$3\n\
[ \"$1 $2\" = 'env find' ] && name=$4\nhome='{storage}'/$name\n\
[ \"$name\" = default ] && home='{storage}'/shop\n\
[ \"$name\" = docs ] && home='{outside}'\n\
[ \"$1 $2\" = 'env find' ] && {{ echo \"$home\"; exit 0; }}\n\
if [ \"$1\" = run ]; then echo 'Syncing dependencies'; : > \"$home/synced\"; echo \"$home\"; exit 0; fi\n\
[ \"$1 $2\" = 'env create' ] || exit 2\necho \"$name\" >> '{storage}'/created\n[ -d \"$home\" ] && exit 0\n\
mkdir -p \"$home/bin\"\ncp \"$HATCH_PYTHON\" \"$home/bin/python\"\n\
echo 'version = 3.12.1' > \"$home/pyvenv.cfg\"\necho \"Creating environment: $name\"\n",
storage = storage.display(),
outside = tmp.path().join("custom docs").display(),
),
)
.unwrap();
std::fs::set_permissions(&hatch, std::fs::Permissions::from_mode(0o755)).unwrap();
let which = |tool: &str| (tool == "hatch").then(|| hatch.clone());
let create = |env: &str| {
crate::python::create_venv_with(
crate::python::VenvTool::Hatch,
&python,
&project.join(env),
false,
which,
&Default::default(),
&|_| {},
)
};
let sdk = create("default").unwrap();
assert_eq!(&*sdk.path, storage.join("shop/bin/python").as_path());
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Hatch: shop)", "hatch"));
let docs = create("docs").unwrap();
assert_eq!((docs.name.as_str(), docs.source.as_str()), ("Python 3.12 (Hatch: shop:docs)", "hatch"));
assert!(tmp.path().join("custom docs/synced").is_file());
// Hatch keeps an existing environment whatever `HATCH_PYTHON` says: one on another Python
// version is refused before anything runs, rather than reported as created.
std::fs::write(tmp.path().join("custom docs/pyvenv.cfg"), "version = 3.11.4\n").unwrap();
let err = create("docs").unwrap_err();
assert!(err.message.contains("Python 3.11 environment, not Python 3.12"), "{}", err.message);
assert!(err.message.contains("hatch env remove docs"), "{}", err.message);
assert_eq!(std::fs::read_to_string(storage.join("created")).unwrap(), "default\ndocs\n");
}
#[test]
fn neutral_dir_is_fresh_and_empty() {
let a = crate::python::neutral_dir().unwrap();
+4 -2
View File
@@ -44,9 +44,10 @@ The project interpreter is chosen in this order:
1. The interpreter set in **Settings › Languages & Frameworks › Python Interpreter**.
2. A virtualenv in the project: `.venv`, `venv`, `env` or `.env` (a folder with `pyvenv.cfg`), or a pixi environment in `.pixi/envs/`.
3. The Pipenv environment for the nearest `Pipfile`, including one selected by a `.venv` file or `PIPENV_CUSTOM_VENV_NAME`.
4. The Python version the project pins for mise or asdf (`mise.toml`, `.tool-versions` and the other mise config files).
4. The `default` environment of a project with Hatch configuration, once Hatch has created it.
5. The Python version the project pins for mise or asdf (`mise.toml`, `.tool-versions` and the other mise config files).
The interpreter list on that page also shows what the IDE detects on the machine: the active `VIRTUAL_ENV`, virtualenvs made by virtualenvwrapper, pipenv and Poetry, pyenv versions, Pythons installed by uv, mise and asdf installs, conda environments (Miniconda, Anaconda, Miniforge, Mambaforge, micromamba, and every env that `conda env list` shows), and the `python` executables on `PATH`.
The interpreter list on that page also shows what the IDE detects on the machine: the active `VIRTUAL_ENV`, virtualenvs made by virtualenvwrapper, pipenv and Poetry, Hatch environments, pyenv versions, Pythons installed by uv, mise and asdf installs, conda environments (Miniconda, Anaconda, Miniforge, Mambaforge, micromamba, and every env that `conda env list` shows), and the `python` executables on `PATH`.
The selected interpreter is passed to basedpyright and Pyright (`python.pythonPath`), and its virtualenv is set as `VIRTUAL_ENV` for the language server and for run configurations.
@@ -75,6 +76,7 @@ On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add
- **uv Environment**: `uv venv <location> --python <base>` (uv must be on `PATH`).
- **Poetry Environment**: `poetry env use <base>` in the project.
- **Pipenv Environment**: `pipenv --python <base>` in the project (pipenv must be on `PATH`). Pipenv writes a `Pipfile` when the project has none, importing `requirements.txt` if there is one. With **Install packages from Pipfile** it then runs `pipenv install --dev`. An environment the project already has is reused; if it was built on another Python version than the base interpreter, nothing is changed and the dialog says so (remove it with `pipenv --rm` to start over).
- **Hatch Environment** is available when the project has `hatch.toml` or a `[tool.hatch]` table in `pyproject.toml`. Pick an environment to run `hatch env create <environment>` in the project. Hatch must be on `PATH` and receives the base interpreter as `HATCH_PYTHON`. Hatch reuses an existing environment. If its Python version differs from the base interpreter, the dialog reports the mismatch. Remove the environment with `hatch env remove <environment>` to recreate it. The interpreter list shows `Hatch: <project>` for `default` and `Hatch: <project>:<environment>` for the others, including environments at custom paths reported by `hatch env find`.
- **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.
+4 -2
View File
@@ -44,9 +44,10 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
1. **设置 › 语言和框架 › Python 解释器** 中选定的解释器。
2. 项目里的虚拟环境:`.venv`、`venv`、`env` 或 `.env`(含 `pyvenv.cfg` 的目录),或 `.pixi/envs/` 下的 pixi 环境。
3. 最近的 `Pipfile` 对应的 Pipenv 环境,包括通过 `.venv` 文件或 `PIPENV_CUSTOM_VENV_NAME` 指定的环境。
4. 项目通过 mise 或 asdf 固定的 Python 版本(`mise.toml`、`.tool-versions` 等 mise 配置文件)。
4. 配置了 Hatch 的项目中已创建的 `default` 环境。
5. 项目通过 mise 或 asdf 固定的 Python 版本(`mise.toml`、`.tool-versions` 等 mise 配置文件)。
该页面的解释器列表还会列出 IDE 在本机找到的解释器:当前激活的 `VIRTUAL_ENV`,virtualenvwrapper、pipenv 和 Poetry 创建的虚拟环境,pyenv 的各个版本,uv 安装的 Python,mise 和 asdf 的安装,conda 环境(Miniconda、Anaconda、Miniforge、Mambaforge、micromamba,以及 `conda env list` 能看到的所有环境),还有 `PATH` 上的 `python` 可执行文件。
该页面的解释器列表还会列出 IDE 在本机找到的解释器:当前激活的 `VIRTUAL_ENV`,virtualenvwrapper、pipenv 和 Poetry 创建的虚拟环境,Hatch 环境,pyenv 的各个版本,uv 安装的 Python,mise 和 asdf 的安装,conda 环境(Miniconda、Anaconda、Miniforge、Mambaforge、micromamba,以及 `conda env list` 能看到的所有环境),还有 `PATH` 上的 `python` 可执行文件。
选定的解释器会传给 basedpyright 和 Pyright(`python.pythonPath`),其虚拟环境会作为 `VIRTUAL_ENV` 提供给语言服务器和运行配置。
@@ -75,6 +76,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
- **uv 环境**:执行 `uv venv <location> --python <base>`(`PATH` 上需要有 uv)。
- **Poetry 环境**:在项目中执行 `poetry env use <base>`。
- **Pipenv 环境**:在项目中执行 `pipenv --python <base>`(`PATH` 上需要有 pipenv)。项目没有 `Pipfile` 时,Pipenv 会写入一个,有 `requirements.txt` 时从中导入。勾选 **安装 Pipfile 中的软件包** 时,随后执行 `pipenv install --dev`。项目已有的环境会被复用;如果它的 Python 版本与基础解释器不同,不做任何改动并在对话框中提示(可用 `pipenv --rm` 删除后重建)。
- 项目包含 `hatch.toml` 或在 `pyproject.toml` 中定义了 `[tool.hatch]` 表时,可以选择 **Hatch 环境**。选定环境后,IDE 会在项目中执行 `hatch env create <环境>`。Hatch 需要在 `PATH` 上,基础解释器通过 `HATCH_PYTHON` 传入。Hatch 会复用已有环境。如果环境与基础解释器的 Python 版本不同,对话框会提示。要重新创建环境,请先用 `hatch env remove <环境>` 删除它。解释器列表将 `default` 环境显示为 `Hatch: <项目>`,其他环境显示为 `Hatch: <项目>:<环境>`,包括 `hatch env find` 返回的自定义路径中的环境。
- **Conda 环境**:执行 `conda create -n <名称>`,环境建在 conda 的 envs 目录中,Python 版本为所选版本。
也可以直接选择已有的解释器或环境目录。新解释器会成为项目解释器。
+1
View File
@@ -599,6 +599,7 @@ sdk_php_xdebug trusted project_host bin
sdk_project_libraries trusted project_host bindings async
sdk_python_create_venv outside_restricted project_host bindings async
sdk_python_effective trusted project_host bindings async
sdk_python_hatch_envs outside_restricted project_host bindings async
sdk_python_interpreter outside_restricted project_host bindings async
sdk_python_packages outside_restricted project_host bindings async
sdk_python_pip outside_restricted project_host bindings async
+7 -3
View File
@@ -1652,12 +1652,14 @@ export const commands = {
*/
sdkProjectLibraries: (request: RequestId, onGroups: Channel<LibraryGroup[]>) => typedError<LibraryGroup[], IdeError>(__TAURI_INVOKE("sdk_project_libraries", { request, onGroups })),
/**
* Creates a Python environment with `tool` (`venv` / `uv` / `poetry` / `pipenv`); output streams through
* `on_output`. `install_packages` also installs what the project's `Pipfile` declares (pipenv).
* Creates a Python environment and streams its output through `on_output`.
* With Pipenv, `install_packages` also installs the packages declared in the project's `Pipfile`.
*/
sdkPythonCreateVenv: (tool: VenvTool, base: string, location: string, installPackages: boolean, request: RequestId, onOutput: Channel<string>) => typedError<Sdk, IdeError>(__TAURI_INVOKE("sdk_python_create_venv", { tool, base, location, installPackages, request, onOutput })),
/** The interpreter the project uses: the configured one, else its virtualenv. */
sdkPythonEffective: (near: string | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective", { near })),
/** The environments the window's project defines for Hatch, `default` first (hatch must be on PATH). */
sdkPythonHatchEnvs: (request: RequestId) => typedError<string[], IdeError>(__TAURI_INVOKE("sdk_python_hatch_envs", { request })),
/** An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run. */
sdkPythonInterpreter: (path: string) => typedError<{
/**
@@ -13802,7 +13804,9 @@ export type VenvTool =
/** `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH). */
"conda" |
/** `pipenv --python <base>` in the project (pipenv must be on PATH). */
"pipenv";
"pipenv" |
/** `hatch env create <env>` in the project (hatch must be on PATH). */
"hatch";
/** What a view or custom editor shows. */
export type View = {
@@ -6,6 +6,8 @@ import { setLocale } from "@/platform/i18n";
const mocks = vi.hoisted(() => ({
detect: vi.fn(),
createVenv: vi.fn(),
hatchEnvs: vi.fn(),
cancel: vi.fn(),
interpreter: vi.fn(),
choosePath: vi.fn(),
}));
@@ -18,8 +20,9 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
...real.commands,
sdkDetect: mocks.detect,
sdkPythonCreateVenv: mocks.createVenv,
sdkPythonHatchEnvs: mocks.hatchEnvs,
sdkPythonInterpreter: mocks.interpreter,
cancelRequest: vi.fn(),
cancelRequest: mocks.cancel,
},
};
});
@@ -51,6 +54,7 @@ beforeEach(() => {
Object.assign(window, { __TAURI_INTERNALS__: { transformCallback: () => 1 } });
mocks.detect.mockResolvedValue(ok([VENV, SYSTEM]));
mocks.createVenv.mockResolvedValue(new Promise(() => {}));
mocks.hatchEnvs.mockResolvedValue(ok(["default", "docs"]));
mocks.interpreter.mockResolvedValue(ok(null));
useSdks.setState({ byKind: {}, loading: {}, errors: {} });
});
@@ -65,10 +69,22 @@ const open = (onAdded = vi.fn()) => {
};
describe("Add Python Interpreter", () => {
it("translates the Pipenv environment type", async () => {
it("hides the Hatch environment type for projects without Hatch configuration", async () => {
mocks.hatchEnvs.mockResolvedValue(ok([]));
await act(async () => {
open();
});
expect(mocks.hatchEnvs).toHaveBeenCalled();
expect(screen.queryByRole("button", { name: "Hatch Environment" })).toBeNull();
expect(screen.getByRole("button", { name: "Pipenv Environment" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Virtualenv Environment" })).toBeInTheDocument();
});
it("translates the Pipenv and Hatch environment types", async () => {
await setLocale("zh");
try {
open();
expect(await screen.findByRole("button", { name: "Hatch 环境" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Pipenv 环境" })).toBeInTheDocument();
} finally {
await act(() => setLocale("en"));
@@ -77,13 +93,14 @@ describe("Add Python Interpreter", () => {
it("lists the environment types PyCharm offers", async () => {
open();
await waitFor(() => expect(mocks.detect).toHaveBeenCalled());
await screen.findByRole("button", { name: "Hatch Environment" });
for (const label of [
"Virtualenv Environment",
"Conda Environment",
"uv Environment",
"Poetry Environment",
"Pipenv Environment",
"Hatch Environment",
]) {
expect(screen.getByRole("button", { name: label })).toBeInTheDocument();
}
@@ -174,6 +191,62 @@ describe("Add Python Interpreter", () => {
}
});
it("creates the Hatch environment picked from the project's own", async () => {
let finish: (v: unknown) => void = () => {};
mocks.createVenv.mockImplementation(() => new Promise((r) => (finish = r)));
open();
await waitFor(() => expect(screen.getByRole("button", { name: "Base interpreter" })).toBeInTheDocument());
fireEvent.click(await screen.findByRole("button", { name: "Hatch Environment" }));
// Hatch decides where the environment goes: its name travels as `<project>/<name>`.
await waitFor(() => expect(screen.getByRole("button", { name: "Hatch environment" })).toHaveTextContent("default"));
expect(screen.queryByLabelText("Location:")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "OK" }));
expect(mocks.createVenv).toHaveBeenLastCalledWith(
"hatch",
"/usr/bin/python3",
"/project/default",
false,
expect.anything(),
expect.anything(),
);
await act(async () => finish(ok(VENV)));
fireEvent.click(screen.getByRole("button", { name: "Hatch environment" }));
fireEvent.click(await screen.findByRole("option", { name: "docs" }));
fireEvent.click(screen.getByRole("button", { name: "OK" }));
expect(mocks.createVenv).toHaveBeenLastCalledWith(
"hatch",
"/usr/bin/python3",
"/project/docs",
false,
expect.anything(),
expect.anything(),
);
});
it("stops listing Hatch environments when the dialog closes", async () => {
mocks.hatchEnvs.mockReturnValue(new Promise(() => {}));
open();
await waitFor(() => expect(screen.getByRole("button", { name: "Base interpreter" })).toBeInTheDocument());
await waitFor(() => expect(mocks.hatchEnvs).toHaveBeenCalled());
const [request] = mocks.hatchEnvs.mock.calls[0] as [unknown];
expect(mocks.cancel).not.toHaveBeenCalled();
cleanup();
expect(mocks.cancel).toHaveBeenCalledWith(request);
});
it("says that Hatch is missing instead of offering to create", async () => {
mocks.hatchEnvs.mockResolvedValue({
status: "error",
error: { kind: "unavailable", message: "Hatch is not installed (install it from https://hatch.pypa.io)" },
});
open();
await waitFor(() => expect(screen.getByRole("button", { name: "Base interpreter" })).toBeInTheDocument());
fireEvent.click(await screen.findByRole("button", { name: "Hatch Environment" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Hatch is not installed");
expect(screen.getByRole("button", { name: "Hatch environment" })).toHaveTextContent("No environments");
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
});
it("adds an existing interpreter without creating anything", async () => {
mocks.interpreter.mockResolvedValue(ok(VENV));
const onAdded = open();
@@ -115,6 +115,7 @@ describe("Python interpreter list", () => {
expect(interpreterIcon("uv")).toBe("python-uv");
expect(interpreterIcon("poetry")).toBe("python-poetry");
expect(interpreterIcon("pipenv")).toBe("file-pipenv");
expect(interpreterIcon("hatch")).toBe("python-hatch");
expect(interpreterIcon("pyenv")).toBe("python-versions");
expect(interpreterIcon("mise")).toBe("python-versions");
expect(interpreterIcon("asdf")).toBe("python-versions");
@@ -1,12 +1,12 @@
/**
* PyCharm's "Add Python Interpreter" (local): generate a new environment with a
* tool (virtualenv / conda / uv / Poetry / Pipenv) or select an existing interpreter.
* tool (virtualenv / conda / uv / Poetry / Pipenv / Hatch) or select an existing interpreter.
*/
import { isCancelled } from "@/platform/ipc";
import { useId, useMemo, useState } from "react";
import { useEffect, useId, useMemo, useState } from "react";
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, type SelectOption, T } from "@/ui";
import { Icon, type IconName } from "@/ui/icons";
import { createVenv, pythonInterpreter, rememberSdk, type Sdk, type VenvTool } from "./api";
import { createVenv, hatchEnvs, pythonInterpreter, rememberSdk, type Sdk, type VenvTool } from "./api";
import { choosePath } from "@/platform/choosePath";
import { tildify, useDetected } from "./components";
import styles from "./Sdk.module.css";
@@ -21,6 +21,7 @@ const KINDS: { tool: VenvTool; label: string; missing: string; icon: IconName }[
{ tool: "uv", label: "uv Environment", missing: "uv is not installed", icon: "python-uv" },
{ tool: "poetry", label: "Poetry Environment", missing: "Poetry is not installed", icon: "python-poetry" },
{ tool: "pipenv", label: "Pipenv Environment", missing: "Pipenv is not installed", icon: "file-pipenv" },
{ tool: "hatch", label: "Hatch Environment", missing: "Hatch is not installed", icon: "python-hatch" },
];
/** Tools that keep the environment in a directory of their own: the location is not asked for. */
@@ -38,12 +39,14 @@ export function AddInterpreterDialog({
const { list, loading } = useDetected("python");
const [kind, setKind] = useState<VenvTool>("venv");
const [mode, setMode] = useState<Mode>("new");
const bases = useMemo(() => list.filter((s) => s.source !== "venv" && s.source !== "pipenv"), [list]);
const bases = useMemo(() => list.filter((s) => !["venv", "pipenv", "hatch"].includes(s.source)), [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 [installPackages, setInstallPackages] = useState(true);
const [hatch, setHatch] = useState<{ root: string; names: string[]; error?: string }>();
const [hatchEnv, setHatchEnv] = useState<string | null>(null);
const [existing, setExisting] = useState<string | null>(null);
const [browsed, setBrowsed] = useState<Sdk[]>([]);
const [busy, setBusy] = useState<{ cancel: () => void } | null>(null);
@@ -99,16 +102,39 @@ export function AddInterpreterDialog({
});
};
useEffect(() => {
let live = true;
const job = hatchEnvs();
void job.promise
.then((names) => live && setHatch({ root, names }))
.catch((e: unknown) => {
if (live && !isCancelled(e)) setHatch({ root, names: [], error: String((e as Error)?.message ?? e) });
})
.finally(() => {
live = false;
});
return () => {
if (live) job.cancel();
live = false;
};
}, [root]);
const hatchForRoot = hatch?.root === root ? hatch : undefined;
const hatchNames = hatchForRoot?.names ?? [];
const hatchEnvValue = hatchEnv && hatchNames.includes(hatchEnv) ? hatchEnv : (hatchNames[0] ?? null);
const hatchTarget = hatchEnvValue ? `${root}/${hatchEnvValue}` : "";
const formError = error ?? (kind === "hatch" && mode === "new" ? hatchForRoot?.error : undefined);
// Poetry and pipenv work on the project itself; the location is only shown, as a hint.
const shownLocation = OWN_LOCATION.has(kind) ? `${root}/.venv` : location;
const target = (kind === "conda" ? envName : shownLocation).trim();
const target = (kind === "conda" ? envName : kind === "hatch" ? hatchTarget : shownLocation).trim();
const ok = () => {
if (busy) return;
setError(null);
if (mode === "existing") {
if (existing)
checkExisting(existing, (sdk) => {
rememberSdk("python", sdk);
const detected = list.find((known) => known.source === "hatch" && known.path === sdk.path);
rememberSdk("python", detected ?? sdk);
onAdded(sdk.path);
});
return;
@@ -141,6 +167,7 @@ export function AddInterpreterDialog({
pipenv: tx(
"Runs “pipenv --python <base>” in the project, which writes a Pipfile (from requirements.txt if there is one) when the project has none. Pipenv chooses where to store the environment and reuses an existing one.",
),
hatch: tx("Runs “hatch env create <environment>” in the project. Hatch decides where to store the environment."),
}[kind];
return (
@@ -162,7 +189,7 @@ export function AddInterpreterDialog({
>
<div className={styles.dialogBody}>
<ul className={styles.kinds} aria-label={tx("Interpreter type")}>
{KINDS.map((k) => (
{KINDS.filter((k) => k.tool !== "hatch" || hatchNames.length > 0 || hatchForRoot?.error).map((k) => (
<li key={k.tool}>
<button
type="button"
@@ -213,6 +240,20 @@ export function AddInterpreterDialog({
</label>
<Input id={ids.location} value={envName} onChange={(e) => setEnvName(e.target.value)} />
</>
) : kind === "hatch" ? (
<>
<label htmlFor={ids.location}>
<T>Environment:</T>
</label>
<Select
id={ids.location}
value={hatchEnvValue}
options={hatchNames.map((name) => ({ value: name, label: name, verbatim: true }))}
onChange={setHatchEnv}
placeholder="No environments"
aria-label={tx("Hatch environment")}
/>
</>
) : (
<>
<label htmlFor={ids.location}>
@@ -312,9 +353,9 @@ export function AddInterpreterDialog({
</div>
</>
)}
{error && (
{formError && (
<div className={styles.error} role="alert">
{error}
<T>{formError}</T>
</div>
)}
{log.length > 0 && <pre className={styles.log}>{log.join("\n")}</pre>}
+13 -1
View File
@@ -123,7 +123,7 @@ function streamed<T>(
}
/** Tool that creates a new Python environment (`VenvTool` in `ide-sdk`). */
export type VenvTool = "venv" | "uv" | "poetry" | "conda" | "pipenv";
export type VenvTool = "venv" | "uv" | "poetry" | "conda" | "pipenv" | "hatch";
export function createVenv(
tool: VenvTool,
@@ -139,6 +139,18 @@ export function createVenv(
);
}
/**
* The open project's Hatch environments, or an empty list when Hatch is unconfigured.
* Hatch may install plugins first, so the caller cancels it when it no longer needs it.
*/
export function hatchEnvs(): Streamed<string[]> {
const request = nextRequestId();
return {
promise: call(commands.sdkPythonHatchEnvs(request)),
cancel: () => void commands.cancelRequest(request),
};
}
/** Resolves an interpreter picked by hand ("Existing environment") into an SDK like the detected ones. */
export function pythonInterpreter(path: string): Promise<Sdk | null> {
return isTauri() ? call(commands.sdkPythonInterpreter(path)) : Promise.resolve(null);
@@ -53,7 +53,7 @@ export function interpreterPathKey(path: string): string {
return isWindowsPath(normalized) ? normalized.toLowerCase() : normalized;
}
/** The icon for an interpreter's source: virtualenv / conda / uv / Poetry / Pipenv, version managers, system. */
/** The icon for an interpreter's source: virtualenv / conda / uv / Poetry / Pipenv / Hatch, version managers, system. */
export function interpreterIcon(source: string): IconName {
switch (source) {
case "conda":
@@ -64,6 +64,8 @@ export function interpreterIcon(source: string): IconName {
return "python-poetry";
case "pipenv":
return "file-pipenv";
case "hatch":
return "python-hatch";
case "pyenv":
case "mise":
case "asdf":
+7 -1
View File
@@ -3750,5 +3750,11 @@
"Upgrade available: {latest}": "Upgrade available: {latest}",
"Rearrange Code": "Rearrange Code",
"Nothing to rearrange: members are in order, or moving them could change the class": "Nothing to rearrange: members are in order, or moving them could change the class",
"The file changed while rearranging; try again": "The file changed while rearranging; try again"
"The file changed while rearranging; try again": "The file changed while rearranging; try again",
"Hatch Environment": "Hatch Environment",
"This project has no Hatch configuration": "This project has no Hatch configuration",
"Environment:": "Environment:",
"Hatch environment": "Hatch environment",
"No environments": "No environments",
"Runs “hatch env create <environment>” in the project. Hatch decides where to store the environment.": "Runs “hatch env create <environment>” in the project. Hatch decides where to store the environment."
}
+7 -1
View File
@@ -9986,5 +9986,11 @@
"Upgrade available: {latest}": "可升级到 {latest}",
"Rearrange Code": "重新排列代码",
"Nothing to rearrange: members are in order, or moving them could change the class": "无需重新排列:成员已按顺序排列,或移动它们可能改变类的行为",
"The file changed while rearranging; try again": "重新排列期间文件已更改,请重试"
"The file changed while rearranging; try again": "重新排列期间文件已更改,请重试",
"Hatch Environment": "Hatch 环境",
"This project has no Hatch configuration": "此项目没有 Hatch 配置",
"Environment:": "环境:",
"Hatch environment": "Hatch 环境",
"No environments": "没有环境",
"Runs “hatch env create <environment>” in the project. Hatch decides where to store the environment.": "在项目中运行“hatch env create <environment>”。环境的存放位置由 Hatch 决定。"
}
+2 -1
View File
@@ -274,11 +274,12 @@ const ICONS = {
"toolwindow-maven": "toolwindows/maven",
"toolwindow-gradle": "toolwindows/gradle",
"toolwindow-build": "toolwindows/build",
// Python environment sources: virtualenv / conda / uv / Poetry, and version managers (pyenv, mise, asdf).
// Python environment sources: virtualenv / conda / uv / Poetry / Hatch, and version managers (pyenv, mise, asdf).
"python-venv": "openidea/python/venv",
"python-conda": "openidea/python/conda",
"python-uv": "openidea/python/uv",
"python-poetry": "openidea/python/poetry",
"python-hatch": "openidea/python/hatch",
"python-versions": "openidea/python/versions",
// General UI
"chevron-right": "general/chevronRight",
+4
View File
@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 1.5c2.5 0 4.6 3.6 4.6 7.1 0 3.2-2 5.9-4.6 5.9s-4.6-2.7-4.6-5.9C3.4 5.1 5.5 1.5 8 1.5z" stroke="#6C707E" stroke-width="1.4" stroke-linejoin="round"/>
<path d="M3.7 8.3l2.1 1.4L8 8.2l2.2 1.5 2.1-1.4" stroke="#6C707E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 402 B