feat(core): scaffold the Cargo workspace, core crate and CLI surface
Phase 0 scaffold per ARCHITECTURE section 2. Everything compiles; nothing resolves or mutates yet. Implemented rather than stubbed, because the spikes need them and they are the parts the invariants rest on: - errors/catalog.rs: all 30 launch codes with their wire forms, plus tests that the wire codes are unique and match the PD-<AREA>-<NNN> grammar. Code::ALL drives the future "no code without fixture" gate. - model.rs: PkgName::parse does PEP 508 validation and PEP 503 normalization. This is the only way a name reaches an argv array, which makes SECURITY section 2 structural rather than aspirational; the test table rejects flags, separators and quoting attempts. - probe.py: stdlib-only, Python 3.10 floor, per ARCHITECTURE section 4. - The pip/uv argv builders, with tests asserting one token per argument. - ExecutionSummary::tally, so the "13 successful, 2 failed" headline is derived from the rows rather than accumulated alongside them. Stubbed with todo!() and a pointer to the milestone that fills them: the Engine trait impls, discovery, index, graph, snapshot, pins, health. UvEngine::parse_dry_run stays unimplemented on purpose — SP-1 must pin uv's text plan format before anything parses it. Two findings recorded in spikes/README.md: - probe.py under -I hides user-site packages: 352 dists vs 376 without it and 375 from pip list, on a non-venv system Python. Venvs are unaffected. The fix trades a documented security control against list accuracy, so it is left as an open SP-6 decision rather than settled here. - Python 3.14 deprecates subscripting absent metadata headers, which wrote DeprecationWarning to stderr on most distributions. probe.py now uses .get(); the probe must stay stderr-clean because noise reads as PD-ENV-003. rusqlite is held at 0.37: 0.40 pulls libsqlite3-sys 0.38.1, whose build script needs the unstable cfg_select! and will not build on stable 1.94.1. Recorded in the ARCHITECTURE version manifest. cargo fmt, clippy -D warnings and 23 tests are green. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
24 files changed
+4697
No files matched your search
Generated
+2324
File diff suppressed because it is too large.
Load diff
+28
@@ -0,0 +1,28 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/pipdock-core", "crates/pipdock-cli"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.94"
|
||||
license = "GPL-3.0-only"
|
||||
repository = "https://github.com/poli0981/pipdock"
|
||||
authors = ["Kokone (poli0981)"]
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
# The five hard invariants in CLAUDE.md are about *not* taking shortcuts around
|
||||
# the engine. These lints are the mechanical half of enforcing that.
|
||||
todo = "allow" # scaffold phase; flip to "warn" once M1 lands
|
||||
dbg_macro = "deny"
|
||||
print_stdout = "deny" # core is a library: emit events, never println
|
||||
unwrap_used = "deny"
|
||||
expect_used = "deny"
|
||||
|
||||
[profile.release]
|
||||
strip = true
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "pipdock-cli"
|
||||
description = "The `pipdock` command-line interface."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "pipdock"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.6.4", features = ["derive"] }
|
||||
pipdock-core = { path = "../pipdock-core" }
|
||||
serde_json = "1.0.151"
|
||||
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros"] }
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
|
||||
[dev-dependencies]
|
||||
assert_cmd = "2.2.2"
|
||||
insta = "1.48.0"
|
||||
@@ -0,0 +1,385 @@
|
||||
//! `pipdock` — the command-line head over `pipdock-core`.
|
||||
//!
|
||||
//! CLI-SPEC §1.1: every command maps 1:1 onto the core functions the GUI uses; **the CLI adds no
|
||||
//! logic of its own**. CLI-SPEC §1.2: safe by default — off a TTY, or with `--yes`, conflicts
|
||||
//! default to *skip*, never *force*.
|
||||
//!
|
||||
//! English-only in v1 (I18N §1); messages reuse catalog codes so they stay greppable.
|
||||
|
||||
// The CLI is the one place that legitimately writes to stdout; the core never does.
|
||||
#![allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
|
||||
/// Exit codes, exhaustively specified in CLI-SPEC §5.
|
||||
///
|
||||
/// Scripts pin against these, so the numbers are a public contract.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum Exit {
|
||||
/// All steps succeeded.
|
||||
Success = 0,
|
||||
/// Completed with per-package failures; see `counts.failed` in `--json`.
|
||||
PartialFailure = 1,
|
||||
/// Plan aborted — resolution impossible and the skip policy removed everything.
|
||||
PlanAborted = 2,
|
||||
/// Environment error, including a PEP 668 block (`PD-ENV-*`).
|
||||
EnvError = 3,
|
||||
/// Engine unavailable or too old (`PD-ENG-*`).
|
||||
EngineError = 4,
|
||||
/// Snapshot failure — **nothing was executed** (`PD-SNP-001`).
|
||||
SnapshotError = 5,
|
||||
/// Network or index error (`PD-NET-*`).
|
||||
NetworkError = 6,
|
||||
/// Internal error (`PD-INT-*`); the log path is printed.
|
||||
Internal = 10,
|
||||
/// User cancelled; child processes reaped and a partial summary printed.
|
||||
Cancelled = 130,
|
||||
}
|
||||
|
||||
impl From<Exit> for ExitCode {
|
||||
fn from(e: Exit) -> Self {
|
||||
Self::from(e as u8)
|
||||
}
|
||||
}
|
||||
|
||||
/// Conflict-handling strategy for `update` and `install`.
|
||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||
pub enum StrategyArg {
|
||||
/// Accept the resolver's compatible version. The safe default.
|
||||
Compatible,
|
||||
/// Force the latest version. Off a TTY this requires an explicit acknowledgement.
|
||||
Latest,
|
||||
}
|
||||
|
||||
/// Which engine to drive.
|
||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||
pub enum EngineArg {
|
||||
/// `<python> -m pip`
|
||||
Pip,
|
||||
/// `uv pip --python <python>`
|
||||
Uv,
|
||||
}
|
||||
|
||||
/// Options accepted by every command (CLI-SPEC §2).
|
||||
#[derive(Debug, Args)]
|
||||
pub struct GlobalOpts {
|
||||
/// Interpreter or environment directory. Defaults to the last used env, else an
|
||||
/// auto-detected `.venv` in the working directory.
|
||||
#[arg(long, global = true, value_name = "PATH")]
|
||||
pub env: Option<PathBuf>,
|
||||
|
||||
/// Override the configured engine for this invocation.
|
||||
#[arg(long, global = true, value_enum)]
|
||||
pub engine: Option<EngineArg>,
|
||||
|
||||
/// Machine-readable output; NDJSON for streaming commands.
|
||||
#[arg(long, global = true)]
|
||||
pub json: bool,
|
||||
|
||||
/// Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*.
|
||||
#[arg(long, short = 'y', global = true)]
|
||||
pub yes: bool,
|
||||
|
||||
/// Reduce log output.
|
||||
#[arg(long, global = true, conflicts_with = "verbose")]
|
||||
pub quiet: bool,
|
||||
|
||||
/// Increase log output.
|
||||
#[arg(long, global = true)]
|
||||
pub verbose: bool,
|
||||
|
||||
/// Tee logs to a file.
|
||||
#[arg(long, global = true, value_name = "PATH")]
|
||||
pub log_file: Option<PathBuf>,
|
||||
|
||||
/// DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
|
||||
///
|
||||
/// This is the sole documented escape from DATA-FLOW §9.2, and it exists because a
|
||||
/// throwaway CI container has nothing to roll back to.
|
||||
#[arg(long, global = true)]
|
||||
pub no_snapshot: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
name = "pipdock",
|
||||
version,
|
||||
about = "A friendly dock for your Python environments.",
|
||||
long_about = "Inspect, install, update and clean up Python packages in bulk.\n\
|
||||
Every mutating operation is previewed and snapshotted first."
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(flatten)]
|
||||
global: GlobalOpts,
|
||||
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
/// The command surface, per CLI-SPEC §3.
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum Command {
|
||||
/// Manage environments.
|
||||
#[command(subcommand)]
|
||||
Env(EnvCommand),
|
||||
|
||||
/// List installed packages.
|
||||
List {
|
||||
/// Show only packages with a newer release available.
|
||||
#[arg(long)]
|
||||
outdated: bool,
|
||||
},
|
||||
|
||||
/// Fuzzy-search the local PyPI name index.
|
||||
Search {
|
||||
/// Query string.
|
||||
query: String,
|
||||
/// Maximum results.
|
||||
#[arg(long, default_value_t = 20)]
|
||||
limit: usize,
|
||||
},
|
||||
|
||||
/// Show cached PyPI metadata for a package.
|
||||
Info {
|
||||
/// Package name.
|
||||
pkg: String,
|
||||
},
|
||||
|
||||
/// Install packages.
|
||||
Install {
|
||||
/// `name` or `name==version`.
|
||||
#[arg(required = true)]
|
||||
specs: Vec<String>,
|
||||
/// Print the resolution report and exit without changing anything.
|
||||
#[arg(long)]
|
||||
dry_run: bool,
|
||||
},
|
||||
|
||||
/// Update packages.
|
||||
Update {
|
||||
/// Packages to update; omit and pass `--all` for everything.
|
||||
pkgs: Vec<String>,
|
||||
/// Update every outdated package (pins still apply).
|
||||
#[arg(long, conflicts_with = "pkgs")]
|
||||
all: bool,
|
||||
/// Conflict strategy.
|
||||
#[arg(long, value_enum, default_value = "compatible")]
|
||||
strategy: StrategyArg,
|
||||
/// Ad-hoc exclusions on top of the pin list.
|
||||
#[arg(long, value_delimiter = ',', value_name = "PKG,...")]
|
||||
except: Vec<String>,
|
||||
/// Print the resolution report and exit without changing anything.
|
||||
#[arg(long)]
|
||||
dry_run: bool,
|
||||
},
|
||||
|
||||
/// Remove packages, guarded by the reverse-dependency check.
|
||||
Uninstall {
|
||||
/// Packages to remove.
|
||||
#[arg(required = true)]
|
||||
pkgs: Vec<String>,
|
||||
/// Proceed even when the guard reports dependents that would break.
|
||||
#[arg(long)]
|
||||
force: bool,
|
||||
},
|
||||
|
||||
/// Manage the per-environment pin list.
|
||||
#[command(subcommand)]
|
||||
Pin(PinCommand),
|
||||
|
||||
/// Manage snapshots.
|
||||
#[command(subcommand)]
|
||||
Snapshot(SnapshotCommand),
|
||||
|
||||
/// Engine check and environment sanity report.
|
||||
Doctor,
|
||||
|
||||
/// Run Code Health (deptry / vulture / ruff) over a project folder.
|
||||
Health {
|
||||
/// Project folder; defaults to the folder remembered for this environment.
|
||||
#[arg(long, value_name = "DIR")]
|
||||
path: Option<PathBuf>,
|
||||
/// Run a single tool instead of all three.
|
||||
#[arg(long)]
|
||||
tool: Option<String>,
|
||||
/// Apply ruff's safe fixes. Prompts before writing.
|
||||
#[arg(long)]
|
||||
fix: bool,
|
||||
},
|
||||
|
||||
/// Upgrade pip inside the selected environment.
|
||||
PipUpgrade,
|
||||
|
||||
/// Show or set the configured engine.
|
||||
Engine {
|
||||
/// Engine to switch to; omit to print the current one.
|
||||
engine: Option<EngineArg>,
|
||||
},
|
||||
|
||||
/// Index maintenance.
|
||||
#[command(subcommand)]
|
||||
Index(IndexCommand),
|
||||
|
||||
/// Print the JSON Schema for a core type so scripts can pin against it.
|
||||
Schema {
|
||||
/// Type name, e.g. `ResolutionReport`.
|
||||
type_name: String,
|
||||
},
|
||||
|
||||
/// Self-service helpers.
|
||||
#[command(subcommand, name = "self")]
|
||||
Selfx(SelfCommand),
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum EnvCommand {
|
||||
/// List discovered environments, their sources and PEP 668 flags.
|
||||
List,
|
||||
/// Set the default environment.
|
||||
Use {
|
||||
/// Interpreter or environment directory.
|
||||
path: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum PinCommand {
|
||||
/// Pin a package so bulk updates skip it.
|
||||
Add {
|
||||
/// Package name.
|
||||
pkg: String,
|
||||
/// Why it is pinned.
|
||||
#[arg(long)]
|
||||
reason: Option<String>,
|
||||
},
|
||||
/// Remove a pin.
|
||||
Remove {
|
||||
/// Package name.
|
||||
pkg: String,
|
||||
},
|
||||
/// Show the pin list.
|
||||
List,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum SnapshotCommand {
|
||||
/// List snapshots for the selected environment.
|
||||
List,
|
||||
/// Take a snapshot now.
|
||||
Create,
|
||||
/// Diff a snapshot against the current environment.
|
||||
Diff {
|
||||
/// Snapshot id.
|
||||
id: String,
|
||||
},
|
||||
/// Restore a snapshot.
|
||||
Rollback {
|
||||
/// Snapshot id, or `latest`.
|
||||
id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum IndexCommand {
|
||||
/// Re-pull the PEP 691 name index.
|
||||
Refresh,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum SelfCommand {
|
||||
/// Print a prefilled GitHub issue URL.
|
||||
ReportBug,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
|
||||
// M1 wires each command to its pipdock-core call. Until then the binary parses its full
|
||||
// surface — which is what the CLI-SPEC §5 exit-code tests and the golden-output tests in
|
||||
// TESTING L4 exercise — and reports honestly that nothing is implemented.
|
||||
let _ = (&cli.global, &cli.command);
|
||||
eprintln!(
|
||||
"error[PD-INT-001]: pipdock is in Phase 0; commands are not implemented yet.\n\
|
||||
The command surface is parsed and stable — see docs/CLI-SPEC.md."
|
||||
);
|
||||
Exit::Internal.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::CommandFactory;
|
||||
|
||||
#[test]
|
||||
fn cli_definition_is_valid() {
|
||||
// Catches conflicting flags, duplicate shorts and bad defaults at test time rather than
|
||||
// at the user's first invocation.
|
||||
Cli::command().debug_assert();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_codes_match_the_specification() {
|
||||
// CLI-SPEC §5 is a public contract; scripts branch on these numbers.
|
||||
assert_eq!(Exit::Success as u8, 0);
|
||||
assert_eq!(Exit::PartialFailure as u8, 1);
|
||||
assert_eq!(Exit::PlanAborted as u8, 2);
|
||||
assert_eq!(Exit::EnvError as u8, 3);
|
||||
assert_eq!(Exit::EngineError as u8, 4);
|
||||
assert_eq!(Exit::SnapshotError as u8, 5);
|
||||
assert_eq!(Exit::NetworkError as u8, 6);
|
||||
assert_eq!(Exit::Internal as u8, 10);
|
||||
assert_eq!(Exit::Cancelled as u8, 130);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_defaults_to_the_safe_strategy() {
|
||||
let cli = Cli::try_parse_from(["pipdock", "update", "--all"]).unwrap();
|
||||
match cli.command {
|
||||
Command::Update { strategy, all, .. } => {
|
||||
assert!(all);
|
||||
assert!(matches!(strategy, StrategyArg::Compatible));
|
||||
}
|
||||
other => panic!("expected update, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_examples_parse() {
|
||||
// The three examples in CLI-SPEC §7, verbatim.
|
||||
Cli::try_parse_from([
|
||||
"pipdock",
|
||||
"update",
|
||||
"--all",
|
||||
"--env",
|
||||
r"C:\bots\scraper\.venv",
|
||||
"--yes",
|
||||
"--json",
|
||||
"--log-file",
|
||||
r"C:\logs\pd.json",
|
||||
])
|
||||
.expect("nightly maintenance example");
|
||||
|
||||
Cli::try_parse_from([
|
||||
"pipdock",
|
||||
"update",
|
||||
"pandas",
|
||||
"numpy",
|
||||
"--dry-run",
|
||||
"--json",
|
||||
])
|
||||
.expect("audit example");
|
||||
|
||||
Cli::try_parse_from(["pipdock", "uninstall", "legacylib", "--json"])
|
||||
.expect("refuse-to-break example");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_and_explicit_packages_are_mutually_exclusive() {
|
||||
assert!(Cli::try_parse_from(["pipdock", "update", "--all", "numpy"]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "pipdock-core"
|
||||
description = "Domain logic for PipDock: engine adapters, planning, snapshots, dependency graph."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
async-trait = "0.1.91"
|
||||
nucleo = "0.5.0"
|
||||
reqwest = { version = "0.13.4", default-features = false, features = ["rustls", "http2", "json", "gzip", "charset"] }
|
||||
rusqlite = { version = "0.37", features = ["bundled"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.151"
|
||||
thiserror = "2.0.19"
|
||||
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "process", "io-util", "time", "sync"] }
|
||||
tracing = "0.1.44"
|
||||
|
||||
[dev-dependencies]
|
||||
insta = { version = "1.48.0", features = ["json"] }
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The `Engine` trait and its two adapters.
|
||||
//!
|
||||
//! ARCHITECTURE §1.2: **explain, don't reimplement.** Resolution is always performed by the
|
||||
//! selected engine in dry-run mode; this module parses and normalizes, and never computes version
|
||||
//! resolution itself.
|
||||
//!
|
||||
//! ARCHITECTURE §1.5: engines are invoked with argv arrays via `tokio::process::Command`,
|
||||
//! **never through a shell**.
|
||||
|
||||
pub mod pip;
|
||||
pub mod uv;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::errors::Result;
|
||||
use crate::model::{
|
||||
CheckReport, Dist, EngineId, EngineInfo, ExecMode, OutdatedDist, PinnedSpec, PkgName, PyEnv,
|
||||
StepResult,
|
||||
};
|
||||
use crate::plan::{PlanRequest, ResolutionReport};
|
||||
|
||||
/// Where live subprocess output goes.
|
||||
///
|
||||
/// The GUI forwards these to the `plan-progress` Tauri event feeding the console drawer
|
||||
/// (ARCHITECTURE §7); the CLI writes them as NDJSON when `--json` is set (CLI-SPEC §6).
|
||||
pub type EventSink = tokio::sync::mpsc::UnboundedSender<ProgressEvent>;
|
||||
|
||||
/// A line of progress from a running engine command.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ProgressEvent {
|
||||
/// Zero-based index of the step within the plan.
|
||||
pub step: usize,
|
||||
/// The package this line belongs to, absent for batch-wide output.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pkg: Option<PkgName>,
|
||||
/// Which execution phase is running.
|
||||
pub phase: ExecMode,
|
||||
/// One line of the engine's stdout or stderr, verbatim and never localized.
|
||||
pub line: String,
|
||||
}
|
||||
|
||||
/// The contract both adapters implement. See ARCHITECTURE §3.
|
||||
#[async_trait]
|
||||
pub trait Engine: Send + Sync {
|
||||
/// Which engine this is.
|
||||
fn id(&self) -> EngineId;
|
||||
|
||||
/// Version and availability for `env`.
|
||||
async fn info(&self, env: &PyEnv) -> EngineInfo;
|
||||
|
||||
/// Everything installed in `env`.
|
||||
async fn list_installed(&self, env: &PyEnv) -> Result<Vec<Dist>>;
|
||||
|
||||
/// Installed packages with a newer release available.
|
||||
async fn list_outdated(&self, env: &PyEnv) -> Result<Vec<OutdatedDist>>;
|
||||
|
||||
/// Dry-run resolve `req` against `env`, normalized into a [`ResolutionReport`].
|
||||
///
|
||||
/// This is the only way a plan may be produced; DATA-FLOW §9.1 forbids any mutating call
|
||||
/// without a report accepted in the same session.
|
||||
async fn resolve(&self, env: &PyEnv, req: &PlanRequest) -> Result<ResolutionReport>;
|
||||
|
||||
/// Install an exact pinned set.
|
||||
///
|
||||
/// `Batch` mode passes the whole set in one invocation (Phase A); `Isolated` mode is the
|
||||
/// per-package retry loop (Phase B), where a failure must **not** stop the caller's loop.
|
||||
async fn install(
|
||||
&self,
|
||||
env: &PyEnv,
|
||||
specs: &[PinnedSpec],
|
||||
mode: ExecMode,
|
||||
sink: EventSink,
|
||||
) -> Result<StepResult>;
|
||||
|
||||
/// Remove packages. Always sequential; the reverse-dependency guard runs once up front
|
||||
/// against the full removal set (ARCHITECTURE §8).
|
||||
async fn uninstall(
|
||||
&self,
|
||||
env: &PyEnv,
|
||||
names: &[PkgName],
|
||||
sink: EventSink,
|
||||
) -> Result<StepResult>;
|
||||
|
||||
/// `pip check` / `uv pip check`, normalized.
|
||||
async fn check(&self, env: &PyEnv) -> Result<CheckReport>;
|
||||
|
||||
/// Upgrade pip inside `env`. The uv adapter returns an `Unsupported` error — DATA-FLOW §7
|
||||
/// says pip upkeep is surfaced only when pip is the active engine or present in the env.
|
||||
async fn upgrade_pip(&self, env: &PyEnv) -> Result<StepResult>;
|
||||
}
|
||||
|
||||
/// pip's floor for `install --dry-run --report -`. Below this, planning is impossible and the app
|
||||
/// offers a one-click pip upgrade (`PD-ENG-002`, DATA-FLOW §7).
|
||||
pub const PIP_MIN_VERSION_FOR_REPORT: (u32, u32) = (22, 2);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn documented_pip_floor() {
|
||||
// DATA-FLOW §7 and ERROR-CATALOG PD-ENG-002 both name 22.2; keep them in step.
|
||||
assert_eq!(PIP_MIN_VERSION_FOR_REPORT, (22, 2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! The pip adapter: `<env-python> -m pip …`.
|
||||
//!
|
||||
//! Command mapping is fixed by `docs/DATA-FLOW.md` §7. Implementation lands in M1; the argv
|
||||
//! builders below are already exercised by tests because they are the surface SECURITY §2 cares
|
||||
//! about — nothing else in this file may construct engine arguments.
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::errors::Result;
|
||||
use crate::model::{
|
||||
CheckReport, Dist, EngineId, EngineInfo, ExecMode, OutdatedDist, PinnedSpec, PkgName, PyEnv,
|
||||
StepResult,
|
||||
};
|
||||
use crate::plan::{PlanRequest, ResolutionReport};
|
||||
|
||||
use super::{Engine, EventSink};
|
||||
|
||||
/// Drives pip as a subprocess.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct PipEngine;
|
||||
|
||||
impl PipEngine {
|
||||
/// argv for `list --format=json`.
|
||||
#[must_use]
|
||||
pub fn argv_list() -> Vec<String> {
|
||||
vec![
|
||||
"-m".into(),
|
||||
"pip".into(),
|
||||
"list".into(),
|
||||
"--format=json".into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// argv for `list --outdated --format=json`.
|
||||
#[must_use]
|
||||
pub fn argv_outdated() -> Vec<String> {
|
||||
vec![
|
||||
"-m".into(),
|
||||
"pip".into(),
|
||||
"list".into(),
|
||||
"--outdated".into(),
|
||||
"--format=json".into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// argv for the dry-run resolve, whose JSON report goes to stdout.
|
||||
#[must_use]
|
||||
pub fn argv_dry_run(specs: &[PinnedSpec]) -> Vec<String> {
|
||||
let mut argv = vec![
|
||||
"-m".into(),
|
||||
"pip".into(),
|
||||
"install".into(),
|
||||
"--dry-run".into(),
|
||||
"--quiet".into(),
|
||||
"--report".into(),
|
||||
"-".into(),
|
||||
];
|
||||
argv.extend(specs.iter().map(PinnedSpec::to_requirement));
|
||||
argv
|
||||
}
|
||||
|
||||
/// argv for `freeze --all`, used for snapshots. `--all` keeps pip/setuptools in the freeze;
|
||||
/// the snapshot metadata records which engine produced it (DATA-FLOW §7).
|
||||
#[must_use]
|
||||
pub fn argv_freeze() -> Vec<String> {
|
||||
vec!["-m".into(), "pip".into(), "freeze".into(), "--all".into()]
|
||||
}
|
||||
|
||||
/// argv for `check`.
|
||||
#[must_use]
|
||||
pub fn argv_check() -> Vec<String> {
|
||||
vec!["-m".into(), "pip".into(), "check".into()]
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Engine for PipEngine {
|
||||
fn id(&self) -> EngineId {
|
||||
EngineId::Pip
|
||||
}
|
||||
|
||||
async fn info(&self, env: &PyEnv) -> EngineInfo {
|
||||
todo!("M1: run `{} -m pip --version`", env.interpreter.display())
|
||||
}
|
||||
|
||||
async fn list_installed(&self, _env: &PyEnv) -> Result<Vec<Dist>> {
|
||||
todo!("M1: parse argv_list() output into Dist")
|
||||
}
|
||||
|
||||
async fn list_outdated(&self, _env: &PyEnv) -> Result<Vec<OutdatedDist>> {
|
||||
todo!("M1: parse argv_outdated() output into OutdatedDist")
|
||||
}
|
||||
|
||||
async fn resolve(&self, _env: &PyEnv, _req: &PlanRequest) -> Result<ResolutionReport> {
|
||||
todo!("M1 (SP-2 fixtures): parse `--dry-run --report -` JSON into ResolutionReport")
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
_env: &PyEnv,
|
||||
_specs: &[PinnedSpec],
|
||||
_mode: ExecMode,
|
||||
_sink: EventSink,
|
||||
) -> Result<StepResult> {
|
||||
todo!("M1: two-phase execution per ARCHITECTURE §8")
|
||||
}
|
||||
|
||||
async fn uninstall(
|
||||
&self,
|
||||
_env: &PyEnv,
|
||||
_names: &[PkgName],
|
||||
_sink: EventSink,
|
||||
) -> Result<StepResult> {
|
||||
todo!("M1: `uninstall -y`, sequential, skip-and-continue")
|
||||
}
|
||||
|
||||
async fn check(&self, _env: &PyEnv) -> Result<CheckReport> {
|
||||
todo!("M1: normalize `pip check` findings")
|
||||
}
|
||||
|
||||
async fn upgrade_pip(&self, _env: &PyEnv) -> Result<StepResult> {
|
||||
todo!("M1: `install -U pip`")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::Version;
|
||||
|
||||
#[test]
|
||||
fn dry_run_argv_matches_the_documented_command() {
|
||||
let argv = PipEngine::argv_dry_run(&[]);
|
||||
assert_eq!(
|
||||
argv,
|
||||
[
|
||||
"-m",
|
||||
"pip",
|
||||
"install",
|
||||
"--dry-run",
|
||||
"--quiet",
|
||||
"--report",
|
||||
"-"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requirements_are_appended_as_separate_argv_entries() {
|
||||
// One token per argument is what makes shell quoting irrelevant (SECURITY §2).
|
||||
let specs = [
|
||||
PinnedSpec {
|
||||
name: PkgName::parse("httpx").unwrap(),
|
||||
version: Version("0.28.1".into()),
|
||||
},
|
||||
PinnedSpec {
|
||||
name: PkgName::parse("Requests").unwrap(),
|
||||
version: Version("2.32.3".into()),
|
||||
},
|
||||
];
|
||||
let argv = PipEngine::argv_dry_run(&specs);
|
||||
assert_eq!(
|
||||
&argv[argv.len() - 2..],
|
||||
["httpx==0.28.1", "requests==2.32.3"]
|
||||
);
|
||||
assert!(
|
||||
argv.iter().all(|a| !a.contains(' ')),
|
||||
"no argv entry may bundle multiple arguments"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freeze_uses_all_so_snapshots_include_pip_itself() {
|
||||
assert!(PipEngine::argv_freeze().contains(&"--all".to_string()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
//! The uv adapter: `uv pip … --python <env-python>`.
|
||||
//!
|
||||
//! **This adapter is gated on spike SP-1.** Unlike pip, uv has no stable JSON report for
|
||||
//! `install --dry-run` — it prints a text plan. SP-1 must establish whether that text carries
|
||||
//! enough information to populate [`ResolutionReport::held_back`] blockers; if it does not,
|
||||
//! `docs/ROADMAP.md` says v1.0 ships pip-primary with uv behind a beta-engine flag.
|
||||
//!
|
||||
//! Until SP-1 lands, the parsing entry point below is deliberately unimplemented rather than
|
||||
//! guessed at, and `PD-ENG-003` is the documented outcome when uv emits a shape the adapter does
|
||||
//! not recognize.
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::errors::Result;
|
||||
use crate::model::{
|
||||
CheckReport, Dist, EngineId, EngineInfo, ExecMode, OutdatedDist, PinnedSpec, PkgName, PyEnv,
|
||||
StepResult,
|
||||
};
|
||||
use crate::plan::{PlanRequest, ResolutionReport};
|
||||
|
||||
use super::{Engine, EventSink};
|
||||
|
||||
/// Drives uv as a subprocess.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct UvEngine;
|
||||
|
||||
impl UvEngine {
|
||||
/// argv for `uv pip list --format=json --python <py>`.
|
||||
#[must_use]
|
||||
pub fn argv_list(python: &str) -> Vec<String> {
|
||||
vec![
|
||||
"pip".into(),
|
||||
"list".into(),
|
||||
"--format=json".into(),
|
||||
"--python".into(),
|
||||
python.into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// argv for `uv pip install -U --dry-run --python <py> [specs…]`.
|
||||
#[must_use]
|
||||
pub fn argv_dry_run(python: &str, specs: &[PinnedSpec]) -> Vec<String> {
|
||||
let mut argv = vec![
|
||||
"pip".into(),
|
||||
"install".into(),
|
||||
"-U".into(),
|
||||
"--dry-run".into(),
|
||||
"--python".into(),
|
||||
python.into(),
|
||||
];
|
||||
argv.extend(specs.iter().map(PinnedSpec::to_requirement));
|
||||
argv
|
||||
}
|
||||
|
||||
/// argv for `uv pip freeze --python <py>`. Note uv has no `--all`, so snapshots taken with
|
||||
/// the uv engine omit pip/setuptools — the snapshot metadata records the engine for this
|
||||
/// reason (DATA-FLOW §7).
|
||||
#[must_use]
|
||||
pub fn argv_freeze(python: &str) -> Vec<String> {
|
||||
vec![
|
||||
"pip".into(),
|
||||
"freeze".into(),
|
||||
"--python".into(),
|
||||
python.into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Parse uv's text dry-run plan into the normalized report.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns `PD-ENG-003` when the output does not match any shape the adapter knows.
|
||||
pub fn parse_dry_run(_stdout: &str) -> Result<ResolutionReport> {
|
||||
todo!("SP-1: pin uv's text plan format against captured fixtures before parsing it")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Engine for UvEngine {
|
||||
fn id(&self) -> EngineId {
|
||||
EngineId::Uv
|
||||
}
|
||||
|
||||
async fn info(&self, _env: &PyEnv) -> EngineInfo {
|
||||
todo!("M1: run `uv --version`")
|
||||
}
|
||||
|
||||
async fn list_installed(&self, _env: &PyEnv) -> Result<Vec<Dist>> {
|
||||
todo!("M1: normalize uv's list output into Dist (shape differs slightly from pip)")
|
||||
}
|
||||
|
||||
async fn list_outdated(&self, _env: &PyEnv) -> Result<Vec<OutdatedDist>> {
|
||||
todo!("M1 (SP-1 fixtures): parse uv's outdated output")
|
||||
}
|
||||
|
||||
async fn resolve(&self, _env: &PyEnv, _req: &PlanRequest) -> Result<ResolutionReport> {
|
||||
todo!("SP-1 go/no-go gates this")
|
||||
}
|
||||
|
||||
async fn install(
|
||||
&self,
|
||||
_env: &PyEnv,
|
||||
_specs: &[PinnedSpec],
|
||||
_mode: ExecMode,
|
||||
_sink: EventSink,
|
||||
) -> Result<StepResult> {
|
||||
todo!("M1: two-phase execution per ARCHITECTURE §8")
|
||||
}
|
||||
|
||||
async fn uninstall(
|
||||
&self,
|
||||
_env: &PyEnv,
|
||||
_names: &[PkgName],
|
||||
_sink: EventSink,
|
||||
) -> Result<StepResult> {
|
||||
todo!("M1: `uv pip uninstall`, sequential, skip-and-continue")
|
||||
}
|
||||
|
||||
async fn check(&self, _env: &PyEnv) -> Result<CheckReport> {
|
||||
todo!("M1: normalize `uv pip check` findings")
|
||||
}
|
||||
|
||||
async fn upgrade_pip(&self, _env: &PyEnv) -> Result<StepResult> {
|
||||
// Documented behaviour, not a gap: pip upkeep is a pip-engine concern (DATA-FLOW §7).
|
||||
Err(crate::errors::PdError::new(
|
||||
crate::errors::Code::EngNotFound,
|
||||
"pip upkeep is not available while uv is the active engine",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PY: &str = r"C:\proj\.venv\Scripts\python.exe";
|
||||
|
||||
#[test]
|
||||
fn dry_run_argv_targets_the_selected_interpreter() {
|
||||
let argv = UvEngine::argv_dry_run(PY, &[]);
|
||||
assert_eq!(argv, ["pip", "install", "-U", "--dry-run", "--python", PY]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windows_path_stays_one_argv_entry() {
|
||||
// The path contains backslashes and could contain spaces; because it is its own argv
|
||||
// entry there is nothing to quote or escape (SECURITY §2).
|
||||
let argv = UvEngine::argv_freeze(r"C:\Program Files\Python312\python.exe");
|
||||
assert_eq!(argv.len(), 4);
|
||||
assert_eq!(argv[3], r"C:\Program Files\Python312\python.exe");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upgrade_pip_is_refused_with_a_catalog_code() {
|
||||
let env = PyEnv {
|
||||
interpreter: PY.into(),
|
||||
prefix: r"C:\proj\.venv".into(),
|
||||
python_version: "3.12.4".into(),
|
||||
externally_managed: false,
|
||||
source: crate::model::EnvSource::VenvScan,
|
||||
};
|
||||
let err = UvEngine
|
||||
.upgrade_pip(&env)
|
||||
.await
|
||||
.expect_err("uv cannot upgrade pip");
|
||||
assert_eq!(err.code, crate::errors::Code::EngNotFound);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! 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 (`py -0p`), `uv python list`, known venv directories,
|
||||
//! and manual *Browse…*. Spike SP-6 sweeps all of these on a real machine, including the
|
||||
//! Microsoft Store Python aliasing quirks, before this module is written.
|
||||
|
||||
use crate::errors::Result;
|
||||
use crate::model::PyEnv;
|
||||
|
||||
/// The embedded introspection helper, executed as `<env-python> -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);
|
||||
|
||||
/// Discover every environment on this machine.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a `PD-ENV-*` code when a discovery source fails in a way the user must act on.
|
||||
pub fn scan() -> Result<Vec<PyEnv>> {
|
||||
todo!("M1, after SP-6: PEP 514 registry + py -0p + uv python list + venv scan")
|
||||
}
|
||||
|
||||
#[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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! The error catalog: the single source of truth for every user-visible failure.
|
||||
//!
|
||||
//! Mirrors `docs/ERROR-CATALOG.md` §2. Two rules from that document are structural:
|
||||
//!
|
||||
//! 1. Every user-visible failure carries **exactly one** code.
|
||||
//! 2. Classifiers run over engine stderr in **priority order, first match wins**, falling back to
|
||||
//! [`Code::EngUnclassified`] (`PD-ENG-999`).
|
||||
//!
|
||||
//! Codes and stderr are never localized — only the one-liner and action text are, and those live
|
||||
//! in the i18next catalogs (`docs/I18N.md` §1). The `as_str` values below are the i18next keys'
|
||||
//! discriminators, so they must stay stable once shipped.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Catalog area: the `<AREA>` in `PD-<AREA>-<NNN>`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
pub enum Area {
|
||||
/// Environment discovery, probing, PEP 668.
|
||||
Env,
|
||||
/// Engine availability and output shape.
|
||||
Eng,
|
||||
/// Dependency resolution.
|
||||
Res,
|
||||
/// Build backends and compiled extensions.
|
||||
Bld,
|
||||
/// Package identity and the index.
|
||||
Pkg,
|
||||
/// Network and TLS.
|
||||
Net,
|
||||
/// Filesystem permissions and locks.
|
||||
Prm,
|
||||
/// Snapshots and rollback.
|
||||
Snp,
|
||||
/// Host system limits.
|
||||
Sys,
|
||||
/// Code Health tooling.
|
||||
Hlt,
|
||||
/// PipDock's own bugs.
|
||||
Int,
|
||||
}
|
||||
|
||||
/// Every code PipDock can surface at v1 launch.
|
||||
///
|
||||
/// `docs/TESTING.md` §2 requires at least one captured stderr fixture per variant before ship;
|
||||
/// the test that enforces "no code without fixture" lives beside the classifiers.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub enum Code {
|
||||
// -- PD-ENV: environment ------------------------------------------------
|
||||
/// Interpreter path missing or not executable — the env was deleted or moved.
|
||||
EnvInterpreterMissing,
|
||||
/// PEP 668 `EXTERNALLY-MANAGED` marker present; mutation blocked by default.
|
||||
EnvExternallyManaged,
|
||||
/// `probe.py` exited non-zero or produced unparseable output.
|
||||
EnvProbeFailed,
|
||||
|
||||
// -- PD-ENG: engine -----------------------------------------------------
|
||||
/// pip or uv binary not found.
|
||||
EngNotFound,
|
||||
/// pip older than 22.2, which predates `--dry-run --report`.
|
||||
EngPipTooOld,
|
||||
/// uv emitted a shape the adapter does not recognize (uv newer than PipDock).
|
||||
EngUvShapeUnknown,
|
||||
/// Fallback for engine failures no classifier matched. Always last.
|
||||
EngUnclassified,
|
||||
|
||||
// -- PD-RES: resolution -------------------------------------------------
|
||||
/// `ResolutionImpossible` or the uv equivalent: constraints cannot be satisfied.
|
||||
ResImpossible,
|
||||
/// Plan older than 10 minutes, or the env's probe hash changed since the preview.
|
||||
ResPlanStale,
|
||||
|
||||
// -- PD-BLD: build ------------------------------------------------------
|
||||
/// MSVC build tools required but absent.
|
||||
BldMsvcMissing,
|
||||
/// Build backend failed (`pyproject.toml` error, `metadata-generation-failed`).
|
||||
BldBackendFailed,
|
||||
/// Generic sdist wheel-build failure.
|
||||
BldWheelFailed,
|
||||
|
||||
// -- PD-PKG: package & index -------------------------------------------
|
||||
/// No matching distribution, and metadata shows a requires-python mismatch.
|
||||
PkgRequiresPython,
|
||||
/// No matching distribution: name or version typo, or the release is gone.
|
||||
PkgNotFound,
|
||||
/// The requested release was yanked.
|
||||
PkgYanked,
|
||||
/// Downloaded artifact failed hash verification.
|
||||
PkgHashMismatch,
|
||||
|
||||
// -- PD-NET: network ----------------------------------------------------
|
||||
/// Timeout, connection aborted, or DNS failure.
|
||||
NetUnreachable,
|
||||
/// TLS/SSL verification failed — typically proxy or AV interception.
|
||||
NetTlsFailure,
|
||||
/// PEP 691 index refresh failed; the stale index stays searchable.
|
||||
NetIndexRefreshFailed,
|
||||
/// Code Health tools-venv bootstrap could not reach PyPI.
|
||||
NetToolsBootstrapFailed,
|
||||
|
||||
// -- PD-PRM: permissions ------------------------------------------------
|
||||
/// `PermissionError` writing site-packages (admin-owned Python).
|
||||
PrmSitePackagesReadOnly,
|
||||
/// File locked by a running process (`WinError 32`).
|
||||
PrmFileLocked,
|
||||
|
||||
// -- PD-SNP: snapshot ---------------------------------------------------
|
||||
/// Snapshot write failed before execution. **The plan is aborted; nothing runs.**
|
||||
SnpWriteFailed,
|
||||
/// A release needed to restore a snapshot is no longer available on PyPI.
|
||||
SnpTargetUnavailable,
|
||||
|
||||
// -- PD-SYS: system -----------------------------------------------------
|
||||
/// `MAX_PATH` exceeded without the long-path opt-in.
|
||||
SysPathTooLong,
|
||||
/// Disk full.
|
||||
SysDiskFull,
|
||||
|
||||
// -- PD-HLT: code health ------------------------------------------------
|
||||
/// A Code Health tool is missing from the tools venv.
|
||||
HltToolMissing,
|
||||
/// A Code Health tool exited non-zero.
|
||||
HltToolFailed,
|
||||
/// A Code Health tool exceeded its watchdog timeout; partial report shown.
|
||||
HltTimeout,
|
||||
|
||||
// -- PD-INT: internal ---------------------------------------------------
|
||||
/// A PipDock bug: panic or unexpected state.
|
||||
IntUnexpected,
|
||||
}
|
||||
|
||||
impl Code {
|
||||
/// The wire form, e.g. `"PD-BLD-002"`. Stable once shipped: it appears in logs, in `--json`
|
||||
/// output, and in prefilled bug-report URLs.
|
||||
#[must_use]
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::EnvInterpreterMissing => "PD-ENV-001",
|
||||
Self::EnvExternallyManaged => "PD-ENV-002",
|
||||
Self::EnvProbeFailed => "PD-ENV-003",
|
||||
Self::EngNotFound => "PD-ENG-001",
|
||||
Self::EngPipTooOld => "PD-ENG-002",
|
||||
Self::EngUvShapeUnknown => "PD-ENG-003",
|
||||
Self::EngUnclassified => "PD-ENG-999",
|
||||
Self::ResImpossible => "PD-RES-001",
|
||||
Self::ResPlanStale => "PD-RES-002",
|
||||
Self::BldMsvcMissing => "PD-BLD-001",
|
||||
Self::BldBackendFailed => "PD-BLD-002",
|
||||
Self::BldWheelFailed => "PD-BLD-003",
|
||||
Self::PkgRequiresPython => "PD-PKG-001",
|
||||
Self::PkgNotFound => "PD-PKG-002",
|
||||
Self::PkgYanked => "PD-PKG-003",
|
||||
Self::PkgHashMismatch => "PD-PKG-004",
|
||||
Self::NetUnreachable => "PD-NET-001",
|
||||
Self::NetTlsFailure => "PD-NET-002",
|
||||
Self::NetIndexRefreshFailed => "PD-NET-010",
|
||||
Self::NetToolsBootstrapFailed => "PD-NET-011",
|
||||
Self::PrmSitePackagesReadOnly => "PD-PRM-001",
|
||||
Self::PrmFileLocked => "PD-PRM-002",
|
||||
Self::SnpWriteFailed => "PD-SNP-001",
|
||||
Self::SnpTargetUnavailable => "PD-SNP-002",
|
||||
Self::SysPathTooLong => "PD-SYS-001",
|
||||
Self::SysDiskFull => "PD-SYS-002",
|
||||
Self::HltToolMissing => "PD-HLT-001",
|
||||
Self::HltToolFailed => "PD-HLT-002",
|
||||
Self::HltTimeout => "PD-HLT-003",
|
||||
Self::IntUnexpected => "PD-INT-001",
|
||||
}
|
||||
}
|
||||
|
||||
/// The catalog area this code belongs to.
|
||||
#[must_use]
|
||||
pub const fn area(self) -> Area {
|
||||
match self {
|
||||
Self::EnvInterpreterMissing | Self::EnvExternallyManaged | Self::EnvProbeFailed => {
|
||||
Area::Env
|
||||
}
|
||||
Self::EngNotFound
|
||||
| Self::EngPipTooOld
|
||||
| Self::EngUvShapeUnknown
|
||||
| Self::EngUnclassified => Area::Eng,
|
||||
Self::ResImpossible | Self::ResPlanStale => Area::Res,
|
||||
Self::BldMsvcMissing | Self::BldBackendFailed | Self::BldWheelFailed => Area::Bld,
|
||||
Self::PkgRequiresPython
|
||||
| Self::PkgNotFound
|
||||
| Self::PkgYanked
|
||||
| Self::PkgHashMismatch => Area::Pkg,
|
||||
Self::NetUnreachable
|
||||
| Self::NetTlsFailure
|
||||
| Self::NetIndexRefreshFailed
|
||||
| Self::NetToolsBootstrapFailed => Area::Net,
|
||||
Self::PrmSitePackagesReadOnly | Self::PrmFileLocked => Area::Prm,
|
||||
Self::SnpWriteFailed | Self::SnpTargetUnavailable => Area::Snp,
|
||||
Self::SysPathTooLong | Self::SysDiskFull => Area::Sys,
|
||||
Self::HltToolMissing | Self::HltToolFailed | Self::HltTimeout => Area::Hlt,
|
||||
Self::IntUnexpected => Area::Int,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every code, in catalog order. The fixture-coverage test in `docs/TESTING.md` §2 iterates
|
||||
/// this, so a new variant fails CI until it has a captured stderr fixture.
|
||||
pub const ALL: &'static [Self] = &[
|
||||
Self::EnvInterpreterMissing,
|
||||
Self::EnvExternallyManaged,
|
||||
Self::EnvProbeFailed,
|
||||
Self::EngNotFound,
|
||||
Self::EngPipTooOld,
|
||||
Self::EngUvShapeUnknown,
|
||||
Self::ResImpossible,
|
||||
Self::ResPlanStale,
|
||||
Self::BldMsvcMissing,
|
||||
Self::BldBackendFailed,
|
||||
Self::BldWheelFailed,
|
||||
Self::PkgRequiresPython,
|
||||
Self::PkgNotFound,
|
||||
Self::PkgYanked,
|
||||
Self::PkgHashMismatch,
|
||||
Self::NetUnreachable,
|
||||
Self::NetTlsFailure,
|
||||
Self::NetIndexRefreshFailed,
|
||||
Self::NetToolsBootstrapFailed,
|
||||
Self::PrmSitePackagesReadOnly,
|
||||
Self::PrmFileLocked,
|
||||
Self::SnpWriteFailed,
|
||||
Self::SnpTargetUnavailable,
|
||||
Self::SysPathTooLong,
|
||||
Self::SysDiskFull,
|
||||
Self::HltToolMissing,
|
||||
Self::HltToolFailed,
|
||||
Self::HltTimeout,
|
||||
Self::IntUnexpected,
|
||||
Self::EngUnclassified,
|
||||
];
|
||||
}
|
||||
|
||||
impl fmt::Display for Code {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify an engine's stderr into a catalog code.
|
||||
///
|
||||
/// Filled during spike SP-2, which captures real stderr for each case. Until then this returns
|
||||
/// the documented fallback so no call site can accidentally surface an uncoded failure.
|
||||
///
|
||||
/// Contract when implemented: patterns are checked in priority order and the **first** match wins.
|
||||
#[must_use]
|
||||
pub fn classify_stderr(_stderr: &str) -> Code {
|
||||
Code::EngUnclassified
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
fn every_variant_is_listed_in_all() {
|
||||
// `ALL` drives the fixture-coverage gate, so a variant missing from it would silently
|
||||
// escape that gate. There is no derive for "enumerate variants", hence this count check.
|
||||
assert_eq!(Code::ALL.len(), 30, "add the new variant to Code::ALL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_codes_are_unique() {
|
||||
let seen: HashSet<&str> = Code::ALL.iter().map(|c| c.as_str()).collect();
|
||||
assert_eq!(
|
||||
seen.len(),
|
||||
Code::ALL.len(),
|
||||
"duplicate wire code in catalog"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_codes_match_the_documented_grammar() {
|
||||
for code in Code::ALL {
|
||||
let s = code.as_str();
|
||||
let mut parts = s.split('-');
|
||||
assert_eq!(parts.next(), Some("PD"), "{s} must start with PD");
|
||||
let area = parts.next().unwrap_or_default();
|
||||
let num = parts.next().unwrap_or_default();
|
||||
assert_eq!(parts.next(), None, "{s} has too many segments");
|
||||
assert_eq!(area.len(), 3, "{s} area must be 3 letters");
|
||||
assert!(
|
||||
area.chars().all(|c| c.is_ascii_uppercase()),
|
||||
"{s} area case"
|
||||
);
|
||||
assert_eq!(num.len(), 3, "{s} number must be 3 digits");
|
||||
assert!(num.chars().all(|c| c.is_ascii_digit()), "{s} number digits");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unclassified_is_the_documented_fallback() {
|
||||
assert_eq!(
|
||||
classify_stderr("something nobody has seen before"),
|
||||
Code::EngUnclassified
|
||||
);
|
||||
assert_eq!(Code::EngUnclassified.as_str(), "PD-ENG-999");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Error types. See `docs/ERROR-CATALOG.md`.
|
||||
|
||||
pub mod catalog;
|
||||
|
||||
pub use catalog::{Area, Code, classify_stderr};
|
||||
|
||||
/// The error type crossing every boundary: Tauri IPC, CLI output, logs.
|
||||
///
|
||||
/// Invariant 4 of `docs/DATA-FLOW.md` §9: every failure surfaced to UI or CLI carries a catalog
|
||||
/// code. That is why `code` is not optional.
|
||||
#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)]
|
||||
#[error("error[{code}]: {message}")]
|
||||
pub struct PdError {
|
||||
/// The single catalog code for this failure.
|
||||
pub code: Code,
|
||||
/// Developer-facing detail. **Not** the user-facing string — per `docs/I18N.md` §1 the core
|
||||
/// emits codes and structured data only; the localized one-liner is looked up frontend-side
|
||||
/// from the code.
|
||||
pub message: String,
|
||||
/// Tail of the engine's stderr, capped at the 40 lines `docs/ERROR-CATALOG.md` §3 shows.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub stderr_tail: Option<String>,
|
||||
}
|
||||
|
||||
impl PdError {
|
||||
/// Build an error for `code` with developer-facing detail.
|
||||
#[must_use]
|
||||
pub fn new(code: Code, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message: message.into(),
|
||||
stderr_tail: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach an engine stderr tail, truncated to the last `MAX_STDERR_TAIL_LINES` lines.
|
||||
#[must_use]
|
||||
pub fn with_stderr(mut self, stderr: impl AsRef<str>) -> Self {
|
||||
let stderr = stderr.as_ref();
|
||||
let tail: Vec<&str> = stderr
|
||||
.lines()
|
||||
.rev()
|
||||
.take(MAX_STDERR_TAIL_LINES)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
.rev()
|
||||
.collect();
|
||||
self.stderr_tail = Some(tail.join("\n"));
|
||||
self
|
||||
}
|
||||
|
||||
/// Classify an engine failure from its stderr (SP-2 fills the classifier table).
|
||||
#[must_use]
|
||||
pub fn from_engine_stderr(stderr: impl AsRef<str>) -> Self {
|
||||
let stderr = stderr.as_ref();
|
||||
Self::new(classify_stderr(stderr), "engine command failed").with_stderr(stderr)
|
||||
}
|
||||
}
|
||||
|
||||
/// `docs/ERROR-CATALOG.md` §3: the GUI's *Details* pane shows at most this many stderr lines.
|
||||
pub const MAX_STDERR_TAIL_LINES: usize = 40;
|
||||
|
||||
/// Convenience alias for core results.
|
||||
pub type Result<T> = std::result::Result<T, PdError>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stderr_tail_keeps_the_last_lines_in_order() {
|
||||
let stderr = (1..=60)
|
||||
.map(|n| n.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let err = PdError::new(Code::BldBackendFailed, "boom").with_stderr(&stderr);
|
||||
let tail = err.stderr_tail.unwrap_or_default();
|
||||
let lines: Vec<&str> = tail.lines().collect();
|
||||
|
||||
assert_eq!(lines.len(), MAX_STDERR_TAIL_LINES);
|
||||
assert_eq!(
|
||||
lines.first(),
|
||||
Some(&"21"),
|
||||
"should start 40 lines from the end"
|
||||
);
|
||||
assert_eq!(
|
||||
lines.last(),
|
||||
Some(&"60"),
|
||||
"should keep the newest line last"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_stderr_is_kept_whole() {
|
||||
let err = PdError::new(Code::BldBackendFailed, "boom").with_stderr("a\nb");
|
||||
assert_eq!(err.stderr_tail.as_deref(), Some("a\nb"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_leads_with_the_code() {
|
||||
let err = PdError::new(Code::SnpWriteFailed, "disk full");
|
||||
assert_eq!(err.to_string(), "error[PD-SNP-001]: disk full");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! The reverse-dependency graph, built from `probe.py`'s `requires_dist` data.
|
||||
//!
|
||||
//! Three features read it (ARCHITECTURE §4): held-back blocker attribution, the uninstall guard,
|
||||
//! and pin auto-suggest. `docs/TESTING.md` §1 lists its correctness as something that must never
|
||||
//! regress, including cycles and `pkg[extra]` markers.
|
||||
|
||||
use crate::model::{Dist, PkgName};
|
||||
|
||||
/// Who depends on what, keyed by the depended-upon package.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ReverseDeps;
|
||||
|
||||
impl ReverseDeps {
|
||||
/// Build the graph from a full environment listing.
|
||||
#[must_use]
|
||||
pub fn build(_dists: &[Dist]) -> Self {
|
||||
todo!("M1: parse requires_dist, honour extras and environment markers")
|
||||
}
|
||||
|
||||
/// Packages that would break if `pkg` were removed.
|
||||
///
|
||||
/// This is the uninstall guard's whole job: bare `pip uninstall` performs no dependency check
|
||||
/// at all (DATA-FLOW §5).
|
||||
#[must_use]
|
||||
pub fn dependents_of(&self, _pkg: &PkgName) -> Vec<PkgName> {
|
||||
todo!("M1: reverse lookup")
|
||||
}
|
||||
}
|
||||
|
||||
/// PRD P1-2: default reverse-dependency count at which a pin is suggested. Configurable.
|
||||
pub const PIN_SUGGEST_THRESHOLD: usize = 5;
|
||||
@@ -0,0 +1,25 @@
|
||||
//! Code Health: deptry, vulture and ruff run from PipDock's own isolated tools venv.
|
||||
//!
|
||||
//! See `docs/CODE-HEALTH-SPEC.md`. Two boundaries are contractual (§1, §7): deptry and vulture are
|
||||
//! **report-only**, and the sole write path is `ruff --fix` / `ruff format` behind an explicit
|
||||
//! confirm. PipDock never edits `pyproject.toml` or `requirements.txt` for the user.
|
||||
|
||||
use crate::errors::Result;
|
||||
|
||||
/// CODE-HEALTH-SPEC §4: per-tool watchdog; exceeding it yields a partial report (`PD-HLT-003`).
|
||||
pub const TOOL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
|
||||
|
||||
/// CODE-HEALTH-SPEC §4: vulture's default confidence floor.
|
||||
pub const DEFAULT_MIN_CONFIDENCE: u8 = 80;
|
||||
|
||||
/// CODE-HEALTH-SPEC §4: directories excluded from every tool, plus user globs from Settings.
|
||||
pub const DEFAULT_EXCLUDES: &[&str] = &[".venv", "venv", "node_modules", "build", "dist", ".git"];
|
||||
|
||||
/// Create or re-sync the tools venv from the shipped `tools-requirements.txt`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns `PD-NET-011` when bootstrap cannot reach PyPI; Health stays disabled and every other
|
||||
/// tab is unaffected (CODE-HEALTH-SPEC §2).
|
||||
pub fn sync_tools_venv() -> Result<()> {
|
||||
todo!(r"M3: create %LOCALAPPDATA%\PipDock\tools\.venv from exact pins")
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//! PyPI name index and metadata cache. See ARCHITECTURE §5.
|
||||
//!
|
||||
//! The PEP 691 JSON Simple Index is ingested into SQLite (`index.db`, table `names`), and fuzzy
|
||||
//! search runs in Rust over the normalized column. Spike SP-3 measures whether the documented
|
||||
//! budgets hold on ~600 k project names before this module is written.
|
||||
|
||||
use crate::errors::Result;
|
||||
use crate::model::PkgName;
|
||||
|
||||
/// UI-SPEC §4 and PRD §6: keystroke-to-results budget for the local index.
|
||||
pub const SEARCH_LATENCY_BUDGET: std::time::Duration = std::time::Duration::from_millis(50);
|
||||
|
||||
/// ROADMAP SP-3: cold refresh of the full name index must finish inside this.
|
||||
pub const COLD_REFRESH_BUDGET: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// ARCHITECTURE §5: the name index is refreshed manually or on this cadence.
|
||||
pub const INDEX_REFRESH_INTERVAL_DAYS: u32 = 7;
|
||||
|
||||
/// ARCHITECTURE §5: per-package PyPI JSON metadata is cached this long.
|
||||
pub const METADATA_TTL_HOURS: u32 = 24;
|
||||
|
||||
/// Fuzzy-search the cached name index.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns `PD-NET-010` when the index has never been populated.
|
||||
pub fn search(_query: &str, _limit: usize) -> Result<Vec<PkgName>> {
|
||||
todo!("M1, after SP-3: nucleo matcher over the normalized names column")
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! PipDock's domain logic — **this crate is the product**.
|
||||
//!
|
||||
//! The Tauri GUI (`src-tauri`) and the clap CLI (`pipdock-cli`) are thin adapters over these
|
||||
//! functions; neither contains business logic (ARCHITECTURE §1.1). Read `docs/ARCHITECTURE.md`
|
||||
//! before changing anything here.
|
||||
//!
|
||||
//! # Invariants this crate enforces
|
||||
//!
|
||||
//! From `docs/DATA-FLOW.md` §9, tested rather than assumed:
|
||||
//!
|
||||
//! 1. No mutating engine call without a [`plan::ResolutionReport`] accepted in this session.
|
||||
//! 2. No mutating engine call without a successful snapshot write.
|
||||
//! 3. `plan_execute` refuses a report older than [`plan::PLAN_MAX_AGE`], or one whose environment
|
||||
//! probe hash has changed.
|
||||
//! 4. Every failure surfaced to the UI or CLI carries an [`errors::Code`].
|
||||
//! 5. Pinned packages never enter `PlanRequest::upgrades` unless explicitly unpinned this session.
|
||||
//!
|
||||
//! # Status
|
||||
//!
|
||||
//! Phase 0. Types and command surfaces are defined; behaviour lands in M1, gated on the spikes in
|
||||
//! `docs/ROADMAP.md`. In particular [`engine::uv`] is gated on SP-1, which decides whether v1.0
|
||||
//! ships both engines.
|
||||
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub mod engine;
|
||||
pub mod envs;
|
||||
pub mod errors;
|
||||
pub mod graph;
|
||||
pub mod health;
|
||||
pub mod index;
|
||||
pub mod model;
|
||||
pub mod pins;
|
||||
pub mod plan;
|
||||
pub mod snapshot;
|
||||
|
||||
pub use errors::{Code, PdError, Result};
|
||||
pub use model::{Dist, EngineId, OutdatedDist, PkgName, PyEnv, Version};
|
||||
|
||||
/// The application data directory under `%LOCALAPPDATA%` (ARCHITECTURE §6).
|
||||
pub const APP_DATA_DIR_NAME: &str = "PipDock";
|
||||
|
||||
/// Log retention in `%LOCALAPPDATA%\PipDock\logs\` (ARCHITECTURE §6).
|
||||
pub const LOG_RETENTION_DAYS: u32 = 14;
|
||||
|
||||
/// Size of the per-plan engine output ring buffer that backs *Report bug*
|
||||
/// (`docs/ERROR-CATALOG.md` §4).
|
||||
pub const LOG_RING_BUFFER_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// `docs/ERROR-CATALOG.md` §4.3: GitHub rejects very long URLs, so the prefilled `log-excerpt`
|
||||
/// is truncated (tail-biased) to this many characters. The full log goes to the clipboard.
|
||||
pub const BUG_REPORT_EXCERPT_CHARS: usize = 6_000;
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Core domain types shared by every module, the CLI and the GUI.
|
||||
//!
|
||||
//! These are the types `specta`/`tauri-specta` will export to TypeScript (ARCHITECTURE §9), so
|
||||
//! their serde representation is part of the public contract — see `docs/CLI-SPEC.md` §6.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::errors::{Code, PdError, Result};
|
||||
|
||||
/// Which resolver PipDock is driving.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum EngineId {
|
||||
/// `<python> -m pip …`
|
||||
Pip,
|
||||
/// `uv pip … --python <python>`
|
||||
Uv,
|
||||
}
|
||||
|
||||
impl EngineId {
|
||||
/// Wire form, also what the status-line engine badge shows (UI-SPEC §3).
|
||||
#[must_use]
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Pip => "pip",
|
||||
Self::Uv => "uv",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Availability and version of an engine for a given environment.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EngineInfo {
|
||||
/// Which engine this describes.
|
||||
pub id: EngineId,
|
||||
/// Reported version, absent when the engine is not available.
|
||||
pub version: Option<String>,
|
||||
/// False means the binary or module could not be found (`PD-ENG-001`).
|
||||
pub available: bool,
|
||||
}
|
||||
|
||||
/// How an environment was discovered. Surfaced as the source chip in the Environments screen.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum EnvSource {
|
||||
/// PEP 514 registry entry.
|
||||
Registry,
|
||||
/// Reported by the `py` launcher (`py -0p`).
|
||||
PyLauncher,
|
||||
/// Reported by `uv python list`.
|
||||
Uv,
|
||||
/// Found by scanning known venv directories.
|
||||
VenvScan,
|
||||
/// Added by the user via *Browse…*.
|
||||
Manual,
|
||||
}
|
||||
|
||||
/// A Python environment PipDock can act on.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PyEnv {
|
||||
/// Canonicalized path to the interpreter. Never a shell string — see SECURITY §2.
|
||||
pub interpreter: PathBuf,
|
||||
/// `sys.prefix` as reported by `probe.py`.
|
||||
pub prefix: PathBuf,
|
||||
/// e.g. `"3.12.4"`.
|
||||
pub python_version: String,
|
||||
/// PEP 668 marker present. When true, mutation is blocked unless the user enabled the
|
||||
/// Settings override (`PD-ENV-002`, SECURITY §3).
|
||||
pub externally_managed: bool,
|
||||
/// Where this env came from.
|
||||
pub source: EnvSource,
|
||||
}
|
||||
|
||||
/// A PEP 503-normalized distribution name.
|
||||
///
|
||||
/// Constructing one is the *only* way a package name reaches an argv array, which is what makes
|
||||
/// SECURITY §2's "validated before it reaches argv" claim structural rather than aspirational.
|
||||
#[derive(
|
||||
Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
|
||||
)]
|
||||
#[serde(transparent)]
|
||||
pub struct PkgName(String);
|
||||
|
||||
impl PkgName {
|
||||
/// Validate and normalize a distribution name.
|
||||
///
|
||||
/// Accepts the PEP 508 name grammar — `^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$` — then
|
||||
/// applies PEP 503 normalization: lowercase, and runs of `-`, `_` or `.` collapse to a single
|
||||
/// `-`. Anything else is rejected with `PD-PKG-002`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns `PD-PKG-002` when `raw` is not a valid distribution name.
|
||||
pub fn parse(raw: &str) -> Result<Self> {
|
||||
let invalid = || PdError::new(Code::PkgNotFound, format!("invalid package name: {raw:?}"));
|
||||
|
||||
if raw.is_empty() {
|
||||
return Err(invalid());
|
||||
}
|
||||
let bytes = raw.as_bytes();
|
||||
let alnum = |b: u8| b.is_ascii_alphanumeric();
|
||||
// First and last characters must be alphanumeric; the middle may also use . _ -
|
||||
if !alnum(bytes[0]) || !alnum(bytes[bytes.len() - 1]) {
|
||||
return Err(invalid());
|
||||
}
|
||||
if !bytes
|
||||
.iter()
|
||||
.all(|&b| alnum(b) || matches!(b, b'.' | b'_' | b'-'))
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
|
||||
// PEP 503 normalization.
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
let mut prev_was_separator = false;
|
||||
for ch in raw.chars() {
|
||||
if matches!(ch, '.' | '_' | '-') {
|
||||
if !prev_was_separator {
|
||||
out.push('-');
|
||||
}
|
||||
prev_was_separator = true;
|
||||
} else {
|
||||
out.push(ch.to_ascii_lowercase());
|
||||
prev_was_separator = false;
|
||||
}
|
||||
}
|
||||
Ok(Self(out))
|
||||
}
|
||||
|
||||
/// The normalized name.
|
||||
#[must_use]
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PkgName {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A version string as the engine reported it. Never reshaped or localized (I18N §2).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Version(pub String);
|
||||
|
||||
impl std::fmt::Display for Version {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the user asked for: a name, optionally constrained.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Spec {
|
||||
/// Normalized distribution name.
|
||||
pub name: PkgName,
|
||||
/// PEP 440 specifier such as `">=2,<3"`, or `None` for "latest".
|
||||
pub version_req: Option<String>,
|
||||
}
|
||||
|
||||
/// A resolved, exact `name==version` pair. Only these reach a mutating engine command.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PinnedSpec {
|
||||
/// Normalized distribution name.
|
||||
pub name: PkgName,
|
||||
/// The exact version the resolver chose.
|
||||
pub version: Version,
|
||||
}
|
||||
|
||||
impl PinnedSpec {
|
||||
/// Render as the `name==version` argv token.
|
||||
#[must_use]
|
||||
pub fn to_requirement(&self) -> String {
|
||||
format!("{}=={}", self.name, self.version)
|
||||
}
|
||||
}
|
||||
|
||||
/// An installed distribution, as read by `probe.py` or `<engine> list`.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Dist {
|
||||
/// Normalized distribution name.
|
||||
pub name: PkgName,
|
||||
/// Installed version.
|
||||
pub version: Version,
|
||||
/// Raw `Requires-Dist` entries. The reverse-dependency graph is built from these.
|
||||
#[serde(default)]
|
||||
pub requires_dist: Vec<String>,
|
||||
/// Raw `Requires-Python` specifier, when declared.
|
||||
#[serde(default)]
|
||||
pub requires_python: Option<String>,
|
||||
}
|
||||
|
||||
/// An installed distribution with a newer release available.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct OutdatedDist {
|
||||
/// Normalized distribution name.
|
||||
pub name: PkgName,
|
||||
/// Currently installed version.
|
||||
pub current: Version,
|
||||
/// Newest version the index offers.
|
||||
pub latest: Version,
|
||||
}
|
||||
|
||||
/// Which of the two execution phases produced a result (ARCHITECTURE §8).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ExecMode {
|
||||
/// Phase A: one engine invocation for the whole pinned set.
|
||||
Batch,
|
||||
/// Phase B: per-package sequential retry after Phase A failed. Skip-and-continue.
|
||||
Isolated,
|
||||
}
|
||||
|
||||
/// Outcome of a single package's step.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum StepStatus {
|
||||
/// Applied successfully.
|
||||
Ok,
|
||||
/// Failed; carries a catalog code. Does **not** abort the batch.
|
||||
Failed,
|
||||
/// Not attempted — user cancelled, or dropped by a Skip decision.
|
||||
Skipped,
|
||||
}
|
||||
|
||||
/// One row of the summary report (DATA-FLOW §6).
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct StepResult {
|
||||
/// Normalized distribution name.
|
||||
pub pkg: PkgName,
|
||||
/// Version before the step, absent for a fresh install.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub from: Option<Version>,
|
||||
/// Version the step targeted.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub to: Option<Version>,
|
||||
/// Whether it applied.
|
||||
pub status: StepStatus,
|
||||
/// Catalog code, present exactly when `status` is `Failed`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub code: Option<Code>,
|
||||
/// Tail of the engine's stderr for the failure detail pane.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub stderr_tail: Option<String>,
|
||||
}
|
||||
|
||||
/// One unsatisfied requirement reported by `pip check` / `uv pip check`.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct CheckFinding {
|
||||
/// The distribution whose requirement is unsatisfied.
|
||||
pub pkg: PkgName,
|
||||
/// Human-readable requirement text as the engine printed it.
|
||||
pub requirement: String,
|
||||
}
|
||||
|
||||
/// Post-execution environment verification.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct CheckReport {
|
||||
/// True when the engine reported no broken requirements.
|
||||
pub ok: bool,
|
||||
/// Details when `ok` is false.
|
||||
#[serde(default)]
|
||||
pub findings: Vec<CheckFinding>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn normalizes_per_pep_503() {
|
||||
let cases = [
|
||||
("Requests", "requests"),
|
||||
("zope.interface", "zope-interface"),
|
||||
("typing_extensions", "typing-extensions"),
|
||||
("ruamel.yaml.clib", "ruamel-yaml-clib"),
|
||||
// Runs of mixed separators collapse to a single dash.
|
||||
("foo._-.bar", "foo-bar"),
|
||||
("A", "a"),
|
||||
];
|
||||
for (raw, want) in cases {
|
||||
let got = PkgName::parse(raw).unwrap_or_else(|e| panic!("{raw:?} rejected: {e}"));
|
||||
assert_eq!(got.as_str(), want, "normalizing {raw:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_names_outside_the_pep_508_grammar() {
|
||||
// Every one of these would be a way to smuggle something past argv validation.
|
||||
let bad = [
|
||||
"",
|
||||
"-leading",
|
||||
"trailing-",
|
||||
".dotstart",
|
||||
"has space",
|
||||
"semi;colon",
|
||||
"amp&and",
|
||||
"pipe|d",
|
||||
"quote\"d",
|
||||
"new\nline",
|
||||
"back\\slash",
|
||||
"sla/sh",
|
||||
"--upgrade",
|
||||
"requests>=2",
|
||||
"naïve",
|
||||
];
|
||||
for raw in bad {
|
||||
assert!(PkgName::parse(raw).is_err(), "{raw:?} should be rejected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_names_use_the_documented_code() {
|
||||
let err = PkgName::parse("--upgrade").expect_err("flag-like name must be rejected");
|
||||
assert_eq!(err.code, Code::PkgNotFound);
|
||||
assert_eq!(err.code.as_str(), "PD-PKG-002");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinned_spec_renders_the_argv_token() {
|
||||
let spec = PinnedSpec {
|
||||
name: PkgName::parse("Typing_Extensions").unwrap_or_else(|_| unreachable!()),
|
||||
version: Version("4.12.2".into()),
|
||||
};
|
||||
assert_eq!(spec.to_requirement(), "typing-extensions==4.12.2");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Per-environment pins. See PRD P0-7.
|
||||
//!
|
||||
//! DATA-FLOW §9.5: pinned packages never appear in a `PlanRequest.upgrades` unless the user
|
||||
//! explicitly unpinned them in the same session. *Select all* excludes them and says how many
|
||||
//! were excluded (UI-SPEC §4).
|
||||
|
||||
use crate::errors::Result;
|
||||
use crate::model::PkgName;
|
||||
|
||||
/// A pin with the reason the user gave for it.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Pin {
|
||||
/// The pinned package.
|
||||
pub pkg: PkgName,
|
||||
/// Free-text justification shown in the Pins screen.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// Pins for one environment, keyed by its `env_hash`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a `PD-INT-*` code when the pin store cannot be read.
|
||||
pub fn list(_env_hash: &str) -> Result<Vec<Pin>> {
|
||||
todo!("M1: read the pins table from index.db")
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
//! Planning: `PlanRequest` → `ResolutionReport` → `ExecutionSummary`.
|
||||
//!
|
||||
//! See `docs/DATA-FLOW.md` §3 for the state machine and §9 for the invariants this module owns.
|
||||
|
||||
use crate::model::{CheckReport, ExecMode, PinnedSpec, PkgName, Spec, StepResult, Version};
|
||||
|
||||
/// How aggressively to resolve conflicts.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Strategy {
|
||||
/// Accept whatever the resolver can satisfy. The safe default; `[C]ompatible` in the CLI.
|
||||
Compatible,
|
||||
/// Force the latest version of the listed packages even though it violates another
|
||||
/// package's requirement. The UI must name what breaks before this is selectable
|
||||
/// (UI-SPEC §4, DISCLAIMER §2).
|
||||
ForceLatest {
|
||||
/// Only these packages are forced; everything else stays `Compatible`.
|
||||
overrides: Vec<PkgName>,
|
||||
},
|
||||
}
|
||||
|
||||
/// The user's intent, before the engine has said anything about it.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PlanRequest {
|
||||
/// Already-installed packages the user selected for upgrade.
|
||||
#[serde(default)]
|
||||
pub upgrades: Vec<PkgName>,
|
||||
/// New packages queued in the dock bay.
|
||||
#[serde(default)]
|
||||
pub installs: Vec<Spec>,
|
||||
/// Conflict-handling strategy.
|
||||
pub strategy: Strategy,
|
||||
}
|
||||
|
||||
/// Which section of the preview a change belongs to (UI-SPEC §4).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum ChangeKind {
|
||||
/// An installed package moving to a newer version.
|
||||
Upgrade,
|
||||
/// A package pulled in to satisfy something else.
|
||||
NewDependency,
|
||||
/// A package the user explicitly asked to install.
|
||||
NewInstall,
|
||||
/// A package moving to an older version to satisfy a constraint.
|
||||
Downgrade,
|
||||
}
|
||||
|
||||
/// One line of the preview diff.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Change {
|
||||
/// Normalized distribution name.
|
||||
pub name: PkgName,
|
||||
/// Version before, absent for a fresh install.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub from: Option<Version>,
|
||||
/// Version the resolver chose.
|
||||
pub to: Version,
|
||||
/// Which preview section this belongs in.
|
||||
pub kind: ChangeKind,
|
||||
}
|
||||
|
||||
/// The package responsible for holding another one back.
|
||||
///
|
||||
/// ARCHITECTURE §3: the engine's report says *what* was held back; *who* is responsible comes from
|
||||
/// cross-referencing the reverse-dependency graph with each blocker's `Requires-Dist` constraint.
|
||||
/// **If attribution is ambiguous, show the constraint without a culprit rather than guessing.**
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Blocker {
|
||||
/// The package imposing the constraint, absent when attribution is ambiguous.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub by: Option<PkgName>,
|
||||
/// The constraint text, e.g. `"requests<2.31"`.
|
||||
pub constraint: String,
|
||||
}
|
||||
|
||||
/// A package the resolver could not take all the way to `latest`.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HeldBack {
|
||||
/// Normalized distribution name.
|
||||
pub pkg: PkgName,
|
||||
/// The version the resolver settled on.
|
||||
pub resolved: Version,
|
||||
/// The version the index offers.
|
||||
pub latest: Version,
|
||||
/// Why it could not go further. Empty means the engine gave no attributable reason.
|
||||
#[serde(default)]
|
||||
pub blockers: Vec<Blocker>,
|
||||
}
|
||||
|
||||
/// A `ResolutionImpossible` outcome and whatever detail the engine gave (`PD-RES-001`).
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ImpossibleDetail {
|
||||
/// Packages involved in the unsatisfiable set.
|
||||
#[serde(default)]
|
||||
pub packages: Vec<PkgName>,
|
||||
/// The engine's own explanation, verbatim.
|
||||
pub explanation: String,
|
||||
}
|
||||
|
||||
/// The normalized dry-run result.
|
||||
///
|
||||
/// **Both adapters must emit this same shape** — that is the whole point of the `Engine` trait
|
||||
/// (ARCHITECTURE §3). The pip adapter fills it from `--dry-run --report` JSON; the uv adapter from
|
||||
/// uv's text plan output.
|
||||
///
|
||||
/// The exact field set is **provisional until spike SP-1** confirms uv's output is rich enough to
|
||||
/// populate `held_back.blockers`. If it is not, SP-1's go/no-go says v1.0 ships pip-primary with uv
|
||||
/// behind a beta flag.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ResolutionReport {
|
||||
/// Everything that would change if the user confirms.
|
||||
#[serde(default)]
|
||||
pub changes: Vec<Change>,
|
||||
/// Packages that could not reach `latest`, with attribution.
|
||||
#[serde(default)]
|
||||
pub held_back: Vec<HeldBack>,
|
||||
/// Present when the whole resolution failed.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub impossible: Option<ImpossibleDetail>,
|
||||
/// The engine's untouched output, kept for the log and for bug reports.
|
||||
pub raw: String,
|
||||
}
|
||||
|
||||
impl ResolutionReport {
|
||||
/// True when the preview has nothing for the user to decide, so the UI can go straight to the
|
||||
/// confirm step (part of the 4-click budget in UI-SPEC §5).
|
||||
#[must_use]
|
||||
pub fn is_clean(&self) -> bool {
|
||||
self.held_back.is_empty() && self.impossible.is_none()
|
||||
}
|
||||
|
||||
/// The pinned set a confirmed plan would execute.
|
||||
#[must_use]
|
||||
pub fn pinned_set(&self) -> Vec<PinnedSpec> {
|
||||
self.changes
|
||||
.iter()
|
||||
.map(|c| PinnedSpec {
|
||||
name: c.name.clone(),
|
||||
version: c.to.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggregate counts rendered as "13 successful, 2 failed, 1 skipped" (DATA-FLOW §6).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Counts {
|
||||
/// Steps that applied.
|
||||
pub ok: usize,
|
||||
/// Steps that failed, each with a catalog code.
|
||||
pub failed: usize,
|
||||
/// Steps not attempted.
|
||||
pub skipped: usize,
|
||||
}
|
||||
|
||||
/// The end-of-run report shown in the summary sheet and emitted by `--json`.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ExecutionSummary {
|
||||
/// Correlates the summary with its snapshot and log ring buffer.
|
||||
pub plan_id: String,
|
||||
/// Which phase produced these results.
|
||||
pub phase: ExecMode,
|
||||
/// One row per package.
|
||||
#[serde(default)]
|
||||
pub results: Vec<StepResult>,
|
||||
/// Post-run `engine.check()`.
|
||||
pub check: CheckReport,
|
||||
/// Derived from `results`; see [`ExecutionSummary::tally`].
|
||||
pub counts: Counts,
|
||||
}
|
||||
|
||||
impl ExecutionSummary {
|
||||
/// Recompute `counts` from `results`.
|
||||
///
|
||||
/// The counts drive the user-visible headline, so they are derived rather than accumulated by
|
||||
/// hand — a mismatch between the rows and the headline is exactly the kind of bug
|
||||
/// `docs/TESTING.md` §1.4 says must never regress.
|
||||
#[must_use]
|
||||
pub fn tally(results: &[StepResult]) -> Counts {
|
||||
use crate::model::StepStatus;
|
||||
let mut counts = Counts::default();
|
||||
for r in results {
|
||||
match r.status {
|
||||
StepStatus::Ok => counts.ok += 1,
|
||||
StepStatus::Failed => counts.failed += 1,
|
||||
StepStatus::Skipped => counts.skipped += 1,
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
}
|
||||
|
||||
/// DATA-FLOW §9.3: a report older than this is refused by `plan_execute` and must be re-resolved.
|
||||
pub const PLAN_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(10 * 60);
|
||||
|
||||
/// DATA-FLOW §3: after this many conflict-decision rounds the UI requires manual pruning, which
|
||||
/// prevents decision ping-pong.
|
||||
pub const MAX_CONFLICT_ROUNDS: u8 = 3;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::StepStatus;
|
||||
|
||||
fn step(pkg: &str, status: StepStatus) -> StepResult {
|
||||
StepResult {
|
||||
pkg: PkgName::parse(pkg).unwrap(),
|
||||
from: None,
|
||||
to: None,
|
||||
status,
|
||||
code: None,
|
||||
stderr_tail: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tally_matches_the_documented_headline() {
|
||||
// The example from DATA-FLOW §6: "13 successful, 2 failed, 1 skipped".
|
||||
let mut results: Vec<StepResult> = (0..13)
|
||||
.map(|i| step(&format!("ok{i}"), StepStatus::Ok))
|
||||
.collect();
|
||||
results.extend((0..2).map(|i| step(&format!("bad{i}"), StepStatus::Failed)));
|
||||
results.push(step("skipped0", StepStatus::Skipped));
|
||||
|
||||
assert_eq!(
|
||||
ExecutionSummary::tally(&results),
|
||||
Counts {
|
||||
ok: 13,
|
||||
failed: 2,
|
||||
skipped: 1
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_run_tallies_to_zero() {
|
||||
assert_eq!(ExecutionSummary::tally(&[]), Counts::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_with_held_back_items_is_not_clean() {
|
||||
let held = HeldBack {
|
||||
pkg: PkgName::parse("requests").unwrap(),
|
||||
resolved: Version("2.30.0".into()),
|
||||
latest: Version("2.32.3".into()),
|
||||
blockers: vec![Blocker {
|
||||
by: Some(PkgName::parse("apiclient").unwrap()),
|
||||
constraint: "requests<2.31".into(),
|
||||
}],
|
||||
};
|
||||
let report = ResolutionReport {
|
||||
changes: vec![],
|
||||
held_back: vec![held],
|
||||
impossible: None,
|
||||
raw: String::new(),
|
||||
};
|
||||
assert!(!report.is_clean());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinned_set_mirrors_the_changes() {
|
||||
let report = ResolutionReport {
|
||||
changes: vec![Change {
|
||||
name: PkgName::parse("httpx").unwrap(),
|
||||
from: Some(Version("0.27.0".into())),
|
||||
to: Version("0.28.1".into()),
|
||||
kind: ChangeKind::Upgrade,
|
||||
}],
|
||||
held_back: vec![],
|
||||
impossible: None,
|
||||
raw: String::new(),
|
||||
};
|
||||
assert!(report.is_clean());
|
||||
let pinned = report.pinned_set();
|
||||
assert_eq!(pinned.len(), 1);
|
||||
assert_eq!(pinned[0].to_requirement(), "httpx==0.28.1");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
"""PipDock environment probe.
|
||||
|
||||
Prints a single JSON document describing the interpreter it runs under and every
|
||||
distribution installed in it. Rust cannot cheaply read a foreign environment's
|
||||
metadata, so this helper is executed as:
|
||||
|
||||
<env-python> -I <tempfile> --json
|
||||
|
||||
Constraints (docs/ARCHITECTURE.md section 4, docs/SECURITY.md section 2):
|
||||
|
||||
* Standard library only. No third-party imports, ever -- the environments this
|
||||
runs in are the user's, and may contain anything.
|
||||
* Python 3.10 floor: `importlib.metadata` only, no `packaging`.
|
||||
* Run with -I so PYTHONPATH and user site are ignored and a poisoned environment
|
||||
cannot inject code into the probe.
|
||||
* Written to a temp file with a random name per invocation; never installed.
|
||||
|
||||
Output shape:
|
||||
|
||||
{"python": "3.12.4", "prefix": "...", "externally_managed": false,
|
||||
"dists": [{"name": "requests", "version": "2.32.3",
|
||||
"requires_dist": ["urllib3<3,>=1.21.1"],
|
||||
"requires_python": ">=3.8"}]}
|
||||
|
||||
Any failure prints {"error": ...} on stdout and exits non-zero, which the core
|
||||
classifies as PD-ENV-003.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import sysconfig
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
def _normalize(name: str) -> str:
|
||||
"""PEP 503 normalization, mirrored in model.rs so both sides agree on identity."""
|
||||
out: list[str] = []
|
||||
prev_sep = False
|
||||
for ch in name:
|
||||
if ch in "-_.":
|
||||
if not prev_sep:
|
||||
out.append("-")
|
||||
prev_sep = True
|
||||
else:
|
||||
out.append(ch.lower())
|
||||
prev_sep = False
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _externally_managed() -> bool:
|
||||
"""Detect the PEP 668 marker.
|
||||
|
||||
The marker sits next to the stdlib in the `stdlib` scheme path. Its mere
|
||||
presence is what pip keys off, so PipDock does the same -- contents are not
|
||||
parsed. Drives PD-ENV-002.
|
||||
"""
|
||||
candidates = []
|
||||
for key in ("stdlib", "platstdlib"):
|
||||
try:
|
||||
path = sysconfig.get_path(key)
|
||||
except (KeyError, OSError):
|
||||
continue
|
||||
if path:
|
||||
candidates.append(os.path.join(path, "EXTERNALLY-MANAGED"))
|
||||
return any(os.path.isfile(p) for p in candidates)
|
||||
|
||||
|
||||
def _dists() -> list[dict[str, object]]:
|
||||
"""Read installed distribution metadata.
|
||||
|
||||
A single unreadable distribution must not fail the whole probe -- broken
|
||||
metadata in one package is common and the user still needs the rest of the
|
||||
list. Such entries are reported with an `error` field instead.
|
||||
"""
|
||||
from importlib.metadata import distributions
|
||||
|
||||
out: list[dict[str, object]] = []
|
||||
for dist in distributions():
|
||||
try:
|
||||
meta = dist.metadata
|
||||
if meta is None:
|
||||
continue
|
||||
# Use .get(), not subscripting: on Python 3.14 a missing header returns None with a
|
||||
# DeprecationWarning ("Implicit None on return values is deprecated") and is slated to
|
||||
# raise KeyError. The warning goes to stderr and would otherwise pollute every probe
|
||||
# run against a 3.14 environment.
|
||||
raw_name = meta.get("Name")
|
||||
if not raw_name:
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"name": _normalize(raw_name),
|
||||
"version": dist.version or "",
|
||||
"requires_dist": list(dist.requires or []),
|
||||
"requires_python": meta.get("Requires-Python"),
|
||||
}
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - one bad dist must not sink the probe
|
||||
out.append({"name": None, "error": f"{type(exc).__name__}: {exc}"})
|
||||
|
||||
out.sort(key=lambda d: (d.get("name") or ""))
|
||||
return out
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="PipDock environment probe")
|
||||
parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
help="emit JSON (the only supported mode; accepted for explicitness)",
|
||||
)
|
||||
parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
payload = {
|
||||
"schema": SCHEMA_VERSION,
|
||||
"python": ".".join(str(p) for p in sys.version_info[:3]),
|
||||
"implementation": sys.implementation.name,
|
||||
"prefix": sys.prefix,
|
||||
"base_prefix": sys.base_prefix,
|
||||
"executable": sys.executable,
|
||||
"is_venv": sys.prefix != sys.base_prefix,
|
||||
"externally_managed": _externally_managed(),
|
||||
"dists": _dists(),
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001 - the core turns this into PD-ENV-003
|
||||
json.dump({"error": f"{type(exc).__name__}: {exc}"}, sys.stdout)
|
||||
sys.stdout.write("\n")
|
||||
return 1
|
||||
|
||||
json.dump(payload, sys.stdout, ensure_ascii=False)
|
||||
sys.stdout.write("\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Freeze snapshots, diffs and minimal-ops rollback. See DATA-FLOW §8.
|
||||
//!
|
||||
//! DATA-FLOW §9.2 is absolute: no mutating engine call happens without a successful snapshot
|
||||
//! write. A failed write aborts the plan and executes nothing (`PD-SNP-001`).
|
||||
|
||||
use crate::errors::Result;
|
||||
|
||||
/// A captured environment state: a freeze file plus its metadata sidecar.
|
||||
#[derive(Debug)]
|
||||
pub struct Snapshot;
|
||||
|
||||
/// Write a snapshot for `env_hash` before a batch runs.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns `PD-SNP-001` on any write failure. **Callers must abort the plan on error** — this is
|
||||
/// the one failure mode that is not skip-and-continue.
|
||||
pub fn create(_env_hash: &str) -> Result<Snapshot> {
|
||||
todo!("M1: engine freeze + .meta.json (trigger, engine, package count, app version)")
|
||||
}
|
||||
|
||||
/// Snapshot retention: `%LOCALAPPDATA%\PipDock\snapshots\<envhash>\<iso-ts>.freeze.txt`
|
||||
/// alongside `.meta.json` (ARCHITECTURE §6).
|
||||
pub const SNAPSHOT_DIR: &str = "snapshots";
|
||||
@@ -129,5 +129,6 @@ Zustand stores: `useEnvStore`, `usePlanStore`, `useIndexStore`, `useSettingsStor
|
||||
| uv engine | latest stable (0.9.x line at writing); minimum pinned after SP-1 |
|
||||
| Managed Pythons | 3.10 – 3.14 (3.9 is EOL) |
|
||||
| Windows | 10 (1809+) / 11; WebView2 Evergreen assumed present; `longPathAware` manifest enabled |
|
||||
| rusqlite | **held at 0.37** (`libsqlite3-sys` 0.35). 0.40 pulls `libsqlite3-sys` 0.38.1, whose build script uses the unstable `cfg_select!` and therefore does not compile on stable Rust 1.94.1. Revisit when the toolchain advances. |
|
||||
|
||||
Dependabot + `cargo audit` + `npm audit` in CI keep this table honest (RELEASE-CI.md §2).
|
||||
@@ -0,0 +1,5 @@
|
||||
[toolchain]
|
||||
channel = "1.94.1"
|
||||
components = ["rustfmt", "clippy"]
|
||||
targets = ["x86_64-pc-windows-msvc"]
|
||||
profile = "minimal"
|
||||
@@ -0,0 +1,58 @@
|
||||
# Phase 0 spikes
|
||||
|
||||
`docs/ROADMAP.md` Phase 0: **before any feature code**, because the architecture rests on
|
||||
assumptions that have to be checked on a real machine. Each spike is a small script here plus
|
||||
fixtures committed to `crates/pipdock-core/tests/fixtures/`, and its answer is recorded below.
|
||||
|
||||
| Spike | Question | Status |
|
||||
|---|---|---|
|
||||
| SP-1 | Exact shape of `uv pip install -U --dry-run`; is held-back attribution derivable? | not started — **blocked on installing uv** |
|
||||
| SP-2 | `pip --dry-run --report` JSON + real stderr for every catalog code | not started |
|
||||
| SP-3 | PEP 691 index size, SQLite ingest time, fuzzy-search latency over ~600 k names | not started |
|
||||
| SP-4 | pip-audit invocation for a foreign environment | not started |
|
||||
| SP-5 | Held-back attribution accuracy on a real numpy/scipy/pandas tangle | not started |
|
||||
| SP-6 | Windows env discovery sweep (PEP 514, `py -0p`, Store Python, uv-managed) | one finding recorded below |
|
||||
|
||||
SP-1 is a **go/no-go**: if uv's plan output is too lossy to populate
|
||||
`ResolutionReport::held_back[].blockers`, v1.0 ships pip-primary with uv behind a beta-engine flag.
|
||||
|
||||
## Findings
|
||||
|
||||
### SP-6 — `probe.py -I` hides user-site packages (measured 2026-07-27)
|
||||
|
||||
`docs/SECURITY.md` §2 specifies running the probe with `-I` (isolated mode) so a poisoned
|
||||
environment cannot inject code into it. Isolated mode also disables **user site-packages**, and on
|
||||
a system Python that is where most packages actually live.
|
||||
|
||||
Measured against `C:\Python314` on the dev machine:
|
||||
|
||||
| View | Distributions |
|
||||
|---|---|
|
||||
| `probe.py` with `-I` | 352 |
|
||||
| `probe.py` without `-I` | 376 |
|
||||
| `pip list` | 375 |
|
||||
|
||||
So `-I` hides **24 packages** that pip itself reports, and PipDock's Installed tab would disagree
|
||||
with `pip list` by that much. The remaining 376 vs 375 gap is a second, smaller question — likely a
|
||||
shadowed distribution that `importlib.metadata` reports twice and pip de-duplicates by normalized
|
||||
name.
|
||||
|
||||
This does not affect the primary target: a venv has no user site, so all three numbers agree. It
|
||||
affects **non-venv system Pythons that are not PEP 668-marked** — `C:\Python314` reports
|
||||
`externally_managed: false`, so nothing blocks PipDock from managing it.
|
||||
|
||||
**Open decision for SP-6** (do not resolve unilaterally — it trades a documented security control
|
||||
against list accuracy):
|
||||
|
||||
- keep `-I` and show a "user-site packages not shown" note on non-venv environments; or
|
||||
- drop to `-E` (ignore `PYTHONPATH` only, keep user site), accepting that a package in user site
|
||||
can influence the probe's imports; or
|
||||
- run the probe twice and reconcile, at the cost of a second interpreter start per scan.
|
||||
|
||||
### SP-6 — Python 3.14 metadata deprecation (fixed 2026-07-27)
|
||||
|
||||
Subscripting `dist.metadata["Requires-Python"]` for an absent header emits
|
||||
`DeprecationWarning: Implicit None on return values is deprecated and will raise KeyErrors` on
|
||||
Python 3.14, on **stderr**, for many distributions. `probe.py` now uses `.get()`. Worth keeping in
|
||||
mind generally: the probe must stay clean on stderr, because the core treats probe noise as
|
||||
`PD-ENV-003`.
|
||||
Reference in new issue
Block a user