From a58b9bb74b6654ab55769c2d0f0106af9ddfde7e Mon Sep 17 00:00:00 2001 From: HMythical Date: Thu, 12 Nov 2026 23:15:13 -0800 Subject: [PATCH] (fix) Addressed failed installations with rollbacks If any package installation were to fail via 'draft', 'substitute' and/or 'update' commands, B.A.L.L.E.R rolls back to the last version you installed. An additional command is provided for you to manually roll back packages when installations from source fail unexpectedly. New installs and/or installs before this change are unaffected for the first time. --- CHANGELOG.md | 3 + docs/architecture.md | 17 +- docs/commands.md | 18 +- docs/error-handling.md | 24 +- src/commands/draft.rs | 96 +++++--- src/commands/mod.rs | 1 + src/commands/rollback.rs | 430 ++++++++++++++++++++++++++++++++ src/commands/substitute.rs | 179 ++++++++------ src/commands/update.rs | 238 ++++++++++-------- tests/rollback.rs | 488 +++++++++++++++++++++++++++++++++++++ 10 files changed, 1285 insertions(+), 209 deletions(-) create mode 100644 src/commands/rollback.rs create mode 100644 tests/rollback.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 73852a0..d8f610c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ with a custom scheme: ### Fixed +- **A failed `draft`, `substitute` or `update` rolls back what it already installed (closes #59)** + All three install a plan as separate persisted steps — extract, link, record — and none undid them on a failure: `draft`'s `session_packages` was "for rollback" but only fed the `--json` `installed` list, `substitute`'s `new_installed` was honoured only when removing the old package's roster row failed (and then only for the root), and `update` tracked nothing and deleted the old release's extract dir before the new one was linked. A failure partway through — a download, a missing binary, a vetoing pre-hook — left the earlier packages linked and on the roster. The new `src/commands/rollback.rs` adds a `Session` each command notes every step in (`begin` before a package's first change, then `downloaded`/`linked`/`recorded`); on an error the command unwinds it newest first, then returns the original error. A package new to the run is unlinked, removed from the roster and purged from the cache (`Downloader::purge_download`). A package the run found already installed is restored rather than removed: `begin` snapshots its roster row and `package_dependencies` rows, and rollback writes them back (via `InstalledPackage::to_package` and `insert_package`, so only `installed_at` is reset) and points its link at its old binary again — without that, a failed `draft --force`, a failed `substitute` (which re-fetches dependencies the user already has, since `resolve_deps_with_root` returns them) and a failed `update` would each have uninstalled working packages. `draft`'s and `substitute`'s loops move into `install_plan` and `install_replacement`, and `update`'s steps from the first new dependency to recording the new release into `install_update`. `update` now prunes the old extract dir only after the new release is linked and recorded, so rolling back never needs files it deleted. `substitute` also rolls back when the old package cannot be unlinked or removed, and puts the old package's link back if its roster row could not be deleted, which the old partial rollback left removed. Behaviour changes: a failed run prints `Rolled back undid this run's changes to ` as a warning (hidden by `-q`/`--json`; details at `--verbose`); `draft --json`'s `installed` lists the packages recorded this run, as before. Not undone: what a system package manager, `cargo install` or a hook did — a warning says when a system or cargo package stays installed with only its roster entry removed. Post-hooks still never fail a command, so they cannot trigger a rollback; Referee Phase A still runs before every install loop. Unit tests in `rollback.rs` cover removal, restore (row, `user_installed`, dependency rows), the same-version reinstall that keeps its tree, and ordering; new `tests/rollback.rs` drives the binary against a mock registry for each command's failure paths and both success paths. The six failure cases fail against the previous code. `tests/rollback.rs` reads which version a package is exposed as from the binary itself, so it covers Windows' copied `.exe` the same way as a Unix symlink, and honours `BALLER_TEST_BIN` like `json_output.rs`. Verified on Windows 11 (PowerShell 5.1, execution policy `Restricted`): all 8 end-to-end cases, the 5 unit tests and the full lib, bin and `json_output` suites pass. Under Wine the 6 non-hook cases pass and the 2 hook-veto cases fail only because Wine's `powershell` is a stub that exits 0. Documented in `docs/commands.md`, `docs/error-handling.md` and `docs/architecture.md`, which already described rollback for `draft` and `substitute` that did not exist. + - **The build scripts run cargo in the repository, wherever they are called from** `build.sh` and `build.ps1` ran a bare `cargo` in the caller's working directory, and cargo finds its project by walking up from there, not from the script. Called from outside the repo, every command failed with ``could not find `Cargo.toml` ``; called from inside *another* Cargo project, they built, tested and linted that project instead — and `clean` deleted that project's `target/` and reported success, leaving baller's own untouched. Every cargo invocation now runs from the repository root (`run_cargo` in `build.sh`, `Invoke-Cargo` in `build.ps1`), so the scripts behave the same from any directory. `build.sh`'s `run_build` no longer assembles its command as a string for `eval`; it passes `CARGO_FLAGS` to cargo as an array. Documented in `CONTRIBUTING.md` (Development Setup). diff --git a/docs/architecture.md b/docs/architecture.md index df20322..c99c6b6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,6 +20,7 @@ baller/ │ │ ├── freeze.rs # Pin/unpin packages │ │ ├── substitute.rs # Swap packages │ │ ├── update.rs # Update non-frozen packages +│ │ ├── rollback.rs # Undo a failed draft/substitute/update │ │ ├── sweep.rs # Clean cache │ │ ├── referee/ # referee group: audit, check, scan, cache, config, sbom │ │ └── build.rs # Assemble a package from a local manifest @@ -298,9 +299,19 @@ The modules live in `src/security/` and are mapped in ## Error Handling and Rollback ### Partial Failure Rollback -Commands that install multiple packages (`draft`, `substitute`) track packages -installed during the current session. If any package fails to install, all -packages from the session are rolled back (symlink removed, DB entry deleted). +`draft`, `substitute` and `update` install a plan as separate persisted steps +(extract, link, record) with no transaction around them, so each notes every +step in a `commands::rollback::Session` as it goes. On a failure the session is +unwound newest package first, then the original error is returned. A package +new to the run is unlinked, taken off the roster and purged from the cache +(extract dir and archive). A package the run found already installed — a +`draft --force` reinstall, a dependency `substitute` re-fetched, `update`'s +root — gets its snapshotted roster row and dependency rows written back and +its link pointed at its old binary again. `update` prunes the old release's +extract dir only after the new one is linked and recorded, so that binary is +always still there to go back to. Rollback is best-effort (a step that cannot +be undone is logged at `--verbose`) and runs no hooks; what a system package +manager or `cargo install` did is not undone. ### Orphan Dependency Cleanup When ejecting a package, BALLER checks for orphaned dependencies — packages diff --git a/docs/commands.md b/docs/commands.md index a9148f0..4591287 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -105,6 +105,12 @@ instead of reporting a plan that cannot work — see [error-handling.md](error-handling.md#github-source-asset-errors). `-v` logs the chosen asset's file name alongside the URL. +If any step of the install fails partway through the plan — a download, a +missing binary, a `pre_install` hook vetoing a later package — the packages +this run already installed are rolled back before the error is reported, and a +package `--force` reinstalled goes back to the version it was at. See +[error-handling.md](error-handling.md#rollback-on-partial-failure). + ### Installation Modes The `draft` command follows one of four code paths depending on the package @@ -338,6 +344,12 @@ If the replacement extracts without an executable, the substitution fails with `NoBinaryFound` **before** the old package is ejected, so a broken replacement cannot cost you a working package. +Any failure before the old package is off the roster rolls the whole +replacement back: packages it installed fresh are removed, and dependencies you +already had (which `substitute` re-fetches) go back to the version they were +at. If the old package's roster entry cannot be removed, its link is put back +too, so it comes out of a failed substitution exactly as it went in. + **Example:** ``` $ baller substitute ripgrep hound @@ -420,7 +432,11 @@ not just strict semver. Falls back to string comparison when both versions cannot be parsed. New dependencies introduced by the updated version are automatically installed. -Old extracted cache directories are cleaned before the new version is installed. +The old version's extracted cache directory is pruned only once the new version +is linked and recorded. If anything fails before that — a new dependency, the +`pre_update` hook, the new download — the new dependencies are rolled back and +the old version keeps its link, roster entry and files, and `update` stops with +the error. Both `BALLER_OLD_VERSION` and `BALLER_NEW_VERSION` environment variables are available in pre-update and post-update hooks. diff --git a/docs/error-handling.md b/docs/error-handling.md index 4180b0d..9d0b95c 100644 --- a/docs/error-handling.md +++ b/docs/error-handling.md @@ -288,13 +288,23 @@ See [referee.md](referee.md). ## Rollback on Partial Failure -When `draft` or `substitute` installs multiple packages and one fails mid-way, -all packages installed during the current session are cleaned up: -- Symlinks are removed -- Database entries are deleted -- The original error is returned after cleanup - -This ensures the system is never left in a partially-installed state. +When `draft`, `substitute` or `update` fails partway through its plan, every +package the run already changed is put back, newest first, before the original +error is returned: +- A package the run installed fresh is unlinked, removed from the roster, and + its extract dir and cached archive are deleted. +- A package that was already installed (a `draft --force` reinstall, a + dependency `substitute` re-fetched, the package `update` was upgrading) gets + its previous roster row, dependency rows and link back. Its `installed_at` + is the one thing reset, to the time of the rollback. + +A warning names the packages rolled back (`Rolled back undid this run's changes +to …`). Cleanup is best-effort: a step that cannot be undone is logged at +`--verbose` and never replaces the original error. Rollback does not run hooks, +and does not uninstall what a system package manager or `cargo install` put on +the system — a warning says when such a package stays installed with only its +roster entry removed. Post-hooks still never fail a command, so a failing +`post_install` or `post_update` hook does not trigger a rollback. ## Confirmation Prompts diff --git a/src/commands/draft.rs b/src/commands/draft.rs index 632c50e..902345a 100644 --- a/src/commands/draft.rs +++ b/src/commands/draft.rs @@ -1,7 +1,9 @@ use colored::Colorize; use serde_json::json; +use std::collections::HashMap; use std::path::Path; +use crate::commands::rollback::Session; use crate::context::{effective_source_order, AppContext}; use crate::core::dep_solver::{get_installed_map, resolve_deps_with_root}; use crate::core::downloader::DownloadedPackage; @@ -81,8 +83,9 @@ pub fn execute_draft( // Every package this draft would install — the root and each dependency // the chain resolved — must be able to run on this host. Gated before the - // dry-run report and before the install loop, which has no rollback, so a - // mismatch deep in the graph cannot leave earlier packages installed. + // dry-run report and before the install loop, so a mismatch deep in the + // graph is reported as a plan that cannot work rather than as a failure + // the loop has to roll back. for candidate in &result_packages { if !installed.contains_key(&candidate.name) || opts.force { ensure_installable(candidate)?; @@ -99,10 +102,11 @@ pub fn execute_draft( } // Referee Phase A: the whole plan is checked before any of it is - // installed. The loop below has no rollback — `session_packages` is - // tracked for reporting, not for undoing — so blocking here is the only - // place a block can be atomic. It also runs before the PreInstall hook, so - // a package Referee rejected never gets to run code of its own. + // installed. The loop below rolls back its own links and roster rows on a + // failure, but not what a system package manager, cargo or a hook already + // did, so blocking here is the only place a block is fully atomic. It also + // runs before the PreInstall hook, so a package Referee rejected never + // gets to run code of its own. let gate = ctx.referee.gate(&ctx.db, &result_packages)?; gate.report(quiet); @@ -114,11 +118,56 @@ pub fn execute_draft( return Err(blocked); } - // D1: Track packages installed in this session for rollback - let mut session_packages: Vec = Vec::new(); + // Every step the loop takes is noted in `session`, so a failure partway + // through the plan unwinds the packages already installed instead of + // leaving a partial set behind (#59). + let mut session = Session::default(); let mut skipped: Vec = Vec::new(); - for pkg_to_install in &result_packages { + if let Err(e) = install_plan( + ctx, + &pkg, + &result_packages, + opts, + &mut installed, + &mut session, + &mut skipped, + ) { + session.rollback(ctx); + return Err(e); + } + + if ctx.flags.json { + return print_json(&json!({ + "command": "draft", + "package": pkg.name, + "version": pkg.version, + "source": source_label(&pkg.source), + "installed": session.installed(), + "skipped": skipped, + "referee": gate.to_json(), + })); + } + + Ok(()) +} + +/// Install each package of the plan in order, noting every step in `session`. +/// +/// Returns at the first failure without undoing anything; the caller rolls +/// the session back. +fn install_plan( + ctx: &AppContext, + root: &Package, + plan: &[Package], + opts: &DraftOptions, + installed: &mut HashMap, + session: &mut Session, + skipped: &mut Vec, +) -> Result<(), BallError> { + let quiet = ctx.flags.is_quiet(); + + for pkg_to_install in plan { if installed.contains_key(&pkg_to_install.name) && !opts.force { tracing::info!( "{} {} already installed", @@ -139,16 +188,18 @@ pub fn execute_draft( &[], )?; + session.begin(&ctx.db, pkg_to_install)?; + // System packages are installed via the native package manager, // not downloaded/archived. Record them in the DB and continue. if let PackageSource::System { manager } = &pkg_to_install.source { tracing::info!("{} installing via {}...", "System".green(), manager.cyan()); install_system_package(manager, &pkg_to_install.name)?; - let is_root = pkg_to_install.name == pkg.name; + let is_root = pkg_to_install.name == root.name; ctx.db .insert_package(pkg_to_install, "", None, None, is_root)?; - session_packages.push(pkg_to_install.name.clone()); + session.recorded(); installed.insert(pkg_to_install.name.clone(), pkg_to_install.version.clone()); run_hook( @@ -180,10 +231,10 @@ pub fn execute_draft( ); install_cargo_package(crate_name)?; - let is_root = pkg_to_install.name == pkg.name; + let is_root = pkg_to_install.name == root.name; ctx.db .insert_package(pkg_to_install, "", None, None, is_root)?; - session_packages.push(pkg_to_install.name.clone()); + session.recorded(); installed.insert(pkg_to_install.name.clone(), pkg_to_install.version.clone()); run_hook( @@ -218,6 +269,7 @@ pub fn execute_draft( let downloaded = ctx .downloader .download_and_extract(pkg_to_install, !quiet)?; + session.downloaded(&downloaded); tracing::debug!( "{}: extracted to {} (binary: {})", @@ -246,6 +298,7 @@ pub fn execute_draft( let bin_path_str = Some(binary_path.to_string_lossy().to_string()); ActiveManager::create_symlink(&binary_path, &pkg_to_install.name)?; + session.linked(); tracing::info!( "{} symlinked to {}", "Linked".green(), @@ -253,7 +306,7 @@ pub fn execute_draft( ); // Pass user_installed=true for root packages, false for deps - let is_root = pkg_to_install.name == pkg.name; + let is_root = pkg_to_install.name == root.name; ctx.db.insert_package( pkg_to_install, &install_path, @@ -261,8 +314,7 @@ pub fn execute_draft( None, is_root, )?; - - session_packages.push(pkg_to_install.name.clone()); + session.recorded(); // D3: Update the installed map so subsequent packages see this one installed.insert(pkg_to_install.name.clone(), pkg_to_install.version.clone()); @@ -289,18 +341,6 @@ pub fn execute_draft( ); } - if ctx.flags.json { - return print_json(&json!({ - "command": "draft", - "package": pkg.name, - "version": pkg.version, - "source": source_label(&pkg.source), - "installed": session_packages, - "skipped": skipped, - "referee": gate.to_json(), - })); - } - Ok(()) } diff --git a/src/commands/mod.rs b/src/commands/mod.rs index e4de108..685272f 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -5,6 +5,7 @@ pub mod external; pub mod freeze; pub mod inject; pub mod referee; +pub(crate) mod rollback; pub mod roster; pub mod substitute; pub mod sweep; diff --git a/src/commands/rollback.rs b/src/commands/rollback.rs new file mode 100644 index 0000000..ac33b0c --- /dev/null +++ b/src/commands/rollback.rs @@ -0,0 +1,430 @@ +//! Undoing a partly applied install (#59). +//! +//! `draft`, `substitute` and `update` apply a plan as a sequence of separate, +//! persisted steps — extract, link, record — with no transaction around them. +//! A [`Session`] notes each step as it is taken, so a failure partway through +//! can unwind everything the run did, newest first, before the original error +//! is returned. +//! +//! A package the run found already installed is restored, never removed: a +//! `draft --force` reinstall, a dependency `substitute` re-fetched and the root +//! of an `update` were all working before the run touched them. Its roster row +//! and dependency rows go back as they were and its link points at its old +//! binary again; only a package new to this run is unlinked, taken off the +//! roster and purged from the cache. +//! +//! Rollback is best-effort: a step that cannot be undone is logged at +//! `--verbose` and the unwind carries on, so a cleanup failure never masks the +//! error that caused it. What baller did not do itself — a system package +//! manager's or `cargo install`'s work, or whatever a hook ran — is not undone. + +use std::path::Path; + +use colored::Colorize; + +use crate::context::AppContext; +use crate::core::db::{DbManager, InstalledPackage}; +use crate::core::downloader::{DownloadedPackage, Downloader}; +use crate::core::package::{Package, PackageSource}; +use crate::error::error::BallError; +use crate::platform::common::PlatformManager; + +#[cfg(target_os = "linux")] +use crate::platform::linux::LinuxManager as ActiveManager; + +#[cfg(target_os = "windows")] +use crate::platform::windows::WindowsManager as ActiveManager; + +/// The packages one run has changed, and how far it got with each. +#[derive(Default)] +pub(crate) struct Session { + entries: Vec, +} + +/// Everything the run has done to one package so far. +struct Entry { + package: Package, + /// Its roster state before this run, if it was already installed. + previous: Option, + downloaded: Option, + linked: bool, + recorded: bool, +} + +/// A roster row as it stood before the run overwrote it. +struct Previous { + row: InstalledPackage, + /// `(name, version)` rows from `package_dependencies`, which an insert + /// rewrites along with the package row. + dependencies: Vec<(String, String)>, +} + +impl Session { + /// Start tracking `pkg`, before the first step that changes anything for it. + /// + /// Snapshots its roster row so rollback can put back a package that was + /// already installed. A roster that cannot be read is an error: without + /// the snapshot, rollback could not tell a reinstall from a fresh install + /// and would remove a package the user already had. + pub(crate) fn begin(&mut self, db: &DbManager, pkg: &Package) -> Result<(), BallError> { + let previous = match db.get_package(&pkg.name) { + Ok(row) => Some(Previous { + dependencies: db.get_dependencies(&pkg.name)?, + row, + }), + Err(BallError::PackageNotFound(_)) => None, + Err(e) => return Err(e), + }; + + self.entries.push(Entry { + package: pkg.clone(), + previous, + downloaded: None, + linked: false, + recorded: false, + }); + Ok(()) + } + + /// The current package's archive was fetched and extracted. + pub(crate) fn downloaded(&mut self, downloaded: &DownloadedPackage) { + if let Some(entry) = self.entries.last_mut() { + entry.downloaded = Some(downloaded.clone()); + } + } + + /// The current package's binary was linked into the install directory. + pub(crate) fn linked(&mut self) { + if let Some(entry) = self.entries.last_mut() { + entry.linked = true; + } + } + + /// The current package was written to the roster. + pub(crate) fn recorded(&mut self) { + if let Some(entry) = self.entries.last_mut() { + entry.recorded = true; + } + } + + /// The packages this run put on the roster, in install order. + pub(crate) fn installed(&self) -> Vec { + self.entries + .iter() + .filter(|entry| entry.recorded) + .map(|entry| entry.package.name.clone()) + .collect() + } + + /// Undo every step this run took, newest package first. + pub(crate) fn rollback(&self, ctx: &AppContext) { + self.unwind(&ctx.db, &ctx.downloader); + } + + fn unwind(&self, db: &DbManager, downloader: &Downloader) { + let touched: Vec<&Entry> = self + .entries + .iter() + .rev() + .filter(|entry| entry.downloaded.is_some() || entry.linked || entry.recorded) + .collect(); + + if touched.is_empty() { + return; + } + + for entry in &touched { + entry.undo(db, downloader); + } + + tracing::warn!( + "{} undid this run's changes to {}", + "Rolled back".yellow(), + touched + .iter() + .rev() + .map(|entry| entry.package.name.as_str()) + .collect::>() + .join(", ") + ); + } +} + +impl Entry { + fn undo(&self, db: &DbManager, downloader: &Downloader) { + let name = &self.package.name; + tracing::debug!( + "rolling back {} v{} ({})", + name, + self.package.version, + if self.previous.is_some() { + "restoring the previous install" + } else { + "removing it" + } + ); + + // The link first: it is what the user runs, and the binary it is put + // back to lives in the previous install's tree, which this run never + // deletes. + if self.linked { + let previous_bin = self + .previous + .as_ref() + .and_then(|previous| previous.row.bin_path.as_deref()); + let result = match previous_bin { + Some(bin) => ActiveManager::create_symlink(Path::new(bin), name), + None => ActiveManager::remove_symlink(name), + }; + if let Err(e) = result { + tracing::debug!("{}: could not restore its link: {}", name, e); + } + } + + if self.recorded { + let result = match &self.previous { + Some(previous) => previous.restore(db), + None => match db.remove_package(name) { + Err(BallError::PackageNotFound(_)) => Ok(()), + other => other, + }, + }; + if let Err(e) = result { + tracing::debug!("{}: could not restore its roster entry: {}", name, e); + } + + if self.previous.is_none() { + if let Some(tool) = native_installer(&self.package.source) { + tracing::warn!( + "{} {} was installed by {} and stays installed; baller only removed its roster entry", + "Note".yellow(), + name.cyan(), + tool.cyan() + ); + } + } + } + + if let Some(downloaded) = &self.downloaded { + // A same-version reinstall extracted over the very tree the + // restored row points at, so that tree is the install and stays. + let in_use = self.previous.as_ref().is_some_and(|previous| { + Path::new(&previous.row.install_path) == downloaded.extract_dir + }); + if !in_use { + downloader.purge_download(&self.package, downloaded); + } + } + } +} + +impl Previous { + /// Write the roster row and its dependency rows back as they were. + /// + /// `installed_at` is the one column that does not survive: the upsert + /// stamps it with the time of the restore. + fn restore(&self, db: &DbManager) -> Result<(), BallError> { + let mut pkg = self.row.to_package(); + // `insert_package` rewrites the dependency rows from this list, in the + // `name>=version` form it parses. + pkg.dependencies = Some( + self.dependencies + .iter() + .map(|(dep, version)| format!("{}>={}", dep, version)) + .collect(), + ); + db.insert_package( + &pkg, + &self.row.install_path, + self.row.bin_path.as_deref(), + self.row.manifest_path.as_deref(), + self.row.user_installed, + ) + } +} + +/// The tool that installed a package outside baller's cache, if any +fn native_installer(source: &PackageSource) -> Option { + match source { + PackageSource::System { manager } => Some(manager.clone()), + PackageSource::Cargo { .. } => Some("cargo".to_string()), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::http::HttpClient; + use std::fs; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + /// A directory no other test shares, with a database and a cache in it + fn scratch(tag: &str) -> (PathBuf, DbManager, Downloader) { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir() + .join("baller_rollback_tests") + .join(format!( + "{}_{}_{}", + std::process::id(), + tag, + COUNTER.fetch_add(1, Ordering::SeqCst) + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("cache")).unwrap(); + let db = DbManager::init_at_path(&dir.join("baller.db")).unwrap(); + let downloader = Downloader::new(dir.join("cache"), HttpClient::new().unwrap()); + (dir, db, downloader) + } + + fn package(name: &str, version: &str, deps: &[&str]) -> Package { + let mut pkg = Package::new(name, version); + pkg.download_url = Some(format!("https://example.test/{}-{}.tar.gz", name, version)); + pkg.dependencies = Some(deps.iter().map(|dep| dep.to_string()).collect()); + pkg + } + + /// Lay down `pkg`'s cached archive and extract dir, as a download would + fn fake_download(dir: &Path, pkg: &Package) -> DownloadedPackage { + let cache = dir.join("cache"); + let extract_dir = cache.join(format!("{}-{}", pkg.name, pkg.version)); + fs::create_dir_all(&extract_dir).unwrap(); + fs::write(extract_dir.join(&pkg.name), "#!/bin/sh\n").unwrap(); + let archive_path = cache.join(crate::utils::fs::sanitize_filename( + pkg.download_url.as_deref().unwrap(), + )); + fs::write(&archive_path, "archive").unwrap(); + DownloadedPackage { + archive_path, + binary_path: Some(extract_dir.join(&pkg.name)), + extract_dir, + } + } + + fn record(db: &DbManager, pkg: &Package, downloaded: &DownloadedPackage, root: bool) { + db.insert_package( + pkg, + &downloaded.extract_dir.to_string_lossy(), + Some(&downloaded.binary_path.as_ref().unwrap().to_string_lossy()), + None, + root, + ) + .unwrap(); + } + + #[test] + fn test_a_fresh_package_is_removed_and_purged() { + let (dir, db, downloader) = scratch("fresh"); + let pkg = package("fresh", "1.0.0", &[]); + + let mut session = Session::default(); + session.begin(&db, &pkg).unwrap(); + let downloaded = fake_download(&dir, &pkg); + session.downloaded(&downloaded); + record(&db, &pkg, &downloaded, true); + session.recorded(); + + session.unwind(&db, &downloader); + + assert!(matches!( + db.get_package("fresh"), + Err(BallError::PackageNotFound(_)) + )); + assert!(!downloaded.extract_dir.exists()); + assert!(!downloaded.archive_path.exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn test_a_package_that_was_already_installed_is_restored_not_removed() { + let (dir, db, downloader) = scratch("restore"); + let old = package("kept", "1.0.0", &["libold>=1.0"]); + let old_download = fake_download(&dir, &old); + record(&db, &old, &old_download, true); + + let new = package("kept", "2.0.0", &["libnew"]); + let mut session = Session::default(); + session.begin(&db, &new).unwrap(); + let new_download = fake_download(&dir, &new); + session.downloaded(&new_download); + record(&db, &new, &new_download, false); + session.recorded(); + + session.unwind(&db, &downloader); + + let row = db.get_package("kept").unwrap(); + assert_eq!(row.version, "1.0.0"); + assert!(row.user_installed); + assert_eq!(row.install_path, old_download.extract_dir.to_string_lossy()); + assert_eq!( + db.get_dependencies("kept").unwrap(), + vec![("libold".to_string(), "1.0".to_string())] + ); + // The old tree is the install again; only the new one is purged. + assert!(old_download.extract_dir.exists()); + assert!(!new_download.extract_dir.exists()); + assert!(!new_download.archive_path.exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn test_a_same_version_reinstall_keeps_the_tree_it_extracted_over() { + let (dir, db, downloader) = scratch("same_version"); + let pkg = package("same", "1.0.0", &[]); + let downloaded = fake_download(&dir, &pkg); + record(&db, &pkg, &downloaded, true); + + let mut session = Session::default(); + session.begin(&db, &pkg).unwrap(); + session.downloaded(&downloaded); + record(&db, &pkg, &downloaded, true); + session.recorded(); + + session.unwind(&db, &downloader); + + assert_eq!(db.get_package("same").unwrap().version, "1.0.0"); + assert!(downloaded.extract_dir.exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn test_packages_unwind_newest_first_and_untouched_ones_are_left_alone() { + let (dir, db, downloader) = scratch("order"); + let dep = package("dep", "1.0.0", &[]); + let root = package("root", "1.0.0", &["dep"]); + + let mut session = Session::default(); + session.begin(&db, &dep).unwrap(); + let dep_download = fake_download(&dir, &dep); + session.downloaded(&dep_download); + record(&db, &dep, &dep_download, false); + session.recorded(); + // The root failed before anything happened to it. + session.begin(&db, &root).unwrap(); + + assert_eq!(session.installed(), vec!["dep".to_string()]); + session.unwind(&db, &downloader); + + assert!(db.list_packages().unwrap().is_empty()); + assert!(!dep_download.extract_dir.exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn test_an_empty_session_changes_nothing() { + let (dir, db, downloader) = scratch("empty"); + let pkg = package("present", "1.0.0", &[]); + let downloaded = fake_download(&dir, &pkg); + record(&db, &pkg, &downloaded, true); + + let mut session = Session::default(); + session.begin(&db, &pkg).unwrap(); + session.unwind(&db, &downloader); + + assert_eq!(db.get_package("present").unwrap().version, "1.0.0"); + assert!(downloaded.extract_dir.exists()); + assert!(downloaded.archive_path.exists()); + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/src/commands/substitute.rs b/src/commands/substitute.rs index f9b7c58..78ed443 100644 --- a/src/commands/substitute.rs +++ b/src/commands/substitute.rs @@ -1,10 +1,13 @@ use colored::Colorize; use serde_json::json; +use std::path::Path; use crate::commands::draft::screen_artifact; +use crate::commands::rollback::Session; use crate::context::AppContext; use crate::core::dep_solver::{get_installed_map, resolve_deps_with_root}; use crate::core::hooks::{run_hook, HookType}; +use crate::core::package::Package; use crate::core::registry::ensure_installable; use crate::error::error::BallError; use crate::platform::common::PlatformManager; @@ -114,12 +117,82 @@ pub fn execute_substitute( )?; } - // Install all resolved packages (deps first, then root — already ordered by topological sort) - let mut new_installed = None; - for pkg_to_install in &packages { + // Every step of the replacement is noted in `session`. Until the old + // package is off the roster, any failure unwinds the whole replacement — + // including dependencies the user already had, which go back to the + // version they were at — so a failed substitution leaves the roster as + // it found it (#59). + let mut session = Session::default(); + + if let Err(e) = install_replacement(ctx, &pkg, &packages, &mut session) { + session.rollback(ctx); + return Err(e); + } + + if opts.keep_old { + tracing::info!( + "{} {} left on the roster", + "Keeping".yellow(), + old_package.cyan() + ); + } else { + if let Err(e) = remove_old(ctx, old_package) { + session.rollback(ctx); + return Err(e); + } + + // S2: Run post-eject hook for old package + run_hook( + &HookType::PostEject, + old_package, + "", + &ctx.config.hooks_dir, + &ctx.config.hooks, + &[], + )?; + } + + if ctx.flags.json { + return print_json(&json!({ + "command": "substitute", + "old_package": old_package, + "new_package": pkg.name, + "new_version": pkg.version, + "old_kept": opts.keep_old, + "installed": packages.iter().map(|p| p.name.clone()).collect::>(), + "status": "substituted", + })); + } + + println!( + "{} Substitution complete: {} -> {}", + "Done".green().bold(), + old_package.cyan(), + new_package.cyan() + ); + Ok(()) +} + +/// Install every resolved package (deps first, then the root — already in +/// topological order), noting each step in `session`. +/// +/// Returns at the first failure without undoing anything; the caller rolls +/// the session back. +fn install_replacement( + ctx: &AppContext, + root: &Package, + packages: &[Package], + session: &mut Session, +) -> Result<(), BallError> { + let quiet = ctx.flags.is_quiet(); + + for pkg_to_install in packages { + session.begin(&ctx.db, pkg_to_install)?; + let downloaded = ctx .downloader .download_and_extract(pkg_to_install, !quiet)?; + session.downloaded(&downloaded); screen_artifact(ctx, pkg_to_install, &downloaded)?; @@ -134,8 +207,9 @@ pub fn execute_substitute( let bin_path_str = Some(binary_path.to_string_lossy().to_string()); ActiveManager::create_symlink(&binary_path, &pkg_to_install.name)?; + session.linked(); - let is_root = pkg_to_install.name == pkg.name; + let is_root = pkg_to_install.name == root.name; ctx.db.insert_package( pkg_to_install, &install_path, @@ -143,6 +217,7 @@ pub fn execute_substitute( None, is_root, )?; + session.recorded(); // S2: Run post-install hooks let bin_path_ref = bin_path_str.as_deref().unwrap_or(""); @@ -158,76 +233,44 @@ pub fn execute_substitute( &ctx.config.hooks, &post_env, )?; - - // Track the newest root package for rollback info - if pkg_to_install.name == pkg.name { - new_installed = Some((install_path, bin_path_str)); - } } - if opts.keep_old { - tracing::info!( - "{} {} left on the roster", - "Keeping".yellow(), - old_package.cyan() - ); - } else { - // Now remove the old package - ActiveManager::remove_symlink(old_package)?; - match ctx.db.remove_package(old_package) { - Ok(_) => {} - Err(BallError::PackageNotFound(_)) => { - tracing::info!( - "{} '{}' was not in the roster", - "Note".yellow(), - old_package.cyan() - ); - } - Err(e) => { - // S3: Rollback on failure — remove the newly installed packages - if let Some((ref install_path, ref _bin_path)) = new_installed { - let _ = ctx.db.remove_package(&pkg.name); - let _ = std::fs::remove_dir_all(install_path); - tracing::warn!( - "{} Rolled back substitution due to error: {}", - "Warning".red(), - e - ); + Ok(()) +} + +/// Unlink the old package and take it off the roster. +/// +/// The replacement is already in place, so a failure here fails the +/// substitution and the caller rolls the replacement back. The old link is +/// removed first, so if the roster then cannot be changed the link is put +/// back: the old package must come out of a failed substitution as it went in. +fn remove_old(ctx: &AppContext, old_package: &str) -> Result<(), BallError> { + let old_bin = match ctx.db.get_package(old_package) { + Ok(row) => row.bin_path, + Err(BallError::PackageNotFound(_)) => None, + Err(e) => return Err(e), + }; + + ActiveManager::remove_symlink(old_package)?; + match ctx.db.remove_package(old_package) { + Ok(_) => Ok(()), + Err(BallError::PackageNotFound(_)) => { + tracing::info!( + "{} '{}' was not in the roster", + "Note".yellow(), + old_package.cyan() + ); + Ok(()) + } + Err(e) => { + if let Some(bin) = old_bin { + if let Err(link_err) = ActiveManager::create_symlink(Path::new(&bin), old_package) { + tracing::debug!("{}: could not restore its link: {}", old_package, link_err); } - return Err(e); } + Err(e) } - - // S2: Run post-eject hook for old package - run_hook( - &HookType::PostEject, - old_package, - "", - &ctx.config.hooks_dir, - &ctx.config.hooks, - &[], - )?; - } - - if ctx.flags.json { - return print_json(&json!({ - "command": "substitute", - "old_package": old_package, - "new_package": pkg.name, - "new_version": pkg.version, - "old_kept": opts.keep_old, - "installed": packages.iter().map(|p| p.name.clone()).collect::>(), - "status": "substituted", - })); } - - println!( - "{} Substitution complete: {} -> {}", - "Done".green().bold(), - old_package.cyan(), - new_package.cyan() - ); - Ok(()) } /// `--dry-run`: describe the swap without installing or removing anything diff --git a/src/commands/update.rs b/src/commands/update.rs index 66eacc2..061d46f 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -2,6 +2,7 @@ use colored::Colorize; use serde_json::json; use crate::commands::draft::{screen_artifact, source_label}; +use crate::commands::rollback::Session; use crate::context::AppContext; use crate::core::db::InstalledPackage; use crate::core::dep_solver::{get_installed_map, parse_version_flexible, resolve_deps}; @@ -145,89 +146,19 @@ pub fn execute_update(ctx: &AppContext, opts: &UpdateOptions) -> Result<(), Ball return Err(blocked); } - // Install any missing dependencies first - for dep in &missing_deps { - tracing::info!( - " {} new dependency: {}", - "Fetching".cyan(), - dep.name.cyan() - ); - tracing::debug!( - "{}: fetching dependency {} v{} from {}", - pkg.name, - dep.name, - dep.version, - dep.download_url - .as_deref() - .unwrap_or("") - ); - - let downloaded = ctx.downloader.download_and_extract(dep, !quiet)?; - - tracing::debug!( - "{}: dependency extracted to {}", - dep.name, - downloaded.extract_dir.display() - ); - - screen_artifact(ctx, dep, &downloaded)?; - - let install_path = downloaded.extract_dir.to_string_lossy().to_string(); - - // A dependency that extracts without an executable is not - // installed, so it must not reach the database either. - let binary_path = match downloaded.binary_path.as_ref() { - Some(path) => path.clone(), - None => return Err(ctx.downloader.no_binary_error(dep, &downloaded)), - }; - let bin_path_str = Some(binary_path.to_string_lossy().to_string()); - - ActiveManager::create_symlink(&binary_path, &dep.name)?; - - ctx.db.insert_package( - dep, - &install_path, - bin_path_str.as_deref(), - None, - false, - )?; + // Every step from the first new dependency to recording the + // new release is noted in `session`, so a failure anywhere in + // between unwinds the new dependencies and puts the old + // release's link and roster row back (#59). + let mut session = Session::default(); + if let Err(e) = install_update(ctx, pkg, &remote_pkg, &missing_deps, &mut session) { + session.rollback(ctx); + return Err(e); } - // U4: Pre-update hook receives both old and new versions - let pre_env = [ - ("BALLER_NEW_VERSION", remote_pkg.version.as_str()), - ("BALLER_OLD_VERSION", pkg.version.as_str()), - ]; - run_hook( - &HookType::PreUpdate, - &pkg.name, - &remote_pkg.version, - &ctx.config.hooks_dir, - &ctx.config.hooks, - &pre_env, - )?; - - tracing::debug!( - "{}: fetching v{} into cache {}", - pkg.name, - remote_pkg.version, - ctx.config.cache_dir.display() - ); - - let downloaded = ctx.downloader.download_and_extract(&remote_pkg, !quiet)?; - - tracing::debug!( - "{}: extracted to {}", - remote_pkg.name, - downloaded.extract_dir.display() - ); - - // Referee Phase B runs *before* the old extract directory is - // pruned: a rejected upgrade must not also cost the user the - // version they already had working. - screen_artifact(ctx, &remote_pkg, &downloaded)?; - - // U3: Clean old extracted directory before installing new one + // Only now, with the new release linked and recorded, is the + // old extract directory pruned: a failed upgrade must not also + // cost the user the version they already had working. let old_extract_dir = ctx .config .cache_dir @@ -239,27 +170,6 @@ pub fn execute_update(ctx: &AppContext, opts: &UpdateOptions) -> Result<(), Ball ); let _ = std::fs::remove_dir_all(&old_extract_dir); - // The old extract dir is already gone; if the new archive holds - // no executable there is nothing to link, so fail instead of - // recording a version bump the user cannot run. - let binary_path = match downloaded.binary_path.as_ref() { - Some(path) => path.clone(), - None => return Err(ctx.downloader.no_binary_error(&remote_pkg, &downloaded)), - }; - - ActiveManager::create_symlink(&binary_path, &remote_pkg.name)?; - - let install_path = downloaded.extract_dir.to_string_lossy().to_string(); - let bin_path_str = Some(binary_path.to_string_lossy().to_string()); - - ctx.db.insert_package( - &remote_pkg, - &install_path, - bin_path_str.as_deref(), - None, - true, - )?; - // U4: Post-update hook receives both old and new versions let post_env = [ ("BALLER_NEW_VERSION", remote_pkg.version.as_str()), @@ -330,6 +240,130 @@ pub fn execute_update(ctx: &AppContext, opts: &UpdateOptions) -> Result<(), Ball Ok(()) } +/// Install the new dependencies, then link and record the new release, +/// noting every step in `session`. +/// +/// The old release's extract directory is left alone: the caller prunes it +/// once this returns `Ok`. Returns at the first failure without undoing +/// anything; the caller rolls the session back. +fn install_update( + ctx: &AppContext, + pkg: &InstalledPackage, + remote_pkg: &Package, + missing_deps: &[&Package], + session: &mut Session, +) -> Result<(), BallError> { + let quiet = ctx.flags.is_quiet(); + + // Install any missing dependencies first + for dep in missing_deps { + tracing::info!( + " {} new dependency: {}", + "Fetching".cyan(), + dep.name.cyan() + ); + tracing::debug!( + "{}: fetching dependency {} v{} from {}", + pkg.name, + dep.name, + dep.version, + dep.download_url + .as_deref() + .unwrap_or("") + ); + + session.begin(&ctx.db, dep)?; + let downloaded = ctx.downloader.download_and_extract(dep, !quiet)?; + session.downloaded(&downloaded); + + tracing::debug!( + "{}: dependency extracted to {}", + dep.name, + downloaded.extract_dir.display() + ); + + screen_artifact(ctx, dep, &downloaded)?; + + let install_path = downloaded.extract_dir.to_string_lossy().to_string(); + + // A dependency that extracts without an executable is not + // installed, so it must not reach the database either. + let binary_path = match downloaded.binary_path.as_ref() { + Some(path) => path.clone(), + None => return Err(ctx.downloader.no_binary_error(dep, &downloaded)), + }; + let bin_path_str = Some(binary_path.to_string_lossy().to_string()); + + ActiveManager::create_symlink(&binary_path, &dep.name)?; + session.linked(); + + ctx.db + .insert_package(dep, &install_path, bin_path_str.as_deref(), None, false)?; + session.recorded(); + } + + // U4: Pre-update hook receives both old and new versions + let pre_env = [ + ("BALLER_NEW_VERSION", remote_pkg.version.as_str()), + ("BALLER_OLD_VERSION", pkg.version.as_str()), + ]; + run_hook( + &HookType::PreUpdate, + &pkg.name, + &remote_pkg.version, + &ctx.config.hooks_dir, + &ctx.config.hooks, + &pre_env, + )?; + + tracing::debug!( + "{}: fetching v{} into cache {}", + pkg.name, + remote_pkg.version, + ctx.config.cache_dir.display() + ); + + // The session snapshots the installed row here, so a rollback puts the + // old release back rather than removing the package. + session.begin(&ctx.db, remote_pkg)?; + let downloaded = ctx.downloader.download_and_extract(remote_pkg, !quiet)?; + session.downloaded(&downloaded); + + tracing::debug!( + "{}: extracted to {}", + remote_pkg.name, + downloaded.extract_dir.display() + ); + + // Referee Phase B: a rejected upgrade is purged before anything is + // linked, and the old release is still untouched. + screen_artifact(ctx, remote_pkg, &downloaded)?; + + // If the new archive holds no executable there is nothing to link, so + // fail instead of recording a version bump the user cannot run. + let binary_path = match downloaded.binary_path.as_ref() { + Some(path) => path.clone(), + None => return Err(ctx.downloader.no_binary_error(remote_pkg, &downloaded)), + }; + + ActiveManager::create_symlink(&binary_path, &remote_pkg.name)?; + session.linked(); + + let install_path = downloaded.extract_dir.to_string_lossy().to_string(); + let bin_path_str = Some(binary_path.to_string_lossy().to_string()); + + ctx.db.insert_package( + remote_pkg, + &install_path, + bin_path_str.as_deref(), + None, + true, + )?; + session.recorded(); + + Ok(()) +} + /// Everything installed, or just the packages named on the command line fn select_packages( ctx: &AppContext, diff --git a/tests/rollback.rs b/tests/rollback.rs new file mode 100644 index 0000000..0e617ee --- /dev/null +++ b/tests/rollback.rs @@ -0,0 +1,488 @@ +//! A failed `draft`, `substitute` or `update` leaves nothing of itself behind +//! (#59). +//! +//! Each case drives the real binary against a mock baller registry, makes one +//! step partway through the plan fail — a 404 archive or a vetoing pre-hook — +//! and then checks the roster, the links and the cache directly. Packages the +//! run installed fresh must be gone; packages it found already installed must +//! be back at the version, link and roster row they had. +//! +//! Which version a package is exposed as is read from the binary itself — each +//! archive holds a script that names its version — so the same checks cover a +//! Unix symlink under `$HOME/.local/bin` and the copy Windows makes under +//! `%LOCALAPPDATA%\baller\bin`. `BALLER_TEST_BIN` overrides the binary, as in +//! `json_output.rs`, so a Windows build of this test can run on a Windows host. + +use std::collections::HashMap; +use std::io::{BufRead, BufReader, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::PathBuf; +use std::process::{Command, Output, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread; + +use serde_json::{json, Value}; + +/// The binary under test. +fn baller_bin() -> PathBuf { + std::env::var_os("BALLER_TEST_BIN") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_baller"))) +} + +/// A baller registry stand-in whose packages and archives can change between +/// runs, the way a new release appears upstream. +#[derive(Clone)] +struct Registry { + base: String, + packages: Arc>>, + files: Arc>>>, +} + +impl Registry { + fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let registry = Registry { + base: format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()), + packages: Arc::default(), + files: Arc::default(), + }; + let serving = registry.clone(); + thread::spawn(move || { + for stream in listener.incoming().flatten() { + serving.answer(stream); + } + }); + registry + } + + /// Publish `name` at `version`. Its archive is served unless `broken`. + fn publish(&self, name: &str, version: &str, deps: &[&str], broken: bool) { + let file = format!("{}-{}.tar.gz", name, version); + self.packages.lock().unwrap().insert( + name.to_string(), + json!({ + "name": name, + "version": version, + "dependencies": deps, + "download_url": format!("{}/files/{}", self.base, file), + }), + ); + let mut files = self.files.lock().unwrap(); + if broken { + files.remove(&file); + } else { + files.insert(file, archive(name, version)); + } + } + + fn answer(&self, mut stream: TcpStream) { + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut request_line = String::new(); + if reader.read_line(&mut request_line).is_err() { + return; + } + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + } + let path = request_line.split_whitespace().nth(1).unwrap_or(""); + + let found = if let Some(name) = path.strip_prefix("/api/packages/") { + self.packages + .lock() + .unwrap() + .get(name) + .map(|pkg| pkg.to_string().into_bytes()) + } else if let Some(file) = path.strip_prefix("/files/") { + self.files.lock().unwrap().get(file).cloned() + } else { + None + }; + + let (status, body) = match found { + Some(body) => ("200 OK", body), + None => ("404 Not Found", b"{}".to_vec()), + }; + let _ = write!( + stream, + "HTTP/1.1 {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + status, + body.len() + ); + let _ = stream.write_all(&body); + } +} + +/// A `.tar.gz` holding one runnable script named after the package. +fn archive(name: &str, version: &str) -> Vec { + let script = format!("#!/bin/sh\necho {} {}\n", name, version); + let mut header = tar::Header::new_gnu(); + header.set_size(script.len() as u64); + header.set_mode(0o755); + header.set_cksum(); + + let mut builder = tar::Builder::new(flate2::write::GzEncoder::new( + Vec::new(), + flate2::Compression::default(), + )); + builder + .append_data(&mut header, name, script.as_bytes()) + .unwrap(); + builder.into_inner().unwrap().finish().unwrap() +} + +/// A baller directory and `HOME` no other case can see. +struct Sandbox { + dir: PathBuf, +} + +impl Sandbox { + fn new(tag: &str, registry: &Registry) -> Self { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir() + .join("baller_rollback_tests") + .join(format!( + "{}_{}_{}", + std::process::id(), + tag, + COUNTER.fetch_add(1, Ordering::SeqCst) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("baller.conf"), + format!( + "source_order = baller\nballer_registry_url = {}/api\n", + registry.base + ), + ) + .unwrap(); + Sandbox { dir } + } + + /// Run baller with `args`, Referee off: these cases are about rollback, + /// not about what the gate would say. + fn run(&self, args: &[&str]) -> Output { + let mut full = vec!["--config", self.dir.to_str().unwrap(), "--no-referee"]; + full.extend_from_slice(args); + Command::new(baller_bin()) + .args(&full) + .env("HOME", &self.dir) + .env("USERPROFILE", &self.dir) + .env("LOCALAPPDATA", &self.dir) + .env_remove("BALLER_LOG") + .stdin(Stdio::null()) + .output() + .expect("run the baller binary") + } + + fn succeeds(&self, args: &[&str]) { + let out = self.run(args); + assert!(out.status.success(), "{:?} failed: {}", args, stderr(&out)); + } + + /// Run `args`, which must fail, and return its stderr. + fn fails(&self, args: &[&str]) -> String { + let out = self.run(args); + assert!(!out.status.success(), "{:?} should have failed", args); + stderr(&out) + } + + /// A pre-hook for `package` that vetoes the operation. + fn veto(&self, package: &str, hook: &str) { + let hooks = self.dir.join("hooks"); + std::fs::create_dir_all(&hooks).unwrap(); + #[cfg(windows)] + let (file, body) = ( + format!("{}_{}.ps1", package, hook), + "Write-Output vetoed\nexit 1\n", + ); + #[cfg(not(windows))] + let (file, body) = (format!("{}_{}.sh", package, hook), "echo vetoed\nexit 1\n"); + std::fs::write(hooks.join(file), body).unwrap(); + } + + /// The roster row for `name`: `(version, user_installed)`. + fn row(&self, name: &str) -> Option<(String, bool)> { + let db = rusqlite::Connection::open(self.dir.join("db").join("baller.db")).unwrap(); + db.query_row( + "SELECT version, user_installed FROM installed_packages WHERE name = ?1", + [name], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .ok() + } + + fn roster(&self) -> Vec { + let db = rusqlite::Connection::open(self.dir.join("db").join("baller.db")).unwrap(); + let mut stmt = db + .prepare("SELECT name FROM installed_packages ORDER BY name") + .unwrap(); + stmt.query_map([], |row| row.get(0)) + .unwrap() + .collect::>() + .unwrap() + } + + /// The file baller exposes `name` as: a symlink on Unix, a copy on Windows. + fn exposed(&self, name: &str) -> PathBuf { + #[cfg(windows)] + let path = self + .dir + .join("baller") + .join("bin") + .join(format!("{}.exe", name)); + #[cfg(not(windows))] + let path = self.dir.join(".local").join("bin").join(name); + path + } + + /// The version `name`'s exposed binary runs, read from the script in it; + /// `None` when nothing is exposed or the symlink dangles. + fn exposed_version(&self, name: &str) -> Option { + let script = std::fs::read_to_string(self.exposed(name)).ok()?; + script + .lines() + .nth(1)? + .strip_prefix(&format!("echo {} ", name)) + .map(str::to_string) + } + + fn extract_dir(&self, name: &str, version: &str) -> PathBuf { + self.dir.join("cache").join(format!("{}-{}", name, version)) + } + + /// Whether any cached archive of `name` at `version` is left. + fn archive_cached(&self, name: &str, version: &str) -> bool { + let suffix = format!("{}-{}.tar.gz", name, version); + std::fs::read_dir(self.dir.join("cache")) + .unwrap() + .flatten() + .any(|entry| { + entry.path().is_file() && entry.file_name().to_string_lossy().ends_with(&suffix) + }) + } + + /// Assert `name` was installed by the failed run and is now fully gone. + fn assert_gone(&self, name: &str, version: &str) { + assert_eq!(self.row(name), None, "{} is still on the roster", name); + assert!( + std::fs::symlink_metadata(self.exposed(name)).is_err(), + "{} is still exposed at {}", + name, + self.exposed(name).display() + ); + assert!( + !self.extract_dir(name, version).exists(), + "{} v{} is still extracted", + name, + version + ); + assert!( + !self.archive_cached(name, version), + "{} v{}'s archive is still cached", + name, + version + ); + } + + /// Assert `name` is installed at `version`, linked to that version's binary. + fn assert_installed(&self, name: &str, version: &str) { + let (installed, _) = self + .row(name) + .unwrap_or_else(|| panic!("{} is not on the roster", name)); + assert_eq!(installed, version, "{} is at the wrong version", name); + assert_eq!( + self.exposed_version(name).as_deref(), + Some(version), + "{} is exposed at the wrong version", + name + ); + let target = self.extract_dir(name, version).join(name); + #[cfg(not(windows))] + assert_eq!( + std::fs::read_link(self.exposed(name)).ok(), + Some(target.clone()), + "{} link", + name + ); + assert!( + target.exists(), + "{}'s binary {} is gone", + name, + target.display() + ); + } +} + +impl Drop for Sandbox { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +fn stderr(out: &Output) -> String { + String::from_utf8_lossy(&out.stderr).to_string() +} + +/// Assert the rollback warning names exactly `names`, in any order: the +/// resolver may install independent dependencies either way round. +fn assert_reports_rollback(stderr: &str, names: &[&str]) { + let marker = "undid this run's changes to "; + let mut reported: Vec<&str> = stderr + .lines() + .find_map(|line| line.split_once(marker).map(|(_, rest)| rest)) + .unwrap_or_else(|| panic!("no rollback report, got:\n{}", stderr)) + .split(", ") + .collect(); + reported.sort_unstable(); + let mut expected = names.to_vec(); + expected.sort_unstable(); + assert_eq!(reported, expected, "stderr:\n{}", stderr); +} + +#[test] +fn test_a_failed_draft_removes_the_dependencies_it_installed() { + let registry = Registry::start(); + registry.publish("liba", "1.0.0", &[], false); + registry.publish("libb", "1.0.0", &[], false); + registry.publish("app", "1.0.0", &["liba", "libb"], true); + let sandbox = Sandbox::new("draft_fresh", ®istry); + + let err = sandbox.fails(&["draft", "app"]); + + assert_reports_rollback(&err, &["liba", "libb"]); + sandbox.assert_gone("liba", "1.0.0"); + sandbox.assert_gone("libb", "1.0.0"); + assert!(sandbox.roster().is_empty(), "{:?}", sandbox.roster()); +} + +#[test] +fn test_a_vetoed_root_rolls_back_its_dependencies() { + let registry = Registry::start(); + registry.publish("liba", "1.0.0", &[], false); + registry.publish("app", "1.0.0", &["liba"], false); + let sandbox = Sandbox::new("draft_veto", ®istry); + sandbox.veto("app", "pre_install"); + + let err = sandbox.fails(&["draft", "app"]); + + assert_reports_rollback(&err, &["liba"]); + sandbox.assert_gone("liba", "1.0.0"); + sandbox.assert_gone("app", "1.0.0"); +} + +#[test] +fn test_a_failed_forced_draft_restores_what_it_reinstalled() { + let registry = Registry::start(); + registry.publish("liba", "1.0.0", &[], false); + let sandbox = Sandbox::new("draft_force", ®istry); + sandbox.succeeds(&["draft", "liba"]); + + // A new liba appears, and an app that needs it but cannot be fetched. + registry.publish("liba", "2.0.0", &[], false); + registry.publish("app", "1.0.0", &["liba"], true); + let err = sandbox.fails(&["draft", "app", "--force"]); + + assert_reports_rollback(&err, &["liba"]); + // liba was reinstalled at 2.0.0 as a dependency; it comes back as the + // 1.0.0 the user drafted, still marked as user-installed. + sandbox.assert_installed("liba", "1.0.0"); + assert_eq!(sandbox.row("liba"), Some(("1.0.0".to_string(), true))); + assert!(!sandbox.extract_dir("liba", "2.0.0").exists()); + assert_eq!(sandbox.roster(), vec!["liba"]); +} + +#[test] +fn test_a_failed_substitute_leaves_both_packages_as_they_were() { + let registry = Registry::start(); + registry.publish("old", "1.0.0", &[], false); + registry.publish("shared", "1.0.0", &[], false); + let sandbox = Sandbox::new("substitute", ®istry); + sandbox.succeeds(&["draft", "old"]); + sandbox.succeeds(&["draft", "shared"]); + + // The replacement needs a newer `shared` and then cannot be fetched. + registry.publish("shared", "2.0.0", &[], false); + registry.publish("new", "1.0.0", &["shared"], true); + let err = sandbox.fails(&["--yes", "substitute", "old", "new"]); + + assert_reports_rollback(&err, &["shared"]); + sandbox.assert_installed("old", "1.0.0"); + sandbox.assert_installed("shared", "1.0.0"); + assert!(!sandbox.extract_dir("shared", "2.0.0").exists()); + assert_eq!(sandbox.row("new"), None); + assert_eq!(sandbox.roster(), vec!["old", "shared"]); +} + +#[test] +fn test_a_failed_update_keeps_the_old_release_and_drops_new_dependencies() { + let registry = Registry::start(); + registry.publish("tool", "1.0.0", &[], false); + let sandbox = Sandbox::new("update_fetch", ®istry); + sandbox.succeeds(&["draft", "tool"]); + + // 2.0.0 pulls in a new dependency, then its own archive is missing. + registry.publish("libnew", "1.0.0", &[], false); + registry.publish("tool", "2.0.0", &["libnew"], true); + let err = sandbox.fails(&["update", "tool"]); + + assert_reports_rollback(&err, &["libnew"]); + sandbox.assert_gone("libnew", "1.0.0"); + // The old extract dir is pruned only after a committed update. + sandbox.assert_installed("tool", "1.0.0"); + assert_eq!(sandbox.roster(), vec!["tool"]); +} + +#[test] +fn test_a_vetoed_update_drops_the_dependencies_it_fetched() { + let registry = Registry::start(); + registry.publish("tool", "1.0.0", &[], false); + let sandbox = Sandbox::new("update_veto", ®istry); + sandbox.succeeds(&["draft", "tool"]); + + registry.publish("libnew", "1.0.0", &[], false); + registry.publish("tool", "2.0.0", &["libnew"], false); + sandbox.veto("tool", "pre_update"); + let err = sandbox.fails(&["update", "tool"]); + + assert_reports_rollback(&err, &["libnew"]); + sandbox.assert_gone("libnew", "1.0.0"); + sandbox.assert_installed("tool", "1.0.0"); + assert!(!sandbox.extract_dir("tool", "2.0.0").exists()); +} + +#[test] +fn test_a_successful_update_still_prunes_the_old_release() { + let registry = Registry::start(); + registry.publish("tool", "1.0.0", &[], false); + let sandbox = Sandbox::new("update_ok", ®istry); + sandbox.succeeds(&["draft", "tool"]); + + registry.publish("libnew", "1.0.0", &[], false); + registry.publish("tool", "2.0.0", &["libnew"], false); + sandbox.succeeds(&["update", "tool"]); + + sandbox.assert_installed("tool", "2.0.0"); + sandbox.assert_installed("libnew", "1.0.0"); + assert!(!sandbox.extract_dir("tool", "1.0.0").exists()); +} + +#[test] +fn test_a_successful_draft_reports_what_it_installed() { + let registry = Registry::start(); + registry.publish("liba", "1.0.0", &[], false); + registry.publish("app", "1.0.0", &["liba"], false); + let sandbox = Sandbox::new("draft_ok", ®istry); + + let out = sandbox.run(&["--json", "draft", "app"]); + assert!(out.status.success(), "{}", stderr(&out)); + let doc: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(doc["installed"], json!(["liba", "app"])); + sandbox.assert_installed("liba", "1.0.0"); + sandbox.assert_installed("app", "1.0.0"); +}