A venv made with --symlinks is run and stored as itself, not as the base Python its python.exe links to: validate_interpreter returned the canonical path, so `--env .venv update --all --yes` would have changed the system Python. Canonicalizing now only decides where a link leads and whether it is PipDock's own; a link to another program is refused, and a Microsoft Store alias (os error 1920) is judged by its own path. The GUI merges and removes an added row by its path rather than by envHash, which follows links: a re-add replaces a broken row, removal sticks for an entry whose file is gone (a share), and neither runs during a scan. Added entries are validated again on every listing in both heads (envs::probe_listed), and the CLI checks its stored default when it uses it. `env remove` makes a typed path absolute first. SECURITY section 2 and env_probe's doc claimed an enforcement point over IPC; they now say what is checked, and backlog X36-b records the rest. notify.yml reports a Triage failure on a pull request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1167 lines
46 KiB
Rust
1167 lines
46 KiB
Rust
//! Environment discovery and probing. See ARCHITECTURE §4 and DATA-FLOW §2.
|
|
//!
|
|
//! Discovery sources, in the order the Environments screen shows them (PRD P0-1): PEP 514
|
|
//! registry, the `py` launcher, `uv python list`, known venv directories, and manual *Browse…*.
|
|
//!
|
|
//! # What spike SP-6 changed here
|
|
//!
|
|
//! - **`uv python list` returns interpreters that are not installed** (`<download available>`) and
|
|
//! **shims that duplicate a real interpreter** — a Chocolatey shim and the direct install both
|
|
//! resolved to the same `python.exe`. De-duplication cannot work on the discovery path alone.
|
|
//! - **The same interpreter reports different path casing** depending on how it was launched, so
|
|
//! [`env_hash`] case-folds. Without that, one environment silently splits its pins and snapshot
|
|
//! history in two (ARCHITECTURE §6).
|
|
//! - **`probe.py -I` hides user-site packages** on a non-venv system Python. Owner decision: keep
|
|
//! `-I`, and report [`crate::model::PyEnv::hidden_user_site`] so the UI can say so accurately.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use crate::compat::PyVersion;
|
|
use crate::errors::{Code, PdError, Result};
|
|
use crate::exec::{Command, TempFile, canonical_interpreter, watchdog};
|
|
use crate::model::{Dist, EnvSource, PkgName, PyEnv, Version};
|
|
|
|
/// The embedded introspection helper, executed as `<env-python> -X utf8 -I probe.py --json`.
|
|
///
|
|
/// SECURITY §2: `-I` (isolated mode) makes the probe ignore `PYTHONPATH` and user site, so a
|
|
/// poisoned environment cannot inject code into it. It is written to a temp file with a random
|
|
/// name per invocation and is **never** installed into the environment.
|
|
pub const PROBE_PY: &str = include_str!("../probe.py");
|
|
|
|
/// Lowest Python the probe supports; it uses `importlib.metadata` only (ARCHITECTURE §4).
|
|
pub const MIN_PROBE_PYTHON: (u32, u32) = (3, 10);
|
|
|
|
/// Everything `probe.py` reports about one environment.
|
|
#[derive(Debug, Clone)]
|
|
pub struct ProbeResult {
|
|
/// The environment itself.
|
|
pub env: PyEnv,
|
|
/// Installed distributions, sorted by normalized name.
|
|
pub dists: Vec<Dist>,
|
|
/// The PEP 508 marker environment (`sys_platform`, `platform_machine`, …), from probe schema
|
|
/// 3. Empty for an older probe, which leaves those markers unevaluated — the conservative
|
|
/// direction (`graph::markers`).
|
|
pub markers: BTreeMap<String, String>,
|
|
}
|
|
|
|
/// Identity of an environment: SHA-256 of the canonicalized interpreter path (ARCHITECTURE §6).
|
|
///
|
|
/// Case-folded on Windows — see the SP-6 note above. This value keys the pin store, the snapshot
|
|
/// directory and the recents list, so a change here orphans a user's data.
|
|
#[must_use]
|
|
pub fn env_hash(interpreter: &Path) -> String {
|
|
let canonical = canonical_interpreter(interpreter);
|
|
crate::model::sha256_hex(canonical.as_bytes())
|
|
}
|
|
|
|
/// Run `probe.py` against an interpreter.
|
|
///
|
|
/// # Errors
|
|
/// `PD-ENV-001` when the interpreter is missing, `PD-ENV-003` when the probe fails or its output
|
|
/// cannot be read.
|
|
pub async fn probe(interpreter: &Path, source: EnvSource) -> Result<ProbeResult> {
|
|
if !interpreter.is_file() {
|
|
return Err(PdError::new(
|
|
Code::EnvInterpreterMissing,
|
|
format!("no interpreter at {}", interpreter.display()),
|
|
));
|
|
}
|
|
|
|
// Removed when it drops, whatever happens; a leaked temp file is harmless but untidy, and
|
|
// leaving one behind after every scan is not.
|
|
let script = TempFile::create("pipdock-probe", "py", PROBE_PY)?;
|
|
// **`-X utf8` is not redundant with `Command::python`'s environment.** `-I` implies `-E`, so
|
|
// PYTHONUTF8 and PYTHONIOENCODING are ignored and stdout falls back to the ANSI code page. The
|
|
// probe prints paths with `ensure_ascii=False`, so a venv under `C:\Dự án\` crashed it with a
|
|
// UnicodeEncodeError (PD-ENV-003) and a `Jürgen` came back as mojibake. `-X` is a command-line
|
|
// option, which isolated mode honours. Reproduced before fixing.
|
|
let out = Command::python(interpreter)
|
|
.args(["-X", "utf8", "-I"])
|
|
.arg(script.path().display().to_string())
|
|
.arg("--json")
|
|
.timeout(watchdog::PROBE)
|
|
.run()
|
|
.await?;
|
|
|
|
if !out.ok() {
|
|
return Err(
|
|
PdError::new(Code::EnvProbeFailed, format!("probe exited {:?}", out.code))
|
|
.with_stderr(&out.stderr),
|
|
);
|
|
}
|
|
|
|
parse_probe(&out.stdout, interpreter, source)
|
|
}
|
|
|
|
/// Parse the probe's JSON document.
|
|
///
|
|
/// # Errors
|
|
/// `PD-ENV-003` when the document is missing or malformed.
|
|
pub fn parse_probe(stdout: &str, interpreter: &Path, source: EnvSource) -> Result<ProbeResult> {
|
|
let bad = |detail: &str| {
|
|
PdError::new(
|
|
Code::EnvProbeFailed,
|
|
format!("unreadable probe output: {detail}"),
|
|
)
|
|
};
|
|
|
|
let doc: serde_json::Value =
|
|
serde_json::from_str(stdout.trim()).map_err(|e| bad(&e.to_string()))?;
|
|
if let Some(err) = doc.get("error").and_then(serde_json::Value::as_str) {
|
|
return Err(bad(err));
|
|
}
|
|
|
|
let python_version = doc
|
|
.get("python")
|
|
.and_then(serde_json::Value::as_str)
|
|
.ok_or_else(|| bad("no `python` field"))?
|
|
.to_owned();
|
|
|
|
let mut dists = Vec::new();
|
|
for entry in doc
|
|
.get("dists")
|
|
.and_then(serde_json::Value::as_array)
|
|
.into_iter()
|
|
.flatten()
|
|
{
|
|
// The probe reports unreadable distributions as `{"name": null, "error": ...}` rather
|
|
// than failing the whole scan; skip them here for the same reason.
|
|
let Some(raw_name) = entry.get("name").and_then(serde_json::Value::as_str) else {
|
|
continue;
|
|
};
|
|
let Ok(name) = PkgName::parse(raw_name) else {
|
|
continue;
|
|
};
|
|
dists.push(Dist {
|
|
name,
|
|
version: Version(
|
|
entry
|
|
.get("version")
|
|
.and_then(serde_json::Value::as_str)
|
|
.unwrap_or_default()
|
|
.to_owned(),
|
|
),
|
|
requires_dist: entry
|
|
.get("requires_dist")
|
|
.and_then(serde_json::Value::as_array)
|
|
.map(|a| {
|
|
a.iter()
|
|
.filter_map(|v| v.as_str().map(str::to_owned))
|
|
.collect()
|
|
})
|
|
.unwrap_or_default(),
|
|
requires_python: entry
|
|
.get("requires_python")
|
|
.and_then(serde_json::Value::as_str)
|
|
.map(str::to_owned),
|
|
// Absent on a schema-1 probe and null whenever the probe judged the number
|
|
// unknowable; both arrive here as `None`, which is the honest answer either way.
|
|
size_bytes: entry.get("size_bytes").and_then(serde_json::Value::as_u64),
|
|
});
|
|
}
|
|
|
|
let env = PyEnv {
|
|
interpreter: interpreter.to_path_buf(),
|
|
prefix: doc
|
|
.get("prefix")
|
|
.and_then(serde_json::Value::as_str)
|
|
.unwrap_or_default()
|
|
.into(),
|
|
python_version,
|
|
externally_managed: doc
|
|
.get("externally_managed")
|
|
.and_then(serde_json::Value::as_bool)
|
|
.unwrap_or(false),
|
|
hidden_user_site: doc
|
|
.get("hidden_user_site")
|
|
.and_then(serde_json::Value::as_str)
|
|
.map(PathBuf::from),
|
|
source,
|
|
};
|
|
|
|
let markers = doc
|
|
.get("markers")
|
|
.and_then(serde_json::Value::as_object)
|
|
.map(|m| {
|
|
m.iter()
|
|
.filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned())))
|
|
.collect()
|
|
})
|
|
.unwrap_or_default();
|
|
|
|
Ok(ProbeResult {
|
|
env,
|
|
dists,
|
|
markers,
|
|
})
|
|
}
|
|
|
|
/// A discovered interpreter, before it has been probed.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Candidate {
|
|
/// Path to the interpreter.
|
|
pub path: PathBuf,
|
|
/// Where it was found.
|
|
pub source: EnvSource,
|
|
}
|
|
|
|
/// Discover every interpreter on this machine.
|
|
///
|
|
/// Sources are queried independently and merged by canonical identity, so a Chocolatey shim and
|
|
/// the installation it points at collapse into one entry (SP-6). The **first** source to report a
|
|
/// path wins, and sources are ordered so the more authoritative one is asked first.
|
|
///
|
|
/// Discovery alone: interpreters a person added are not here. Code Health's choice of a Python to
|
|
/// build its tools venv with reads this, and should choose among installations, not among whatever
|
|
/// the user pointed the Environments screen at.
|
|
pub async fn scan() -> Vec<Candidate> {
|
|
scan_reporting(&[], &|_| {}).await
|
|
}
|
|
|
|
/// Discovery plus the interpreters a person added (*Browse…*, `pipdock env add`), for the two
|
|
/// listings — the Environments screen and `pipdock env list`.
|
|
pub async fn scan_with(manual: &[PathBuf]) -> Vec<Candidate> {
|
|
scan_reporting(manual, &|_| {}).await
|
|
}
|
|
|
|
/// Refuse an interpreter path a person supplied before anything runs it (SECURITY §2).
|
|
///
|
|
/// Discovery finds interpreters where Python installs them. A path from *Browse…*, `pipdock env
|
|
/// add`, `env use` or `--env` can name anything, and the probe **runs** the file — so this is the
|
|
/// enforcement point, not the picker, which only suggests:
|
|
///
|
|
/// - it must exist and be a file, or there is nothing to probe;
|
|
/// - its name must be `python.exe`, `python3.exe`, `python3.12.exe` or the free-threaded
|
|
/// `python3.14t.exe` (`python`, `python3`, … off
|
|
/// Windows), so that adding an interpreter is not a way to start any program with PipDock's
|
|
/// arguments. `pythonw.exe` is refused too: it has no console, the probe's output would be empty,
|
|
/// and the failure would read as a broken environment instead of the wrong file;
|
|
/// - it must not be one of PipDock's own environments — Code Health's tools venv or the Security
|
|
/// tab's audit venv — which PipDock builds and replaces itself, and which a user's update would
|
|
/// quietly break. The check is on resolved paths too, or `..` or a link would walk past it.
|
|
///
|
|
/// **Returns the path as given, made absolute — never with its links resolved.** A venv made with
|
|
/// `--symlinks` has a `Scripts\python.exe` that is a link to the base interpreter, and running the
|
|
/// *link* is what makes Python find the venv's `pyvenv.cfg`. The first version returned the
|
|
/// canonical path, so `--env .venv` ran — and *Add interpreter…* stored — the base Python instead
|
|
/// of the venv: an update meant for a project would have changed the system's Python. Found by an
|
|
/// independent review of 1.6.0 and reproduced before fixing. Where the link really points is still
|
|
/// checked: a `python.exe` that links to another program is another program, and is refused.
|
|
///
|
|
/// A Microsoft Store app-execution alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\python.exe`) is a
|
|
/// file Windows will not resolve at all (os error 1920); it is judged by its own path, and accepted,
|
|
/// as discovery has always listed it.
|
|
///
|
|
/// # Errors
|
|
/// `PD-ENV-001` for each refusal, the message saying which. A missing file reads exactly as the
|
|
/// probe's own "no interpreter at …", so a caller that validates first changes no output.
|
|
pub fn validate_interpreter(path: &Path, app_data: &Path) -> Result<PathBuf> {
|
|
use crate::health::project::plain;
|
|
let refuse = |why: String| PdError::new(Code::EnvInterpreterMissing, why);
|
|
if !path.is_file() {
|
|
return Err(refuse(format!("no interpreter at {}", path.display())));
|
|
}
|
|
if !is_python_name(path) {
|
|
return Err(refuse(format!(
|
|
"{} is not a Python interpreter PipDock will run: the file has to be python.exe \
|
|
(or python3.exe, python3.12.exe, python3.14t.exe)",
|
|
path.display()
|
|
)));
|
|
}
|
|
let absolute = std::path::absolute(path)
|
|
.map(plain)
|
|
.map_err(|e| refuse(format!("cannot read {}: {e}", path.display())))?;
|
|
let target = path.canonicalize().map(plain).ok();
|
|
if let Some(target) = &target
|
|
&& !is_python_name(target)
|
|
{
|
|
return Err(refuse(format!(
|
|
"{} leads to {}, which is not a Python interpreter PipDock will run",
|
|
path.display(),
|
|
target.display()
|
|
)));
|
|
}
|
|
let own_dirs: Vec<PathBuf> = [
|
|
crate::health::tools_dir(app_data),
|
|
crate::health::audit_dir(app_data),
|
|
]
|
|
.iter()
|
|
.flat_map(|dir| {
|
|
[
|
|
dir.canonicalize().map(plain).ok(),
|
|
std::path::absolute(dir).map(plain).ok(),
|
|
]
|
|
})
|
|
.flatten()
|
|
.collect();
|
|
let inside_own = |p: &Path| own_dirs.iter().any(|own| p.starts_with(own));
|
|
if inside_own(&absolute) || target.as_deref().is_some_and(inside_own) {
|
|
return Err(refuse(format!(
|
|
"{} is one of PipDock's own environments, which it manages itself",
|
|
path.display()
|
|
)));
|
|
}
|
|
Ok(absolute)
|
|
}
|
|
|
|
/// `python`, `python3` or `python3.12`, with `.exe` on Windows; any case. A version may end in `t`,
|
|
/// the free-threaded build's name (`python3.14t.exe`, PEP 703) — the python.org installer puts one
|
|
/// beside `python.exe`, and the registry reports it; refusing it was found by running `env list`
|
|
/// against this machine's own Pythons.
|
|
fn is_python_name(path: &Path) -> bool {
|
|
let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
|
|
return false;
|
|
};
|
|
let name = name.to_ascii_lowercase();
|
|
let stem = if cfg!(windows) {
|
|
match name.strip_suffix(".exe") {
|
|
Some(stem) => stem,
|
|
None => return false,
|
|
}
|
|
} else {
|
|
name.as_str()
|
|
};
|
|
let Some(version) = stem.strip_prefix("python") else {
|
|
return false;
|
|
};
|
|
let version = match version.strip_suffix('t') {
|
|
Some(threaded) if !threaded.is_empty() => threaded,
|
|
_ => version,
|
|
};
|
|
version.is_empty()
|
|
|| (version.split('.').count() <= 2
|
|
&& version
|
|
.split('.')
|
|
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())))
|
|
}
|
|
|
|
/// An interpreter path, or the interpreter inside an environment directory (CLI-SPEC §2).
|
|
///
|
|
/// `<dir>\Scripts\python.exe` on Windows, `<dir>/bin/python` elsewhere; anything else comes back
|
|
/// unchanged, for [`validate_interpreter`] to refuse with the path the person gave.
|
|
#[must_use]
|
|
pub fn interpreter_in(path: &Path) -> PathBuf {
|
|
if path.is_file() {
|
|
return path.to_path_buf();
|
|
}
|
|
let candidate = venv_interpreter(path);
|
|
if candidate.is_file() {
|
|
candidate
|
|
} else {
|
|
path.to_path_buf()
|
|
}
|
|
}
|
|
|
|
/// Where a virtual environment's interpreter is, whether or not it is there: `<dir>\Scripts\python.exe`
|
|
/// on Windows, `<dir>/bin/python` elsewhere. `pipdock env remove <dir>` needs the answer for a venv
|
|
/// that has been deleted — exactly the entry someone wants gone, and one [`interpreter_in`] can no
|
|
/// longer resolve.
|
|
#[must_use]
|
|
pub fn venv_interpreter(dir: &Path) -> PathBuf {
|
|
if cfg!(windows) {
|
|
dir.join("Scripts").join("python.exe")
|
|
} else {
|
|
dir.join("bin").join("python")
|
|
}
|
|
}
|
|
|
|
/// Where a discovery sweep currently is.
|
|
///
|
|
/// ARCHITECTURE §7 names a `scan-progress` event and never says what it carries; this is the
|
|
/// payload. Discovery is the slowest thing PipDock does before it can show anything — a registry
|
|
/// walk, `py -0p`, `uv python list` and a venv scan, each spawning processes — so a first screen
|
|
/// that sits blank through all of it is the worst possible first impression.
|
|
///
|
|
/// `label` is a path and is **never localized** (I18N §2). The UI localizes `phase`.
|
|
#[derive(
|
|
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
|
)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct ScanProgress {
|
|
/// Which source is being read.
|
|
pub phase: ScanPhase,
|
|
/// Sources finished so far.
|
|
pub done: usize,
|
|
/// How many sources there are, so a caller can render a determinate bar.
|
|
pub total: usize,
|
|
/// The interpreter or directory in hand, when there is one.
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub label: Option<String>,
|
|
}
|
|
|
|
/// The discovery sources, in the order [`scan`] reads them.
|
|
#[derive(
|
|
Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
|
|
)]
|
|
#[serde(rename_all = "kebab-case")]
|
|
pub enum ScanPhase {
|
|
/// PEP 514 registry entries.
|
|
Registry,
|
|
/// `py -0p`.
|
|
Launcher,
|
|
/// `uv python list`.
|
|
Uv,
|
|
/// `.venv` directories below the working directory.
|
|
VenvScan,
|
|
/// Deduplicating and canonicalizing what was found.
|
|
Collating,
|
|
}
|
|
|
|
/// How many sources a sweep reads, for the `total` a caller renders against.
|
|
const SCAN_SOURCES: usize = 5;
|
|
|
|
/// Discover environments, reporting progress as each source is read, and append the interpreters a
|
|
/// person added.
|
|
///
|
|
/// `manual` comes last, so an interpreter discovery also finds keeps the discovered source — the
|
|
/// chip says where Python put it, which is the more useful fact. Unlike every discovered path, a
|
|
/// manual one is kept **when its file is gone**: dropping it would make an entry the user added
|
|
/// vanish without a word, and with no row there would be nothing to remove it from. Its probe then
|
|
/// fails with `PD-ENV-001`, whose remedy is exactly that removal.
|
|
///
|
|
/// The callback is synchronous and must not block: it is called between sources, on the task
|
|
/// driving the scan.
|
|
pub async fn scan_reporting(
|
|
manual: &[PathBuf],
|
|
report: &(dyn Fn(ScanProgress) + Sync),
|
|
) -> Vec<Candidate> {
|
|
let step = |phase: ScanPhase, done: usize| ScanProgress {
|
|
phase,
|
|
done,
|
|
total: SCAN_SOURCES,
|
|
label: None,
|
|
};
|
|
|
|
report(step(ScanPhase::Registry, 0));
|
|
let registry = registry_interpreters();
|
|
report(step(ScanPhase::Launcher, 1));
|
|
let launcher = py_launcher_interpreters().await;
|
|
report(step(ScanPhase::Uv, 2));
|
|
let uv = uv_interpreters().await;
|
|
report(step(ScanPhase::VenvScan, 3));
|
|
let venvs = venv_scan(&std::env::current_dir().unwrap_or_default());
|
|
report(step(ScanPhase::Collating, 4));
|
|
|
|
let mut found: BTreeMap<String, Candidate> = BTreeMap::new();
|
|
let sources = [
|
|
(registry, EnvSource::Registry),
|
|
(launcher, EnvSource::PyLauncher),
|
|
(uv, EnvSource::Uv),
|
|
(venvs, EnvSource::VenvScan),
|
|
];
|
|
for (paths, source) in sources {
|
|
for path in paths {
|
|
if !path.is_file() {
|
|
continue;
|
|
}
|
|
found
|
|
.entry(canonical_interpreter(&path))
|
|
.or_insert(Candidate { path, source });
|
|
}
|
|
}
|
|
merge_manual(found, manual)
|
|
}
|
|
|
|
/// Discovered candidates in canonical order, then the manual ones no source already reported, in
|
|
/// the order they were added.
|
|
///
|
|
/// Compared by the path as listed — made absolute, case-folded on Windows — and **not** by
|
|
/// [`canonical_interpreter`], which follows links: a venv made with `--symlinks` would otherwise
|
|
/// collapse into the base interpreter its `python.exe` points at, and the venv a person added would
|
|
/// never be listed.
|
|
fn merge_manual(found: BTreeMap<String, Candidate>, manual: &[PathBuf]) -> Vec<Candidate> {
|
|
let mut out: Vec<Candidate> = found.into_values().collect();
|
|
let mut seen: std::collections::HashSet<String> =
|
|
out.iter().map(|c| listing_key(&c.path)).collect();
|
|
for path in manual {
|
|
if seen.insert(listing_key(path)) {
|
|
out.push(Candidate {
|
|
path: path.clone(),
|
|
source: EnvSource::Manual,
|
|
});
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// A path as a listing compares it: absolute, case-folded on Windows, links left alone.
|
|
fn listing_key(path: &Path) -> String {
|
|
let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
|
|
let text = absolute.display().to_string();
|
|
if cfg!(windows) {
|
|
text.to_lowercase()
|
|
} else {
|
|
text
|
|
}
|
|
}
|
|
|
|
/// Probe a candidate a listing returned — the one place both heads decide what a listing runs.
|
|
///
|
|
/// An added interpreter goes through [`validate_interpreter`] again on **every** listing, not only
|
|
/// on the day it was added: that check said what the file was then, and a `python.exe` that is a
|
|
/// link can be pointed at another program afterwards. `env_scan` and `env list` probed stored
|
|
/// entries unchecked until an independent review of 1.6.0 said so. A discovered path is probed as
|
|
/// found — discovery read it from where Python installs interpreters, and no person typed it.
|
|
///
|
|
/// # Errors
|
|
/// What [`validate_interpreter`] or [`probe`] reports: `PD-ENV-001` for a file that is gone (in the
|
|
/// probe's own words) or is not a Python PipDock will run, `PD-ENV-003` for a probe that fails.
|
|
pub async fn probe_listed(candidate: &Candidate, app_data: &Path) -> Result<ProbeResult> {
|
|
if candidate.source == EnvSource::Manual {
|
|
let path = candidate.path.clone();
|
|
let app_data = app_data.to_path_buf();
|
|
// On a blocking thread: the check reads the file system (`rust:S7493`).
|
|
tokio::task::spawn_blocking(move || validate_interpreter(&path, &app_data))
|
|
.await
|
|
.map_err(|e| {
|
|
PdError::new(
|
|
Code::IntUnexpected,
|
|
format!("interpreter check stopped: {e}"),
|
|
)
|
|
})??;
|
|
}
|
|
probe(&candidate.path, candidate.source).await
|
|
}
|
|
|
|
/// PEP 514 registry entries: `HKCU`, and both views of `HKLM`.
|
|
///
|
|
/// SP-6 found `PythonCore` present under **both** hives on the reference machine, which is one of
|
|
/// the two ways the same interpreter reaches discovery twice.
|
|
///
|
|
/// PEP 514 puts a 32-bit all-users install under `HKLM\Software\Wow6432Node\Python`, which a
|
|
/// 64-bit process does not see through the default view — so every such Python was missing from
|
|
/// the registry source. `HKCU` is shared between the views and needs no second read.
|
|
#[must_use]
|
|
pub fn registry_interpreters() -> Vec<PathBuf> {
|
|
#[cfg(windows)]
|
|
{
|
|
use winreg::RegKey;
|
|
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY};
|
|
|
|
let mut out = Vec::new();
|
|
for (hive, view) in [
|
|
(HKEY_CURRENT_USER, 0),
|
|
(HKEY_LOCAL_MACHINE, 0),
|
|
(HKEY_LOCAL_MACHINE, KEY_WOW64_32KEY),
|
|
] {
|
|
let flags = KEY_READ | view;
|
|
let root = RegKey::predef(hive);
|
|
let Ok(software) = root.open_subkey_with_flags(r"SOFTWARE\Python", flags) else {
|
|
continue;
|
|
};
|
|
for company in software.enum_keys().flatten() {
|
|
let Ok(company_key) = software.open_subkey_with_flags(&company, flags) else {
|
|
continue;
|
|
};
|
|
for tag in company_key.enum_keys().flatten() {
|
|
let Ok(install) =
|
|
company_key.open_subkey_with_flags(format!(r"{tag}\InstallPath"), flags)
|
|
else {
|
|
continue;
|
|
};
|
|
// PEP 514: `ExecutablePath` is authoritative; the default value is the
|
|
// directory, which older installers set instead.
|
|
if let Ok(exe) = install.get_value::<String, _>("ExecutablePath") {
|
|
out.push(PathBuf::from(exe));
|
|
} else if let Ok(dir) = install.get_value::<String, _>("") {
|
|
out.push(Path::new(&dir).join("python.exe"));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
#[cfg(not(windows))]
|
|
{
|
|
Vec::new()
|
|
}
|
|
}
|
|
|
|
/// Interpreters reported by the `py` launcher (`py -0p`).
|
|
pub async fn py_launcher_interpreters() -> Vec<PathBuf> {
|
|
let Ok(out) = Command::new("py")
|
|
.arg("-0p")
|
|
.timeout(watchdog::DISCOVERY)
|
|
.run()
|
|
.await
|
|
else {
|
|
return Vec::new();
|
|
};
|
|
if !out.ok() {
|
|
return Vec::new();
|
|
}
|
|
out.stdout.lines().filter_map(parse_listed_path).collect()
|
|
}
|
|
|
|
/// Interpreters reported by `uv python list`.
|
|
///
|
|
/// SP-6: uv lists **downloadable** interpreters alongside installed ones. Those rows carry
|
|
/// `<download available>` where a path would be, and must be dropped — offering to manage a
|
|
/// Python that is not on the machine would be nonsense.
|
|
pub async fn uv_interpreters() -> Vec<PathBuf> {
|
|
let Ok(out) = Command::new("uv")
|
|
.args(["python", "list"])
|
|
.timeout(watchdog::DISCOVERY)
|
|
.run()
|
|
.await
|
|
else {
|
|
return Vec::new();
|
|
};
|
|
if !out.ok() {
|
|
return Vec::new();
|
|
}
|
|
out.stdout.lines().filter_map(parse_listed_path).collect()
|
|
}
|
|
|
|
/// The interpreter path of one `py -0p` or `uv python list` row.
|
|
///
|
|
/// Both print a key that never contains whitespace — `-V:3.14`, `cpython-3.14.7-windows-x86_64-none`
|
|
/// — then, for `py`, an optional `*` marking the default, then the path. **The path may contain
|
|
/// spaces.** Taking the last whitespace-separated token turned `C:\Program Files\Python312\python.exe`
|
|
/// — where every all-users python.org installer puts it — into the relative
|
|
/// `Files\Python312\python.exe`, which the existence check then quietly dropped. A row uv offers to
|
|
/// download carries `<download available>` where the path would be, and is rejected.
|
|
fn parse_listed_path(line: &str) -> Option<PathBuf> {
|
|
let (_key, rest) = line.trim().split_once(char::is_whitespace)?;
|
|
let rest = rest.trim_start();
|
|
let rest = rest.strip_prefix('*').map_or(rest, str::trim_start);
|
|
// uv prints a symlink as `path -> target`; the listed path is the interpreter itself.
|
|
let path = rest.split(" -> ").next()?.trim_end();
|
|
if path.is_empty() || path.starts_with('<') {
|
|
return None;
|
|
}
|
|
let path = PathBuf::from(path);
|
|
path.is_absolute().then_some(path)
|
|
}
|
|
|
|
/// Virtual environments in `dir`, one level deep.
|
|
#[must_use]
|
|
pub fn venv_scan(dir: &Path) -> Vec<PathBuf> {
|
|
const NAMES: &[&str] = &[".venv", "venv", "env", ".env"];
|
|
let exe: PathBuf = if cfg!(windows) {
|
|
["Scripts", "python.exe"].iter().collect()
|
|
} else {
|
|
["bin", "python"].iter().collect()
|
|
};
|
|
|
|
NAMES
|
|
.iter()
|
|
.map(|name| dir.join(name).join(&exe))
|
|
.filter(|p| p.is_file())
|
|
.collect()
|
|
}
|
|
|
|
/// Is this interpreter new enough to run the probe?
|
|
#[must_use]
|
|
pub fn probe_supported(version: &str) -> bool {
|
|
let Ok(v) = PyVersion::parse(version) else {
|
|
return false;
|
|
};
|
|
let floor = format!("{}.{}", MIN_PROBE_PYTHON.0, MIN_PROBE_PYTHON.1);
|
|
PyVersion::parse(&floor).is_ok_and(|min| v >= min)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn probe_is_embedded_and_stdlib_only() {
|
|
assert!(
|
|
PROBE_PY.contains("importlib.metadata"),
|
|
"probe must read metadata"
|
|
);
|
|
// ARCHITECTURE §4: no third-party imports. These are the ones a careless edit would add.
|
|
for forbidden in [
|
|
"import requests",
|
|
"import packaging",
|
|
"import setuptools",
|
|
"import pip",
|
|
] {
|
|
assert!(
|
|
!PROBE_PY.contains(forbidden),
|
|
"probe must stay stdlib-only: {forbidden}"
|
|
);
|
|
}
|
|
}
|
|
|
|
fn scratch(name: &str) -> PathBuf {
|
|
let dir = std::env::temp_dir().join(format!("pd-envs-{name}-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
std::fs::create_dir_all(&dir).expect("create scratch dir");
|
|
dir
|
|
}
|
|
|
|
/// An empty file at `dir/rel`, which is all [`validate_interpreter`] looks at — it never runs it.
|
|
fn touch(dir: &Path, rel: &str) -> PathBuf {
|
|
let path = dir.join(rel);
|
|
std::fs::create_dir_all(path.parent().expect("a parent")).expect("parents");
|
|
std::fs::write(&path, "").expect("write");
|
|
path
|
|
}
|
|
|
|
fn exe(stem: &str) -> String {
|
|
if cfg!(windows) {
|
|
format!("{stem}.exe")
|
|
} else {
|
|
stem.to_owned()
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn only_a_file_named_like_python_is_accepted() {
|
|
// The free-threaded build (PEP 703) is `python3.14t.exe`, beside `python.exe` in the same
|
|
// install — the registry lists it on this repository's own reference machine.
|
|
for name in [
|
|
"python",
|
|
"PYTHON",
|
|
"python3",
|
|
"python3.12",
|
|
"Python3.14",
|
|
"python3.14t",
|
|
"python3t",
|
|
] {
|
|
assert!(is_python_name(Path::new(&exe(name))), "{name}");
|
|
}
|
|
// pythonw has no console; the rest are other programs, or versions that are not versions.
|
|
for name in [
|
|
"pythonw",
|
|
"pythonw3.14t",
|
|
"pythont",
|
|
"python3.14tt",
|
|
"notepad",
|
|
"py",
|
|
"python3.12.1",
|
|
"python3.",
|
|
"python.3",
|
|
"python3x",
|
|
"mypython",
|
|
] {
|
|
assert!(!is_python_name(Path::new(&exe(name))), "{name}");
|
|
}
|
|
if cfg!(windows) {
|
|
assert!(
|
|
!is_python_name(Path::new("python.bat")),
|
|
"a script is not an exe"
|
|
);
|
|
assert!(
|
|
!is_python_name(Path::new("python")),
|
|
"Windows needs the .exe"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_missing_interpreter_reads_exactly_as_the_probe_says_it() {
|
|
// The CLI's error-envelope goldens pin this sentence for `--env C:/definitely/not/here`.
|
|
let err = validate_interpreter(Path::new("C:/definitely/not/here"), &scratch("missing"))
|
|
.expect_err("nothing there");
|
|
assert_eq!(err.code, Code::EnvInterpreterMissing);
|
|
assert_eq!(err.message, "no interpreter at C:/definitely/not/here");
|
|
}
|
|
|
|
#[test]
|
|
fn another_program_is_refused_before_anything_runs_it() {
|
|
let dir = scratch("other");
|
|
let notepad = touch(&dir, &exe("notepad"));
|
|
let err = validate_interpreter(¬epad, &dir.join("data")).expect_err("not python");
|
|
assert_eq!(err.code, Code::EnvInterpreterMissing);
|
|
assert!(
|
|
err.message.contains("is not a Python interpreter"),
|
|
"{}",
|
|
err.message
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_python_is_accepted_and_comes_back_absolute_and_plain() {
|
|
let dir = scratch("ok");
|
|
let python = touch(&dir, &format!("proj/.venv/Scripts/{}", exe("python")));
|
|
let got = validate_interpreter(&python, &dir.join("data")).expect("a python");
|
|
assert!(
|
|
!got.display().to_string().starts_with(r"\\?\"),
|
|
"no verbatim prefix: {}",
|
|
got.display()
|
|
);
|
|
assert_eq!(got, std::path::absolute(&python).expect("absolute"));
|
|
}
|
|
|
|
/// A link, or `None` where this machine may not make one (Windows without Developer Mode).
|
|
fn link(target: &Path, at: &Path) -> Option<()> {
|
|
std::fs::create_dir_all(at.parent().expect("a parent")).expect("parents");
|
|
#[cfg(windows)]
|
|
let made = std::os::windows::fs::symlink_file(target, at);
|
|
#[cfg(not(windows))]
|
|
let made = std::os::unix::fs::symlink(target, at);
|
|
made.ok()
|
|
}
|
|
|
|
#[test]
|
|
fn a_symlinked_venv_keeps_its_own_path_and_a_link_to_another_program_is_refused() {
|
|
// `python -m venv --symlinks`: the venv's python.exe links to the base interpreter, and
|
|
// only running the link finds the venv. Resolving it handed back — and stored — the base.
|
|
let dir = scratch("links");
|
|
let base = touch(&dir, &format!("base/{}", exe("python")));
|
|
let venv_python = dir.join("venv").join("Scripts").join(exe("python"));
|
|
let Some(()) = link(&base, &venv_python) else {
|
|
eprintln!("skipped: this machine cannot create symbolic links");
|
|
return;
|
|
};
|
|
let got = validate_interpreter(&venv_python, &dir.join("data")).expect("a python");
|
|
assert_eq!(got, std::path::absolute(&venv_python).expect("absolute"));
|
|
assert_ne!(
|
|
got,
|
|
std::path::absolute(&base).expect("absolute"),
|
|
"not the base"
|
|
);
|
|
|
|
// A python.exe that is really another program is still another program.
|
|
let other = touch(&dir, &format!("tools/{}", exe("notepad")));
|
|
let disguised = dir.join("disguise").join(exe("python"));
|
|
link(&other, &disguised).expect("links work here");
|
|
let err = validate_interpreter(&disguised, &dir.join("data")).expect_err("not python");
|
|
assert!(err.message.contains("leads to"), "{}", err.message);
|
|
}
|
|
|
|
#[test]
|
|
fn pipdocks_own_environments_are_refused_even_through_dot_dot() {
|
|
let dir = scratch("own");
|
|
let app_data = dir.join("data");
|
|
for own in ["tools", "audit"] {
|
|
let python = touch(&app_data, &format!("{own}/.venv/Scripts/{}", exe("python")));
|
|
let err = validate_interpreter(&python, &app_data).expect_err("PipDock's own");
|
|
assert!(err.message.contains("PipDock's own"), "{}", err.message);
|
|
|
|
// Reached the long way round: canonicalized before the comparison, or `..` walks past.
|
|
let sideways = app_data
|
|
.join("elsewhere")
|
|
.join("..")
|
|
.join(own)
|
|
.join(".venv")
|
|
.join("Scripts")
|
|
.join(exe("python"));
|
|
std::fs::create_dir_all(app_data.join("elsewhere")).expect("dir");
|
|
let err = validate_interpreter(&sideways, &app_data).expect_err("still PipDock's own");
|
|
assert!(err.message.contains("PipDock's own"), "{}", err.message);
|
|
}
|
|
// A sibling whose name merely starts with "tools" is someone else's.
|
|
let neighbour = touch(&app_data, &format!("tools-mine/{}", exe("python")));
|
|
validate_interpreter(&neighbour, &app_data).expect("not inside tools");
|
|
}
|
|
|
|
#[test]
|
|
fn an_environment_directory_resolves_to_its_interpreter() {
|
|
let dir = scratch("dir");
|
|
let inside = if cfg!(windows) {
|
|
format!("venv/Scripts/{}", exe("python"))
|
|
} else {
|
|
"venv/bin/python".to_owned()
|
|
};
|
|
let python = touch(&dir, &inside);
|
|
assert_eq!(interpreter_in(&dir.join("venv")), python);
|
|
assert_eq!(interpreter_in(&python), python, "a file is itself");
|
|
let nothing = dir.join("nothing-here");
|
|
assert_eq!(
|
|
interpreter_in(¬hing),
|
|
nothing,
|
|
"left for the validator to refuse"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn manual_entries_come_last_and_never_shadow_discovery() {
|
|
let discovered = PathBuf::from(r"C:\Python314\python.exe");
|
|
let mut found = BTreeMap::new();
|
|
found.insert(
|
|
canonical_interpreter(&discovered),
|
|
Candidate {
|
|
path: discovered.clone(),
|
|
source: EnvSource::Registry,
|
|
},
|
|
);
|
|
let manual = [
|
|
PathBuf::from(r"D:\work\proj\myenv\Scripts\python.exe"),
|
|
// The same interpreter the registry reported, in other casing: discovery keeps it.
|
|
PathBuf::from(r"c:\python314\python.exe"),
|
|
// Added twice, listed once.
|
|
PathBuf::from(r"D:\work\proj\myenv\Scripts\python.exe"),
|
|
// Gone from disk: still listed, so it can be removed.
|
|
PathBuf::from(r"E:\gone\python.exe"),
|
|
];
|
|
let merged = merge_manual(found, &manual);
|
|
let sources: Vec<_> = merged.iter().map(|c| (c.path.clone(), c.source)).collect();
|
|
let mut expected = vec![(discovered, EnvSource::Registry)];
|
|
if !cfg!(windows) {
|
|
// Off Windows the casing differs, so the second is its own interpreter.
|
|
expected.push((manual[0].clone(), EnvSource::Manual));
|
|
expected.push((manual[1].clone(), EnvSource::Manual));
|
|
} else {
|
|
expected.push((manual[0].clone(), EnvSource::Manual));
|
|
}
|
|
expected.push((manual[3].clone(), EnvSource::Manual));
|
|
assert_eq!(sources, expected);
|
|
}
|
|
|
|
#[test]
|
|
fn env_hash_is_stable_and_case_insensitive_on_windows() {
|
|
// SP-6: the Chocolatey shim and the direct install differ only in casing. Two hashes for
|
|
// one environment would split its pins and snapshot history without any visible cause.
|
|
let a = env_hash(Path::new(r"C:\Python314\python.exe"));
|
|
let b = env_hash(Path::new(r"c:\python314\python.exe"));
|
|
assert_eq!(a.len(), 64, "SHA-256 hex");
|
|
if cfg!(windows) {
|
|
assert_eq!(a, b);
|
|
}
|
|
assert_ne!(a, env_hash(Path::new(r"C:\Python312\python.exe")));
|
|
}
|
|
|
|
#[test]
|
|
fn parses_a_real_probe_document() {
|
|
let doc = r#"{
|
|
"schema": 2, "python": "3.12.4", "prefix": "C:\\proj\\.venv",
|
|
"is_venv": true, "externally_managed": false, "hidden_user_site": null,
|
|
"dists": [
|
|
{"name":"requests","version":"2.32.3",
|
|
"requires_dist":["urllib3<3,>=1.21.1"],"requires_python":">=3.8",
|
|
"size_bytes":131072},
|
|
{"name":null,"error":"KeyError: broken"}
|
|
]}"#;
|
|
let got = parse_probe(doc, Path::new("python.exe"), EnvSource::Manual).expect("parse");
|
|
|
|
assert_eq!(got.env.python_version, "3.12.4");
|
|
assert!(!got.env.externally_managed);
|
|
assert!(!got.env.listing_is_partial());
|
|
// The unreadable distribution is skipped rather than sinking the whole scan.
|
|
assert_eq!(got.dists.len(), 1);
|
|
assert_eq!(got.dists[0].name.as_str(), "requests");
|
|
assert_eq!(got.dists[0].requires_dist, ["urllib3<3,>=1.21.1"]);
|
|
assert_eq!(got.dists[0].size_bytes, Some(131_072));
|
|
}
|
|
|
|
#[test]
|
|
fn an_unknowable_size_arrives_as_none_not_zero() {
|
|
// Three ways the probe declines to guess, and one older probe that never knew to.
|
|
// `Some(0)` would render as "0 B" in the Installed table, which is a claim; `None`
|
|
// renders as "—", which is the truth.
|
|
let doc = r#"{
|
|
"schema": 2, "python": "3.12.4", "prefix": "C:\\proj\\.venv",
|
|
"externally_managed": false, "hidden_user_site": null,
|
|
"dists": [
|
|
{"name":"editable-one","version":"1.0.0","size_bytes":null},
|
|
{"name":"legacy-egg","version":"0.9.0"},
|
|
{"name":"schema-one-probe","version":"2.0.0"}
|
|
]}"#;
|
|
let got = parse_probe(doc, Path::new("python.exe"), EnvSource::Manual).expect("parse");
|
|
assert_eq!(got.dists.len(), 3);
|
|
assert!(got.dists.iter().all(|d| d.size_bytes.is_none()));
|
|
}
|
|
|
|
/// The join P4's remembered project folder rests on.
|
|
///
|
|
/// `env_scan` keys the store lookup off the **discovered candidate path**, before any probe has
|
|
/// run; `health_run` keys the store *write* off `PyEnv.interpreter`, which comes back through
|
|
/// the frontend afterwards. If those two ever hash differently the folder is written under one
|
|
/// key and read under another, and the only symptom is a Health screen that keeps asking where
|
|
/// the project is — no error, nothing in a log.
|
|
///
|
|
/// They agree because `parse_probe` carries the path it was given through untouched, and
|
|
/// `env_hash` canonicalizes whatever it is handed. Both halves are load-bearing, so both are
|
|
/// asserted here rather than reasoned about at the call site.
|
|
#[test]
|
|
fn a_probed_env_hashes_the_same_as_the_path_it_was_discovered_at() {
|
|
let doc = r#"{"python":"3.12.4","prefix":"C:\\proj\\.venv","externally_managed":false,
|
|
"hidden_user_site":null,"dists":[]}"#;
|
|
let discovered = Path::new(r"C:\Proj\.venv\Scripts\Python.exe");
|
|
let got = parse_probe(doc, discovered, EnvSource::VenvScan).expect("parse");
|
|
|
|
assert_eq!(
|
|
got.env.interpreter, discovered,
|
|
"the path is carried, not rewritten"
|
|
);
|
|
assert_eq!(
|
|
env_hash(discovered),
|
|
env_hash(&got.env.interpreter),
|
|
"the write key and the read key must be the same string"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_hidden_user_site_marks_the_listing_partial() {
|
|
let doc = r#"{"python":"3.14.6","prefix":"C:\\Python314","externally_managed":false,
|
|
"hidden_user_site":"C:\\Users\\a\\AppData\\Roaming\\Python\\Python314\\site-packages",
|
|
"dists":[]}"#;
|
|
let got = parse_probe(doc, Path::new("python.exe"), EnvSource::Registry).expect("parse");
|
|
assert!(got.env.listing_is_partial());
|
|
assert!(got.env.hidden_user_site.is_some());
|
|
}
|
|
|
|
#[test]
|
|
fn probe_errors_use_the_documented_code() {
|
|
for bad in [
|
|
"",
|
|
"not json",
|
|
r#"{"error":"ModuleNotFoundError"}"#,
|
|
r#"{"prefix":"x"}"#,
|
|
] {
|
|
let err = parse_probe(bad, Path::new("python.exe"), EnvSource::Manual)
|
|
.unwrap_err_or_panic(bad);
|
|
assert_eq!(err.code, Code::EnvProbeFailed, "{bad:?}");
|
|
}
|
|
}
|
|
|
|
/// Small helper so the loop above reads cleanly.
|
|
trait UnwrapErrOrPanic {
|
|
fn unwrap_err_or_panic(self, ctx: &str) -> PdError;
|
|
}
|
|
impl UnwrapErrOrPanic for Result<ProbeResult> {
|
|
fn unwrap_err_or_panic(self, ctx: &str) -> PdError {
|
|
match self {
|
|
Ok(_) => panic!("{ctx:?} should not have parsed"),
|
|
Err(e) => e,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn downloadable_uv_entries_are_rejected() {
|
|
// SP-6: `uv python list` mixes installed interpreters with ones it offers to fetch.
|
|
assert!(
|
|
parse_listed_path("cpython-3.15.0b4-windows-x86_64-none <download available>")
|
|
.is_none()
|
|
);
|
|
assert_eq!(
|
|
parse_listed_path(r"cpython-3.14.6-windows-x86_64-none C:\Python314\python.exe"),
|
|
Some(PathBuf::from(r"C:\Python314\python.exe"))
|
|
);
|
|
// `py -0p` rows have the same trailing-path shape.
|
|
assert_eq!(
|
|
parse_listed_path(r" -V:3.14 * C:\Python314\python.exe"),
|
|
Some(PathBuf::from(r"C:\Python314\python.exe"))
|
|
);
|
|
assert!(parse_listed_path("").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn a_listed_path_with_spaces_survives() {
|
|
// Where every all-users python.org installer puts Python. The last token alone was the
|
|
// relative `Files\Python312\python.exe`, and the interpreter vanished from discovery.
|
|
let program_files = r"C:\Program Files\Python312\python.exe";
|
|
for line in [
|
|
format!(" -V:3.12 {program_files}"),
|
|
format!(" -V:3.12 * {program_files}\r"),
|
|
format!(" -3.12-64 {program_files}"),
|
|
format!("cpython-3.12.10-windows-x86_64-none {program_files}"),
|
|
] {
|
|
assert_eq!(
|
|
parse_listed_path(&line),
|
|
Some(PathBuf::from(program_files)),
|
|
"{line:?}"
|
|
);
|
|
}
|
|
// uv's warnings, should one reach stdout, are not paths.
|
|
assert!(
|
|
parse_listed_path("warning: Failed to inspect Python interpreter from search path")
|
|
.is_none()
|
|
);
|
|
assert!(
|
|
parse_listed_path("cpython-3.16.0a1-windows-x86_64-none <download available>")
|
|
.is_none()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_marker_environment_is_carried_and_an_older_probe_has_none() {
|
|
let doc = r#"{"schema":3,"python":"3.14.7","prefix":"C:\\Python314",
|
|
"externally_managed":false,"hidden_user_site":null,
|
|
"markers":{"sys_platform":"win32","platform_machine":"AMD64","bogus":7},
|
|
"dists":[]}"#;
|
|
let got = parse_probe(doc, Path::new("python.exe"), EnvSource::Registry).expect("parse");
|
|
assert_eq!(
|
|
got.markers.get("sys_platform").map(String::as_str),
|
|
Some("win32")
|
|
);
|
|
assert_eq!(
|
|
got.markers.get("platform_machine").map(String::as_str),
|
|
Some("AMD64")
|
|
);
|
|
assert!(
|
|
!got.markers.contains_key("bogus"),
|
|
"only strings are markers"
|
|
);
|
|
|
|
let old = r#"{"schema":2,"python":"3.12.4","prefix":"x","externally_managed":false,
|
|
"hidden_user_site":null,"dists":[]}"#;
|
|
let got = parse_probe(old, Path::new("python.exe"), EnvSource::Registry).expect("parse");
|
|
assert!(got.markers.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn the_probe_reads_metadata_once_per_distribution() {
|
|
// `dist.version` and `dist.requires` each re-parse METADATA; on the path every environment
|
|
// open pays, asking all three tripled the work. Measured on CPython 3.14 with 64
|
|
// distributions: 154 ms before, 118 ms after, the same document either way.
|
|
// On the code, not the words: the probe's own comment names both on purpose.
|
|
assert!(
|
|
PROBE_PY.contains(r#""version": meta.get("Version")"#),
|
|
"the version comes from the one parse"
|
|
);
|
|
assert!(
|
|
PROBE_PY.contains(r#"meta.get_all("Requires-Dist")"#),
|
|
"the requirements come from the one parse"
|
|
);
|
|
// And it does not reach for `platform`, whose uname() is a WMI query on Windows.
|
|
assert!(!PROBE_PY.contains("import platform"));
|
|
}
|
|
|
|
#[test]
|
|
fn the_probe_python_floor_matches_the_document() {
|
|
assert_eq!(MIN_PROBE_PYTHON, (3, 10));
|
|
assert!(probe_supported("3.10.0"));
|
|
assert!(probe_supported("3.14.6"));
|
|
assert!(!probe_supported("3.9.18"));
|
|
assert!(!probe_supported("nonsense"));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn probing_a_missing_interpreter_is_an_env_error() {
|
|
let err = probe(Path::new("no-such-python.exe"), EnvSource::Manual)
|
|
.await
|
|
.expect_err("missing interpreter must fail");
|
|
assert_eq!(err.code, Code::EnvInterpreterMissing);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn an_added_entry_is_checked_again_on_every_listing() {
|
|
// The store held a Python when it was added; what it holds now is another program. Refused
|
|
// before anything runs it, and still a row — PD-ENV-001 — so it can be removed.
|
|
let dir = scratch("relisted");
|
|
let added = Candidate {
|
|
path: touch(&dir, &exe("notepad")),
|
|
source: EnvSource::Manual,
|
|
};
|
|
let err = probe_listed(&added, &dir.join("data"))
|
|
.await
|
|
.expect_err("refused");
|
|
assert_eq!(err.code, Code::EnvInterpreterMissing);
|
|
assert!(
|
|
err.message.contains("is not a Python interpreter"),
|
|
"{}",
|
|
err.message
|
|
);
|
|
|
|
// An entry whose file is gone reads exactly as the probe has always said it.
|
|
let gone = Candidate {
|
|
path: dir.join("deleted").join(exe("python")),
|
|
source: EnvSource::Manual,
|
|
};
|
|
let err = probe_listed(&gone, &dir.join("data"))
|
|
.await
|
|
.expect_err("gone");
|
|
assert_eq!(
|
|
err.message,
|
|
format!("no interpreter at {}", gone.path.display())
|
|
);
|
|
}
|
|
}
|