Skip to main content

thunderstore_engine/profile/
mod.rs

1//! Profile installs on top of [`crate::install`]: five high-level operations
2//! (install an extracted package, uninstall, enable, disable, and the full
3//! download-resolve-install pipeline) that work against an arbitrary target
4//! directory. `mods.yml` ([`modlist`](crate::profile::modlist)) is the
5//! authoritative install record in every mode.
6//!
7//! Two layers share the same primitives:
8//!
9//! - **Client mode** (named r2modman profiles):
10//!   [`install_extracted`](crate::profile::install_extracted),
11//!   [`uninstall_mod`](crate::profile::uninstall_mod),
12//!   [`set_enabled`](crate::profile::set_enabled) (and
13//!   [`enable_mod`](crate::profile::enable_mod)/[`disable_mod`](crate::profile::disable_mod)),
14//!   and [`install_mod`](crate::profile::install_mod) take `base` +
15//!   `profile_name`, compute `layout::profile_dir(base, game, profile_name)`,
16//!   and delegate to the `_in` variant below. The profile name is validated by
17//!   [`layout::validate_name`](crate::profile::layout::validate_name).
18//! - **Server mode**: the `_in` variants
19//!   ([`install_extracted_in`](crate::profile::install_extracted_in),
20//!   [`uninstall_mod_in`](crate::profile::uninstall_mod_in),
21//!   [`set_enabled_in`](crate::profile::set_enabled_in)/[`enable_mod_in`](crate::profile::enable_mod_in)/
22//!   [`disable_mod_in`](crate::profile::disable_mod_in),
23//!   [`install_mod_in`](crate::profile::install_mod_in)) take a
24//!   `target_dir: &Path` directly — there is no named r2modman profile layout;
25//!   `mods.yml` is the source of truth for a single mod set installed straight
26//!   into the game directory.
27//!
28//! A caller-supplied `target_dir` is caller-owned and expected to already be
29//! absolute; unlike a layout profile name it is **not** name-validated here —
30//! there is no [`layout::validate_name`](crate::profile::layout::validate_name)-equivalent
31//! check on it, the caller is trusted to pass a real directory. Package
32//! *contents* are still traversal-guarded regardless of mode:
33//! [`crate::install`]'s `ensure_safe_relative` rejects any archive entry or
34//! computed destination that would escape `target_dir`.
35//!
36//! [`install_mod_in`](crate::profile::install_mod_in)/[`install_mod`](crate::profile::install_mod)
37//! additionally take a `cache_base` independent of the install target:
38//! extracted packages land under
39//! [`cache::ensure_extracted`](crate::profile::cache::ensure_extracted)`(cache_base, ...)`,
40//! never under `target_dir`.
41//! `cache_base` must persist across installs — it is also the restore source
42//! [`crate::install::enable_mod`] copies from when re-enabling a `State`-
43//! tracked mod — and in server mode it must not be `target_dir` itself, or
44//! cache contents would sit inside the installed mod tree.
45
46#![deny(missing_docs)]
47
48/// Extract packages into the per-game package cache.
49pub mod cache;
50/// Compute a launch invocation and stage loader files.
51pub mod launch;
52/// Directory layout and profile lifecycle (named r2modman profiles; client mode).
53pub mod layout;
54/// The `mods.yml` model and its read/write.
55pub mod modlist;
56/// `.r2z` export/import and Thunderstore profile codes.
57pub mod portability;
58/// Where an install goes: a named profile, or the game directory itself.
59#[cfg(feature = "io")]
60pub mod target;
61
62#[cfg(feature = "io")]
63use crate::client::ThunderstoreClient;
64use crate::ecosystem::Ecosystem;
65use crate::error::{Error, Result};
66#[cfg(feature = "io")]
67use crate::extract::parse_package_filename;
68#[cfg(feature = "io")]
69use crate::install::{
70  apply_install_reporting, clear_state_files, plan_install, remove_mod_folders, remove_state_file,
71  remove_state_payload, state_tracker_from_plan, write_state_file,
72};
73use crate::models::Version;
74#[cfg(feature = "io")]
75use crate::models::{DependencyGraph, PackageIndex};
76#[cfg(feature = "io")]
77use crate::progress::{Operation, Stage, StageProgress};
78use modlist::{ProfileMod, SemVer};
79#[cfg(feature = "io")]
80use std::collections::BTreeSet;
81#[cfg(feature = "io")]
82use std::collections::HashMap;
83use std::path::{Path, PathBuf};
84#[cfg(feature = "io")]
85use std::sync::Arc;
86
87/// Builds a [`ProfileMod`] from a Thunderstore [`Version`], applying the same
88/// defaults r2modman uses for a Thunderstore install (`fromThunderstoreCombo`):
89/// `manifestVersion=1`, `gameVersion="0"`, `networkMode="both"`,
90/// `packageType="other"`, `installMode="managed"`.
91pub fn mod_entry_from_version(
92  full_name: &str,
93  owner: &str,
94  version: &Version,
95  installed_at_time: u64,
96) -> ProfileMod {
97  let version_number = version
98    .version_number
99    .as_deref()
100    .map(SemVer::parse)
101    .unwrap_or(SemVer {
102      major: 0,
103      minor: 0,
104      patch: 0,
105    });
106
107  ProfileMod {
108    manifest_version: 1,
109    name: full_name.to_string(),
110    author_name: owner.to_string(),
111    website_url: version.website_url.clone().unwrap_or_default(),
112    display_name: version
113      .name
114      .clone()
115      .unwrap_or_else(|| full_name.to_string()),
116    description: version.description.clone().unwrap_or_default(),
117    game_version: "0".to_string(),
118    network_mode: "both".to_string(),
119    package_type: "other".to_string(),
120    install_mode: "managed".to_string(),
121    installed_at_time,
122    loaders: Vec::new(),
123    dependencies: version.dependencies.clone(),
124    incompatibilities: Vec::new(),
125    optional_dependencies: Vec::new(),
126    version_number,
127    enabled: true,
128    icon: version.icon.clone().unwrap_or_default(),
129    online_source: true,
130    trusted_package: false,
131  }
132}
133
134/// The per-item result of a batch operation.
135///
136/// A batch does not stop at the first failure: an operation that already mutated
137/// earlier items has to report which ones, so `failed` carries the reason per
138/// item rather than collapsing to a single error.
139#[derive(Debug, Clone, Default)]
140#[non_exhaustive]
141pub struct BatchOutcome {
142  /// Identifiers the operation completed.
143  ///
144  /// For [`uninstall_batch`] and [`set_enabled_batch`], this is exactly the
145  /// requested identifiers, in the order each completed, matching this
146  /// field's name at face value. For [`install_batch`] it does not: that
147  /// function sorts and deduplicates it, and fills it with the whole
148  /// dependency closure that installed rather than only what the caller
149  /// asked for. A caller zipping `batch.desired` against this positionally,
150  /// or reading `succeeded.len()` as "how many of my requested items
151  /// worked", is wrong for install by however many dependencies were pulled
152  /// in.
153  pub succeeded: Vec<String>,
154  /// Identifiers left alone because the version already recorded in `mods.yml`
155  /// is the one that would be installed. Only [`install_batch`] fills this;
156  /// like `succeeded` it covers the dependency closure, sorted and
157  /// deduplicated, and never names anything `succeeded` or `failed` also names.
158  pub unchanged: Vec<String>,
159  /// Identifiers that failed, each with the reason.
160  pub failed: Vec<(String, Error)>,
161  /// Untracked folders an uninstall left in place because the caller did not
162  /// call [`UninstallBatch::confirm_untracked`]. Only [`uninstall_batch`]
163  /// fills this.
164  pub kept_untracked: Vec<PathBuf>,
165  /// What was left undone because the caller cancelled.
166  ///
167  /// [`install_batch_with`] lists each `desired` identifier not started, as
168  /// given, and each `Owner-Name` of a started identifier's dependency closure
169  /// left uninstalled. [`uninstall_batch_with`] and [`set_enabled_batch_with`]
170  /// list each identifier not started, and an uninstall also lists each
171  /// confirmed untracked folder it did not remove, by path.
172  pub cancelled: Vec<String>,
173  /// Recorded mods that were disabled before an install and are enabled after
174  /// it, sorted. Only [`install_batch`] fills this, and leaves it empty when
175  /// `mods.yml` cannot be read before or after the installs.
176  pub re_enabled: Vec<String>,
177  /// Mods an install reinstalled and then restored to disabled, from
178  /// [`InstallBatch::protect_disabled`], sorted. Only [`install_batch`] fills
179  /// this, and leaves it empty when `mods.yml` cannot be read after the
180  /// installs.
181  pub kept_disabled: Vec<String>,
182}
183
184impl BatchOutcome {
185  /// Whether every item succeeded: nothing failed and nothing was cancelled.
186  pub fn is_ok(&self) -> bool {
187    self.failed.is_empty() && self.cancelled.is_empty()
188  }
189}
190
191/// What an install batch will install, and whose disabled state it must restore
192/// afterwards.
193#[derive(Debug, Clone, Default)]
194#[non_exhaustive]
195pub struct InstallBatch {
196  /// Every identifier to install. Dependency closures are resolved per item by
197  /// the install itself, so this is what the caller asked for, not the closure.
198  pub desired: Vec<String>,
199  /// Recorded mods whose `enabled: false` must be restored after the batch.
200  ///
201  /// An install upserts every dependency-closure member with `enabled: true` and
202  /// `modlist::upsert` replaces the entry wholesale, so without this a mod the
203  /// user disabled is silently re-enabled by a reinstall.
204  pub protect_disabled: Vec<String>,
205  /// Mods the caller wants enabled after the batch (e.g. the ones it named).
206  ///
207  /// A reinstall already leaves them enabled, but one skipped because its
208  /// recorded version is current is not reinstalled at all, so without this
209  /// naming a disabled mod would leave it disabled. A name that is already
210  /// enabled, or was not skipped, is left alone.
211  pub enable_requested: Vec<String>,
212  /// Reinstall each `desired` mod even when `mods.yml` already records the
213  /// version that would be installed. Applies to the `desired` names only, so
214  /// their dependencies are still skipped at a recorded version.
215  pub force: bool,
216}
217
218impl InstallBatch {
219  /// Builds a batch directly, for a caller that knows its own protect set rather
220  /// than deriving it from the target (e.g. an import applying an export's
221  /// recorded disabled state).
222  pub fn new(desired: Vec<String>, protect_disabled: Vec<String>) -> Self {
223    Self {
224      desired,
225      protect_disabled,
226      ..Self::default()
227    }
228  }
229}
230
231/// Plans an install batch against `target_dir`'s current record.
232///
233/// `desired` is everything to install. `explicit` is the subset the caller named
234/// directly: asking for a mod by name is a request to have it active, so a
235/// disabled one goes to `enable_requested` rather than `protect_disabled`. Pass
236/// an empty `explicit` when the batch is run on the user's behalf rather than at
237/// their request, so every disabled mod is restored.
238///
239/// Reads `target_dir`'s `mods.yml` and plans with [`plan_install_batch_from`].
240#[cfg(feature = "io")]
241pub fn plan_install_batch(
242  target_dir: &Path,
243  desired: &[String],
244  explicit: &[String],
245) -> Result<InstallBatch> {
246  let recorded = modlist::read(target_dir)?;
247
248  Ok(plan_install_batch_from(&recorded, desired, explicit))
249}
250
251/// Plans an install batch against an already-read record, without touching
252/// disk.
253///
254/// `recorded` is the target's `mods.yml` entries. `desired` and `explicit` mean
255/// what they do for [`plan_install_batch`]: a disabled mod named in `explicit`
256/// goes to [`InstallBatch::enable_requested`], and every other disabled mod to
257/// [`InstallBatch::protect_disabled`].
258pub fn plan_install_batch_from(
259  recorded: &[ProfileMod],
260  desired: &[String],
261  explicit: &[String],
262) -> InstallBatch {
263  let (enable_requested, protect_disabled): (Vec<String>, Vec<String>) = recorded
264    .iter()
265    .filter(|entry| !entry.enabled)
266    .map(|entry| entry.name.clone())
267    .partition(|name| {
268      explicit
269        .iter()
270        .any(|requested| crate::util::full_name_prefix(requested) == name.as_str())
271    });
272
273  InstallBatch {
274    desired: desired.to_vec(),
275    protect_disabled,
276    enable_requested,
277    force: false,
278  }
279}
280
281/// Re-disables everything `batch` protects, after the installs have run.
282///
283/// Must run after the whole batch, never interleaved: a mod later in a batch can
284/// pull an earlier one back in as a dependency, so only a final pass catches
285/// every re-enable. Runs even when the batch failed partway, since items
286/// installed before the failure are already enabled. A protected mod that is not
287/// installed, because its own install failed, has nothing to disable and is
288/// skipped, so the install's failure is the one reported.
289#[cfg(feature = "io")]
290pub fn reapply_batch_disabled(
291  target_dir: &Path,
292  eco: &Ecosystem,
293  game: &str,
294  batch: &InstallBatch,
295) -> Result<()> {
296  let recorded = modlist::read(target_dir)?;
297
298  for full_name in &batch.protect_disabled {
299    if !recorded.iter().any(|entry| &entry.name == full_name) {
300      continue;
301    }
302
303    set_enabled_in(target_dir, eco, game, full_name, false)?;
304  }
305
306  Ok(())
307}
308
309/// Installs an already-extracted package into `target_dir`: plans the file copy,
310/// removes any copy already installed (its namespaced `<route>/<ident>/` folders
311/// and `State`-tracked files, as r2modman uninstalls before installing), applies
312/// the copy, writes the `_state` tracker for any `State`-tracked files, and
313/// upserts the `mods.yml` entry.
314///
315/// Shared `none`-tracked files (config) are left in place, and an existing one is
316/// not overwritten. A failure after the removal leaves the mod without files
317/// while `mods.yml` and its `_state` record still name it; reinstalling repairs
318/// that, and uninstalling still works.
319///
320/// This is the apply-only, target-directory primitive; the full download
321/// pipeline ([`install_mod_in`]) is layered on top of it.
322#[allow(clippy::too_many_arguments)]
323#[cfg(feature = "io")]
324pub fn install_extracted_in(
325  target_dir: &Path,
326  eco: &Ecosystem,
327  game: &str,
328  full_name: &str,
329  owner: &str,
330  version: &Version,
331  extracted_dir: &Path,
332  archive: Option<&Path>,
333  installed_at_time: u64,
334) -> Result<()> {
335  install_extracted_reporting(
336    target_dir,
337    eco,
338    game,
339    full_name,
340    owner,
341    version,
342    extracted_dir,
343    archive,
344    installed_at_time,
345    &mut |_, _| {},
346  )
347}
348
349/// [`install_extracted_in`], passing `on_progress` to the file copy.
350#[allow(clippy::too_many_arguments)]
351#[cfg(feature = "io")]
352fn install_extracted_reporting(
353  target_dir: &Path,
354  eco: &Ecosystem,
355  game: &str,
356  full_name: &str,
357  owner: &str,
358  version: &Version,
359  extracted_dir: &Path,
360  archive: Option<&Path>,
361  installed_at_time: u64,
362  on_progress: &mut dyn FnMut(u64, u64),
363) -> Result<()> {
364  let game_profile = eco.require_profile(game)?;
365
366  let plan = plan_install(eco, game_profile, full_name, extracted_dir, archive)?;
367
368  // Planned first so a package that cannot be routed fails before anything of
369  // the installed copy is removed. Shared `none` routes are never named here,
370  // so user config survives. The `_state` record outlives its payload until the
371  // copy lands, so a failed apply still leaves the mod uninstallable, which
372  // `ensure_removable` refuses for a loader with no record.
373  clear_state_files(target_dir, full_name)?;
374  remove_mod_folders(game_profile, target_dir, full_name)?;
375  apply_install_reporting(&plan, target_dir, on_progress)?;
376
377  match state_tracker_from_plan(&plan, full_name) {
378    Some(tracker) => write_state_file(target_dir, &tracker)?,
379    None => remove_state_file(target_dir, full_name)?,
380  }
381
382  let mut mods = modlist::read(target_dir)?;
383
384  modlist::upsert(
385    &mut mods,
386    mod_entry_from_version(full_name, owner, version, installed_at_time),
387  );
388
389  modlist::write(target_dir, &mods)
390}
391
392/// Installs an already-extracted package into an r2modman-layout profile
393/// (`<base>/<game>/profiles/<profile_name>`). See [`install_extracted_in`].
394#[allow(clippy::too_many_arguments)]
395#[cfg(feature = "io")]
396pub fn install_extracted(
397  base: &Path,
398  eco: &Ecosystem,
399  game: &str,
400  profile_name: &str,
401  full_name: &str,
402  owner: &str,
403  version: &Version,
404  extracted_dir: &Path,
405  archive: Option<&Path>,
406  installed_at_time: u64,
407) -> Result<()> {
408  install_extracted_in(
409    &layout::profile_dir(base, game, profile_name),
410    eco,
411    game,
412    full_name,
413    owner,
414    version,
415    extracted_dir,
416    archive,
417    installed_at_time,
418  )
419}
420
421/// Why a recorded mod's files cannot be removed exactly.
422///
423/// Returned rather than flattened into a message because the distinction drives
424/// what a caller should advise: an absent record can be rebuilt by reinstalling,
425/// while an unreadable one is a file the engine will not guess the contents of.
426/// Only the wording of that advice belongs to the caller, and a caller that
427/// words it itself should not have to re-derive the reason by re-reading the
428/// record the engine has already read.
429///
430/// Deliberately **not** `#[non_exhaustive]`, unlike the rest of this crate's
431/// public types, for the same reason [`launch::LaunchPlan::to_command`] gives: a
432/// caller that words each refusal should stop compiling when a new reason
433/// appears, rather than silently printing a generic fallback for a case nobody
434/// worded. Designing that fallback is the thing this type exists to avoid.
435#[derive(Debug)]
436pub enum NotRemovable {
437  /// A recognised mod loader with no install record at `path`, so which files it
438  /// placed is unknown. Reinstalling the loader rebuilds the record.
439  RecordAbsent {
440    /// The mod that cannot be removed.
441    name: String,
442    /// Where the record was expected.
443    path: PathBuf,
444  },
445  /// An install record exists at `path` but could not be read or parsed, so the
446  /// engine does not know which files it tracked and will not guess.
447  RecordUnreadable {
448    /// The mod that cannot be removed.
449    name: String,
450    /// The record that could not be read.
451    path: PathBuf,
452    /// Why it could not be read.
453    source: Error,
454  },
455}
456
457impl std::fmt::Display for NotRemovable {
458  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
459    match self {
460      Self::RecordAbsent { name, path } => write!(
461        f,
462        "{name} is a mod loader with no install record at {}, so its files \
463         cannot be removed exactly. Reinstall it, then uninstall it again, or \
464         remove its files by hand.",
465        path.display()
466      ),
467      Self::RecordUnreadable { name, path, source } => write!(
468        f,
469        "{name} has an install record at {} that cannot be read, so its files \
470         cannot be removed exactly: {source}",
471        path.display()
472      ),
473    }
474  }
475}
476
477impl From<NotRemovable> for Error {
478  fn from(value: NotRemovable) -> Self {
479    Error::Profile(value.to_string())
480  }
481}
482
483/// Whether `full_name`'s files can be removed exactly, reporting the reason
484/// when they cannot.
485///
486/// A *missing* record is only a problem for a package whose files are `State`
487/// tracked. A recognised mod loader always gets one when this engine installs
488/// it, so a missing record means the target was adopted from disk rather than
489/// installed and there is no way to know which files the loader placed;
490/// uninstalling anyway would drop the `mods.yml` entry and leave every one of
491/// its files orphaned. An ordinary mod, by contrast, has no record by design
492/// under install rules with no `state` route, and its folders are removed
493/// by presence instead.
494///
495/// An *unreadable* record is always a problem, loader or not: the file exists,
496/// so something tracked files, and guessing which is how an uninstall orphans or
497/// over-deletes. That case arrives as the `Err` from
498/// [`crate::install::read_state_file`], which is carried as
499/// [`NotRemovable::RecordUnreadable`]'s `source` rather than propagated on its
500/// own, so the two reasons reach a caller as one type it can match.
501///
502/// Returns [`NotRemovable`] rather than [`Error`] because the two reasons want
503/// different advice and a caller wording that advice itself would otherwise have
504/// to re-read the record to tell them apart. `?` still converts it for a caller
505/// that does not care, via [`From<NotRemovable>`](NotRemovable).
506///
507/// Public and separate from [`uninstall_mod_in`] so a caller can pre-flight a
508/// whole batch and refuse before touching the first mod. `uninstall_mod_in`
509/// calls it too, so a single uninstall is protected whether or not the caller
510/// does.
511///
512/// Takes no `game`: the only schema consulted is the mod-loader registry, which
513/// [`Ecosystem::modloader_package`] keys on package identity rather than on a
514/// game, so a `game` argument would go unread.
515///
516/// Reads the record with [`read_record_state`] and decides with
517/// [`check_removable_from`].
518#[cfg(feature = "io")]
519pub fn ensure_removable(
520  target_dir: &Path,
521  eco: &Ecosystem,
522  full_name: &str,
523) -> std::result::Result<(), NotRemovable> {
524  check_removable_from(
525    target_dir,
526    eco,
527    full_name,
528    read_record_state(target_dir, full_name),
529  )
530}
531
532/// What reading a mod's `_state` install record found.
533///
534/// The input [`check_removable_from`] and [`plan_uninstall_batch_from`] decide
535/// from, so a caller that reads the record itself can hand over what it found.
536#[derive(Debug)]
537pub enum RecordState {
538  /// The record exists and parses.
539  Present,
540  /// There is no record.
541  Absent,
542  /// The record exists but could not be read or parsed, for this reason.
543  Unreadable(Error),
544}
545
546/// Reads `full_name`'s `_state` record in `target_dir` and reports what it
547/// found.
548#[cfg(feature = "io")]
549pub fn read_record_state(target_dir: &Path, full_name: &str) -> RecordState {
550  match crate::install::read_state_file(target_dir, full_name) {
551    Ok(Some(_)) => RecordState::Present,
552    Ok(None) => RecordState::Absent,
553    Err(source) => RecordState::Unreadable(source),
554  }
555}
556
557/// Whether `full_name`'s files can be removed exactly, given what its install
558/// record holds, without touching disk.
559///
560/// The rules are [`ensure_removable`]'s: an unreadable record always refuses,
561/// and a missing one refuses only for a recognised mod loader. `target_dir` only
562/// names the record's path in a refusal.
563pub fn check_removable_from(
564  target_dir: &Path,
565  eco: &Ecosystem,
566  full_name: &str,
567  record: RecordState,
568) -> std::result::Result<(), NotRemovable> {
569  match record {
570    RecordState::Present => return Ok(()),
571    RecordState::Absent => {}
572    RecordState::Unreadable(source) => {
573      return Err(NotRemovable::RecordUnreadable {
574        name: full_name.to_string(),
575        path: crate::install::state_file_path(target_dir, full_name),
576        source,
577      });
578    }
579  }
580
581  if eco.modloader_package(full_name).is_none() {
582    return Ok(());
583  }
584
585  Err(NotRemovable::RecordAbsent {
586    name: full_name.to_string(),
587    path: crate::install::state_file_path(target_dir, full_name),
588  })
589}
590
591/// Uninstalls a mod from `target_dir`: removes its `mods.yml` entry, its
592/// `<Owner-Name>/` folder under each namespaced route, and its `State`-tracked
593/// payload files along with its `_state` file. Folders the record does not
594/// name are left alone; [`uninstall_batch`] removes those only when asked.
595/// A name `mods.yml` does not record exactly is [`Error::NotInstalled`], before
596/// anything is touched.
597///
598/// [`ensure_removable`] gates the whole thing before anything is touched, so a
599/// mod whose files cannot be removed exactly is refused rather than half
600/// removed. See its doc for which records qualify.
601///
602/// Both removal paths are needed: the per-mod folders sit under namespaced
603/// routes, while `State`-tracked files sit directly under a shared route (e.g.
604/// `BepInEx/core/`) and are only recoverable from the `_state` record. This
605/// function does not special-case the mod loader beyond the refusal above:
606/// naming it as `full_name` removes it through these same two paths like any
607/// other mod, which is how callers such as `vmm uninstall --all` uninstall it.
608/// Only shared config
609/// (`none`-tracked) is unconditionally left untouched, since nothing this
610/// function does ever names it for removal.
611#[cfg(feature = "io")]
612pub fn uninstall_mod_in(
613  target_dir: &Path,
614  eco: &Ecosystem,
615  game: &str,
616  full_name: &str,
617) -> Result<()> {
618  let game_profile = eco.require_profile(game)?;
619
620  // Before any mutation. `remove_state_payload` below reaches an unreadable
621  // record on its own, but only after `remove_mod_folders` has already deleted
622  // this mod's folders and before `mods.yml` is rewritten, so the entry would be
623  // left naming files that are gone. Refusing here is what keeps both sides
624  // intact.
625  ensure_removable(target_dir, eco, full_name)?;
626
627  let mut mods = modlist::read(target_dir)?;
628
629  if modlist::find(&mods, full_name).is_none() {
630    return Err(Error::NotInstalled {
631      package: full_name.to_string(),
632    });
633  }
634
635  mods.retain(|m| m.name != full_name);
636
637  remove_mod_folders(game_profile, target_dir, full_name)?;
638  remove_state_payload(target_dir, full_name)?;
639
640  modlist::write(target_dir, &mods)
641}
642
643/// Uninstalls a mod from an r2modman-layout profile. See [`uninstall_mod_in`].
644#[cfg(feature = "io")]
645pub fn uninstall_mod(
646  base: &Path,
647  eco: &Ecosystem,
648  game: &str,
649  profile_name: &str,
650  full_name: &str,
651) -> Result<()> {
652  uninstall_mod_in(
653    &layout::profile_dir(base, game, profile_name),
654    eco,
655    game,
656    full_name,
657  )
658}
659
660/// Enables or disables an installed mod in `target_dir`: applies the on-disk
661/// file toggle through the install layer, then flips `enabled` in `mods.yml`.
662/// Errors if the mod is not present in `target_dir`.
663///
664/// A mod-loader pack (see [`Ecosystem::modloader_package`]) is a no-op here,
665/// matching r2modman: loaders can't be disabled, so neither the on-disk files
666/// nor its `enabled` flag are touched.
667#[cfg(feature = "io")]
668pub fn set_enabled_in(
669  target_dir: &Path,
670  eco: &Ecosystem,
671  game: &str,
672  full_name: &str,
673  enabled: bool,
674) -> Result<()> {
675  let game_profile = eco.require_profile(game)?;
676
677  let mut mods = modlist::read(target_dir)?;
678
679  let entry = mods
680    .iter_mut()
681    .find(|m| m.name == full_name)
682    .ok_or_else(|| Error::NotInstalled {
683      package: full_name.to_string(),
684    })?;
685
686  if eco.modloader_package(full_name).is_some() {
687    return Ok(());
688  }
689
690  if enabled {
691    crate::install::enable_mod(game_profile, target_dir, full_name)?;
692  } else {
693    crate::install::disable_mod(game_profile, target_dir, full_name)?;
694  }
695
696  entry.enabled = enabled;
697
698  modlist::write(target_dir, &mods)
699}
700
701/// Enables or disables an installed mod in an r2modman-layout profile. See
702/// [`set_enabled_in`].
703#[cfg(feature = "io")]
704pub fn set_enabled(
705  base: &Path,
706  eco: &Ecosystem,
707  game: &str,
708  profile_name: &str,
709  full_name: &str,
710  enabled: bool,
711) -> Result<()> {
712  set_enabled_in(
713    &layout::profile_dir(base, game, profile_name),
714    eco,
715    game,
716    full_name,
717    enabled,
718  )
719}
720
721/// Enables an installed mod in `target_dir`. See [`set_enabled_in`].
722#[cfg(feature = "io")]
723pub fn enable_mod_in(
724  target_dir: &Path,
725  eco: &Ecosystem,
726  game: &str,
727  full_name: &str,
728) -> Result<()> {
729  set_enabled_in(target_dir, eco, game, full_name, true)
730}
731
732/// Disables an installed mod in `target_dir`. See [`set_enabled_in`].
733#[cfg(feature = "io")]
734pub fn disable_mod_in(
735  target_dir: &Path,
736  eco: &Ecosystem,
737  game: &str,
738  full_name: &str,
739) -> Result<()> {
740  set_enabled_in(target_dir, eco, game, full_name, false)
741}
742
743/// Enables an installed mod. See [`set_enabled`].
744#[cfg(feature = "io")]
745pub fn enable_mod(
746  base: &Path,
747  eco: &Ecosystem,
748  game: &str,
749  profile_name: &str,
750  full_name: &str,
751) -> Result<()> {
752  set_enabled(base, eco, game, profile_name, full_name, true)
753}
754
755/// Disables an installed mod. See [`set_enabled`].
756#[cfg(feature = "io")]
757pub fn disable_mod(
758  base: &Path,
759  eco: &Ecosystem,
760  game: &str,
761  profile_name: &str,
762  full_name: &str,
763) -> Result<()> {
764  set_enabled(base, eco, game, profile_name, full_name, false)
765}
766
767/// Installs a mod and its full dependency closure into `target_dir`: resolves
768/// the download set against `index`, downloads the archives via `client`,
769/// extracts each into `cache_base`'s per-game package cache, and installs
770/// each into `target_dir` (updating `mods.yml`).
771///
772/// A package whose version `mods.yml` already records, and whose files that
773/// version installs are still on disk, is skipped before it is downloaded, as
774/// r2modman does, unless it is `full_name` itself and `force` is set. A recorded
775/// package with missing files is reinstalled, which repairs a failed install or
776/// a hand-deleted folder. Returns the sorted `Owner-Name` identifiers installed
777/// and those skipped.
778///
779/// `cache_base` is deliberately independent of `target_dir`: packages are
780/// extracted *from* it, never installed *into* it. See the module docs for
781/// why it must persist across installs and, in server mode, must not be
782/// `target_dir` itself.
783#[allow(clippy::too_many_arguments)]
784#[cfg(feature = "io")]
785async fn install_one(
786  target_dir: &Path,
787  cache_base: &Path,
788  eco: &Arc<Ecosystem>,
789  index: &PackageIndex,
790  client: &ThunderstoreClient,
791  game: &str,
792  full_name: &str,
793  pins: &[String],
794  force: bool,
795  installed_at_time: u64,
796  operation: &Operation,
797) -> Result<ClosureOutcome> {
798  let resolution = DependencyGraph::new(vec![full_name.to_string()])
799    .pins(pins.iter().cloned())
800    .resolve_report(index);
801
802  // A pinned version the package does not publish stops resolution before any
803  // dependency is reached, so the request itself is the only entry.
804  if let [unresolved] = resolution.unresolved.as_slice()
805    && unresolved == full_name
806    && let Some((name, version)) = crate::util::split_version(full_name)
807  {
808    return Err(Error::MissingVersion {
809      package: name.to_string(),
810      version: version.to_string(),
811    });
812  }
813
814  if !resolution.unresolved.is_empty() {
815    return Err(Error::UnresolvedDependency {
816      package: full_name.to_string(),
817      unresolved: resolution.unresolved,
818    });
819  }
820
821  let recorded = modlist::read(target_dir)?;
822  let forced = force.then(|| crate::util::full_name_prefix(full_name));
823  let downloads = client.cache_dir().join("downloads");
824  let mut urls = HashMap::new();
825  let mut unchanged = Vec::new();
826
827  for (filename, url) in resolution.urls {
828    let (pkg_full_name, version_str) = parse_package_filename(&filename)
829      .ok_or_else(|| Error::Profile(format!("unparseable package filename {filename:?}")))?;
830
831    let version = SemVer::parse(&version_str);
832    let current = forced != Some(pkg_full_name.as_str())
833      && recorded
834        .iter()
835        .find(|entry| entry.name == pkg_full_name && entry.version_number == version)
836        .is_some_and(|entry| {
837          recorded_files_present(
838            target_dir,
839            cache_base,
840            eco,
841            game,
842            entry,
843            &version_str,
844            &downloads.join(&filename),
845          )
846        });
847
848    if current {
849      unchanged.push(pkg_full_name);
850    } else {
851      urls.insert(filename, url);
852    }
853  }
854
855  client.download_files_for(urls.clone(), operation).await?;
856
857  let mut jobs = Vec::with_capacity(urls.len());
858
859  for filename in urls.keys() {
860    let (pkg_full_name, version_str) = parse_package_filename(filename)
861      .ok_or_else(|| Error::Profile(format!("unparseable package filename {filename:?}")))?;
862
863    let package = index
864      .get_package_by_full_name(&pkg_full_name)
865      .ok_or_else(|| Error::Profile(format!("{pkg_full_name} missing from index")))?;
866
867    let owner = package.owner.clone().unwrap_or_default();
868    let version = package
869      .versions
870      .iter()
871      .find(|v| v.version_number.as_deref() == Some(version_str.as_str()))
872      .or_else(|| package.latest_version())
873      .ok_or_else(|| Error::Profile(format!("{pkg_full_name} has no usable version")))?
874      .clone();
875
876    jobs.push(PackageJob {
877      target_dir: target_dir.to_path_buf(),
878      cache_base: cache_base.to_path_buf(),
879      eco: eco.clone(),
880      game: game.to_string(),
881      full_name: pkg_full_name,
882      owner,
883      version,
884      version_str,
885      archive: downloads.join(filename),
886      installed_at_time,
887      operation: operation.clone(),
888    });
889  }
890
891  let mut closure = ClosureOutcome {
892    unchanged,
893    ..ClosureOutcome::default()
894  };
895
896  for job in dependencies_first(jobs) {
897    let pkg_full_name = job.full_name.clone();
898
899    if operation.is_cancelled() {
900      closure.cancelled.push(pkg_full_name);
901
902      continue;
903    }
904
905    tokio::task::spawn_blocking(move || job.run())
906      .await
907      .map_err(|e| Error::Install(format!("install task for {pkg_full_name} failed: {e}")))??;
908
909    closure.installed.push(pkg_full_name);
910  }
911
912  closure.installed.sort();
913  closure.unchanged.sort();
914  closure.cancelled.sort();
915
916  Ok(closure)
917}
918
919/// What [`install_one`] did with each package of one dependency closure, each
920/// list sorted.
921#[cfg(feature = "io")]
922#[derive(Debug, Default)]
923struct ClosureOutcome {
924  installed: Vec<String>,
925  unchanged: Vec<String>,
926  cancelled: Vec<String>,
927}
928
929/// `jobs` reordered so each package comes after every package in `jobs` it
930/// depends on, which keeps a cancel between packages from leaving an
931/// installed mod without its dependencies. Ties go by name, and a dependency
932/// cycle is broken at the first package reached.
933#[cfg(feature = "io")]
934fn dependencies_first(mut jobs: Vec<PackageJob>) -> Vec<PackageJob> {
935  jobs.sort_by(|a, b| a.full_name.cmp(&b.full_name));
936
937  let position: HashMap<&str, usize> = jobs
938    .iter()
939    .enumerate()
940    .map(|(at, job)| (job.full_name.as_str(), at))
941    .collect();
942  let requires: Vec<Vec<usize>> = jobs
943    .iter()
944    .map(|job| {
945      job
946        .version
947        .dependencies
948        .iter()
949        .filter_map(|dependency| {
950          position
951            .get(crate::util::full_name_prefix(dependency))
952            .copied()
953        })
954        .collect()
955    })
956    .collect();
957  let mut visited = vec![false; jobs.len()];
958  let mut order = Vec::with_capacity(jobs.len());
959
960  for at in 0..jobs.len() {
961    visit_dependencies_first(at, &requires, &mut visited, &mut order);
962  }
963
964  let mut slots: Vec<Option<PackageJob>> = jobs.into_iter().map(Some).collect();
965
966  order
967    .into_iter()
968    .filter_map(|at| slots[at].take())
969    .collect()
970}
971
972/// Pushes `at` onto `order` after everything it `requires`, depth first.
973#[cfg(feature = "io")]
974fn visit_dependencies_first(
975  at: usize,
976  requires: &[Vec<usize>],
977  visited: &mut [bool],
978  order: &mut Vec<usize>,
979) {
980  if visited[at] {
981    return;
982  }
983
984  visited[at] = true;
985
986  for &dependency in &requires[at] {
987    visit_dependencies_first(dependency, requires, visited, order);
988  }
989
990  order.push(at);
991}
992
993/// The blocking half of installing one downloaded package: extract it into the
994/// package cache, then install it into the target. Owns its inputs so it can
995/// run on the blocking pool.
996#[cfg(feature = "io")]
997struct PackageJob {
998  target_dir: PathBuf,
999  cache_base: PathBuf,
1000  eco: Arc<Ecosystem>,
1001  game: String,
1002  full_name: String,
1003  owner: String,
1004  version: Version,
1005  version_str: String,
1006  archive: PathBuf,
1007  installed_at_time: u64,
1008  operation: Operation,
1009}
1010
1011#[cfg(feature = "io")]
1012impl PackageJob {
1013  fn run(self) -> Result<()> {
1014    let mut extracting = None;
1015
1016    let extracted = cache::ensure_extracted_reporting(
1017      &self.cache_base,
1018      &self.game,
1019      &self.full_name,
1020      &self.version_str,
1021      &self.archive,
1022      &mut |done, total| self.advance(&mut extracting, Stage::Extracting, done, total),
1023    )?;
1024
1025    drop(extracting);
1026
1027    let mut installing = None;
1028
1029    install_extracted_reporting(
1030      &self.target_dir,
1031      &self.eco,
1032      &self.game,
1033      &self.full_name,
1034      &self.owner,
1035      &self.version,
1036      &extracted,
1037      Some(&self.archive),
1038      self.installed_at_time,
1039      &mut |done, total| self.advance(&mut installing, Stage::Installing, done, total),
1040    )
1041  }
1042
1043  /// Starts `stage` in `slot` on the first call, then reports `done`.
1044  fn advance(&self, slot: &mut Option<StageProgress>, stage: Stage, done: u64, total: u64) {
1045    let progress =
1046      slot.get_or_insert_with(|| self.operation.stage(&self.full_name, stage, Some(total)));
1047
1048    if done > 0 {
1049      progress.advance(done);
1050    }
1051  }
1052}
1053
1054/// Whether the files `entry` installed at `version` are still in place, judged
1055/// from the package's cached extraction. A missing cache, an unknown game or a
1056/// package that no longer plans counts as not in place, so the install runs and
1057/// either repairs the mod or reports why it cannot.
1058#[cfg(feature = "io")]
1059fn recorded_files_present(
1060  target_dir: &Path,
1061  cache_base: &Path,
1062  eco: &Ecosystem,
1063  game: &str,
1064  entry: &ProfileMod,
1065  version: &str,
1066  archive: &Path,
1067) -> bool {
1068  let extracted = cache::package_cache_dir(cache_base, game, &entry.name, version);
1069
1070  if !extracted.is_dir() {
1071    return false;
1072  }
1073
1074  let Some(game_profile) = eco.game(game).and_then(|g| g.profile()) else {
1075    return false;
1076  };
1077
1078  let archive = archive.exists().then_some(archive);
1079
1080  plan_install(eco, game_profile, &entry.name, &extracted, archive).is_ok_and(|plan| {
1081    crate::install::plan_is_on_disk(&plan, target_dir, &entry.name, entry.enabled)
1082  })
1083}
1084
1085/// Installs every identifier in `batch`, restoring protected disabled state
1086/// afterwards, and reports per-item outcomes.
1087///
1088/// Failures do not abort the batch: each item is attempted and its reason
1089/// recorded, because an operation that already installed earlier items has to
1090/// say which ones. The disabled-state restore runs regardless, since items
1091/// installed before a failure are already enabled. A requested enable or a
1092/// disabled-state restore that fails is recorded the same way, as is every one
1093/// of them when `mods.yml` cannot be read, so the outcome is kept rather than
1094/// replaced by an error.
1095///
1096/// A `desired` entry of `Owner-Name-Version` installs exactly that version, and
1097/// the pin holds for the rest of the batch.
1098///
1099/// Reports nothing and cannot be cancelled; see [`install_batch_with`].
1100#[allow(clippy::too_many_arguments)]
1101#[cfg(feature = "io")]
1102pub async fn install_batch(
1103  target_dir: &Path,
1104  cache_base: &Path,
1105  eco: &Ecosystem,
1106  index: &PackageIndex,
1107  client: &ThunderstoreClient,
1108  game: &str,
1109  batch: &InstallBatch,
1110  installed_at_time: u64,
1111) -> Result<BatchOutcome> {
1112  install_batch_with(
1113    target_dir,
1114    cache_base,
1115    eco,
1116    index,
1117    client,
1118    game,
1119    batch,
1120    installed_at_time,
1121    &Operation::default(),
1122  )
1123  .await
1124}
1125
1126/// [`install_batch`], reporting each package's download, extraction, and
1127/// install to `operation`, and stopping once `operation` is cancelled.
1128/// Extraction and file copying run on Tokio's blocking pool.
1129///
1130/// A cancel takes effect before the next package, dependencies included: the
1131/// package being installed finishes, and the rest are left alone. Each
1132/// identifier's dependencies install before it, so no installed mod is left
1133/// without them. The packages and `desired` identifiers not started land in
1134/// [`BatchOutcome::cancelled`], and the disabled-state restore still runs.
1135/// Downloads for an identifier's closure run together and are not
1136/// interrupted. Dropping the future instead skips the restore, and the package
1137/// on the blocking pool keeps installing, writing `mods.yml` and its `_state`
1138/// file, after the future is gone, so a profile operation started right after
1139/// can race it. Cancel through the token and await the future instead.
1140///
1141/// # Examples
1142///
1143/// ```no_run
1144/// use std::path::Path;
1145/// use thunderstore_engine::client::ThunderstoreClient;
1146/// use thunderstore_engine::ecosystem::Ecosystem;
1147/// use thunderstore_engine::profile::{self, modlist};
1148/// use thunderstore_engine::progress::{Operation, OperationId};
1149///
1150/// # async fn run(client: &ThunderstoreClient, target: &Path) -> thunderstore_engine::Result<()> {
1151/// let index = client.get_manifest().await?;
1152/// let desired = ["Owner-ModA".to_string()];
1153/// let batch = profile::plan_install_batch(target, &desired, &desired)?;
1154/// let (tx, rx) = std::sync::mpsc::channel();
1155/// let operation = Operation::new(OperationId(1)).with_progress(move |event| {
1156///   let _ = tx.send(event);
1157/// });
1158/// let cancel = operation.cancel_token();
1159///
1160/// let outcome = profile::install_batch_with(
1161///   target,
1162///   Path::new("/var/cache/my-mod-manager"),
1163///   &Ecosystem::bundled(),
1164///   &index,
1165///   client,
1166///   "valheim",
1167///   &batch,
1168///   modlist::now_millis(),
1169///   &operation,
1170/// )
1171/// .await?;
1172///
1173/// println!("cancelled: {:?}", outcome.cancelled);
1174/// # let _ = (rx, cancel);
1175/// # Ok(())
1176/// # }
1177/// ```
1178#[allow(clippy::too_many_arguments)]
1179#[cfg(feature = "io")]
1180pub async fn install_batch_with(
1181  target_dir: &Path,
1182  cache_base: &Path,
1183  eco: &Ecosystem,
1184  index: &PackageIndex,
1185  client: &ThunderstoreClient,
1186  game: &str,
1187  batch: &InstallBatch,
1188  installed_at_time: u64,
1189  operation: &Operation,
1190) -> Result<BatchOutcome> {
1191  let before = modlist::read(target_dir).ok();
1192  let shared_eco = Arc::new(eco.clone());
1193  let mut outcome = BatchOutcome::default();
1194
1195  for full_name in &batch.desired {
1196    if operation.is_cancelled() {
1197      outcome.cancelled.push(full_name.clone());
1198
1199      continue;
1200    }
1201
1202    match install_one(
1203      target_dir,
1204      cache_base,
1205      &shared_eco,
1206      index,
1207      client,
1208      game,
1209      full_name,
1210      &batch.desired,
1211      batch.force,
1212      installed_at_time,
1213      operation,
1214    )
1215    .await
1216    {
1217      Ok(closure) => {
1218        outcome.succeeded.extend(closure.installed);
1219        outcome.unchanged.extend(closure.unchanged);
1220        outcome.cancelled.extend(closure.cancelled);
1221      }
1222      Err(error) => outcome.failed.push((full_name.clone(), error)),
1223    }
1224  }
1225
1226  outcome.succeeded.sort();
1227  outcome.succeeded.dedup();
1228
1229  let restore_failures = reapply_each_disabled(target_dir, eco, game, batch, &outcome.succeeded);
1230
1231  outcome.failed.extend(restore_failures);
1232  outcome.unchanged.sort();
1233  outcome.unchanged.dedup();
1234  outcome
1235    .unchanged
1236    .retain(|name| outcome.succeeded.binary_search(name).is_err());
1237
1238  // A reinstalled mod is already enabled; only one skipped as current can still
1239  // carry the disabled state the caller asked to clear.
1240  let to_enable = batch
1241    .enable_requested
1242    .iter()
1243    .filter(|full_name| outcome.unchanged.binary_search(full_name).is_ok());
1244
1245  match modlist::read(target_dir) {
1246    Ok(recorded) => {
1247      for full_name in to_enable {
1248        if modlist::find(&recorded, full_name).is_some_and(|entry| !entry.enabled)
1249          && let Err(error) = set_enabled_in(target_dir, eco, game, full_name, true)
1250        {
1251          outcome.failed.push((full_name.clone(), error));
1252        }
1253      }
1254    }
1255    Err(error) => {
1256      let unconfirmed: Vec<_> = to_enable
1257        .map(|full_name| (full_name.clone(), error.clone()))
1258        .collect();
1259
1260      outcome.failed.extend(unconfirmed);
1261    }
1262  }
1263
1264  // A mod whose enable failed is reported as failed, not also as unchanged.
1265  let failed: BTreeSet<&String> = outcome.failed.iter().map(|(name, _)| name).collect();
1266
1267  outcome.unchanged.retain(|name| !failed.contains(name));
1268
1269  if let Ok(after) = modlist::read(target_dir) {
1270    (outcome.re_enabled, outcome.kept_disabled) = enabled_state_changes(
1271      before.as_deref(),
1272      &after,
1273      &batch.protect_disabled,
1274      &outcome.succeeded,
1275    );
1276  }
1277
1278  Ok(outcome)
1279}
1280
1281/// [`reapply_batch_disabled`] for a batch outcome: every protected mod is
1282/// attempted, and each one left enabled comes back with the reason. When
1283/// `mods.yml` cannot be read, that is every protected mod in `reinstalled`,
1284/// since its install enabled it.
1285#[cfg(feature = "io")]
1286fn reapply_each_disabled(
1287  target_dir: &Path,
1288  eco: &Ecosystem,
1289  game: &str,
1290  batch: &InstallBatch,
1291  reinstalled: &[String],
1292) -> Vec<(String, Error)> {
1293  let recorded = match modlist::read(target_dir) {
1294    Ok(recorded) => recorded,
1295    Err(error) => {
1296      return batch
1297        .protect_disabled
1298        .iter()
1299        .filter(|full_name| reinstalled.contains(full_name))
1300        .map(|full_name| (full_name.clone(), error.clone()))
1301        .collect();
1302    }
1303  };
1304
1305  batch
1306    .protect_disabled
1307    .iter()
1308    .filter(|full_name| modlist::find(&recorded, full_name).is_some())
1309    .filter_map(|full_name| {
1310      set_enabled_in(target_dir, eco, game, full_name, false)
1311        .err()
1312        .map(|error| (full_name.clone(), error))
1313    })
1314    .collect()
1315}
1316
1317/// The recorded mods disabled in `before` and enabled in `after`, and the
1318/// `protect_disabled` mods in `reinstalled` that are disabled in `after`, each
1319/// sorted. With no `before`, nothing counts as re-enabled.
1320#[cfg(feature = "io")]
1321fn enabled_state_changes(
1322  before: Option<&[ProfileMod]>,
1323  after: &[ProfileMod],
1324  protect_disabled: &[String],
1325  reinstalled: &[String],
1326) -> (Vec<String>, Vec<String>) {
1327  let disabled_before: BTreeSet<&str> = before
1328    .unwrap_or_default()
1329    .iter()
1330    .filter(|entry| !entry.enabled)
1331    .map(|entry| entry.name.as_str())
1332    .collect();
1333
1334  let mut re_enabled: Vec<String> = after
1335    .iter()
1336    .filter(|entry| entry.enabled && disabled_before.contains(entry.name.as_str()))
1337    .map(|entry| entry.name.clone())
1338    .collect();
1339
1340  let mut kept_disabled: Vec<String> = after
1341    .iter()
1342    .filter(|entry| !entry.enabled)
1343    .filter(|entry| protect_disabled.contains(&entry.name) && reinstalled.contains(&entry.name))
1344    .map(|entry| entry.name.clone())
1345    .collect();
1346
1347  re_enabled.sort();
1348  kept_disabled.sort();
1349
1350  (re_enabled, kept_disabled)
1351}
1352
1353/// Installs one mod and its dependency closure, protecting the disabled state of
1354/// every recorded mod it did not name. See [`install_batch`].
1355///
1356/// Returns every `Owner-Name` actually installed, which is the named package
1357/// plus its transitive dependencies. A package already recorded at the version
1358/// that would be installed, with its files still on disk, is skipped and not
1359/// listed, so this is empty when the whole closure is current; use
1360/// [`install_batch`] with [`InstallBatch::force`] to reinstall regardless.
1361///
1362/// `cache_base` must not be `target_dir` or a directory inside it, or extracted
1363/// packages would land inside the installed mod tree.
1364///
1365/// # Errors
1366///
1367/// - [`Error::Http`] or
1368///   [`Error::Download`] if fetching the package or a
1369///   dependency fails.
1370/// - [`Error::UnknownGame`] or [`Error::NoGameProfile`] if `eco` has no
1371///   profile for `game`.
1372/// - [`Error::UnresolvedDependency`] if the package or a dependency is absent
1373///   from `index`, and [`Error::MissingVersion`] if `full_name` names a version
1374///   the index does not have. Nothing is installed in either case.
1375/// - [`Error::Install`] if a package's files cannot be routed.
1376/// - [`Error::Io`] if `target_dir` or `cache_base` cannot be
1377///   written.
1378///
1379/// # Examples
1380///
1381/// ```no_run
1382/// use std::path::Path;
1383/// use thunderstore_engine::client::ThunderstoreClient;
1384/// use thunderstore_engine::ecosystem::Ecosystem;
1385/// use thunderstore_engine::profile::{install_mod_in, modlist};
1386///
1387/// # async fn run() -> thunderstore_engine::Result<()> {
1388/// let client = ThunderstoreClient::builder()
1389///   .community("valheim")
1390///   .cache_dir("/var/cache/my-mod-manager")
1391///   .build()?;
1392///
1393/// let index = client.get_manifest().await?;
1394/// let eco = Ecosystem::bundled();
1395///
1396/// let installed = install_mod_in(
1397///   Path::new("/srv/valheim"),
1398///   Path::new("/var/cache/my-mod-manager"),
1399///   &eco,
1400///   &index,
1401///   &client,
1402///   "valheim",
1403///   "denikson-BepInExPack_Valheim",
1404///   modlist::now_millis(),
1405/// )
1406/// .await?;
1407///
1408/// println!("installed {} packages", installed.len());
1409/// # Ok(())
1410/// # }
1411/// ```
1412#[allow(clippy::too_many_arguments)]
1413#[cfg(feature = "io")]
1414pub async fn install_mod_in(
1415  target_dir: &Path,
1416  cache_base: &Path,
1417  eco: &Ecosystem,
1418  index: &PackageIndex,
1419  client: &ThunderstoreClient,
1420  game: &str,
1421  full_name: &str,
1422  installed_at_time: u64,
1423) -> Result<Vec<String>> {
1424  install_named_in(
1425    target_dir,
1426    cache_base,
1427    eco,
1428    index,
1429    client,
1430    game,
1431    full_name,
1432    false,
1433    installed_at_time,
1434  )
1435  .await
1436}
1437
1438/// Installs one named mod and its dependency closure, surfacing the first
1439/// per-item failure as the error. With `force`, the named mod is reinstalled
1440/// even when `mods.yml` already records its version. Shared by
1441/// [`install_mod_in`] and adoption, which forces the loader reinstall.
1442#[allow(clippy::too_many_arguments)]
1443#[cfg(feature = "io")]
1444pub(crate) async fn install_named_in(
1445  target_dir: &Path,
1446  cache_base: &Path,
1447  eco: &Ecosystem,
1448  index: &PackageIndex,
1449  client: &ThunderstoreClient,
1450  game: &str,
1451  full_name: &str,
1452  force: bool,
1453  installed_at_time: u64,
1454) -> Result<Vec<String>> {
1455  let named = [full_name.to_string()];
1456  let mut batch = plan_install_batch(target_dir, &named, &named)?;
1457
1458  batch.force = force;
1459
1460  let outcome = install_batch(
1461    target_dir,
1462    cache_base,
1463    eco,
1464    index,
1465    client,
1466    game,
1467    &batch,
1468    installed_at_time,
1469  )
1470  .await?;
1471
1472  match outcome.failed.into_iter().next() {
1473    Some((_, error)) => Err(error),
1474    None => Ok(outcome.succeeded),
1475  }
1476}
1477
1478/// Installs a mod and its full dependency closure into an r2modman-layout
1479/// profile, using `base` as both the profile base and the package cache
1480/// base (matching this pipeline's pre-existing behavior). See
1481/// [`install_mod_in`].
1482#[allow(clippy::too_many_arguments)]
1483#[cfg(feature = "io")]
1484pub async fn install_mod(
1485  base: &Path,
1486  eco: &Ecosystem,
1487  index: &PackageIndex,
1488  client: &ThunderstoreClient,
1489  game: &str,
1490  profile_name: &str,
1491  full_name: &str,
1492  installed_at_time: u64,
1493) -> Result<Vec<String>> {
1494  install_mod_in(
1495    &layout::profile_dir(base, game, profile_name),
1496    base,
1497    eco,
1498    index,
1499    client,
1500    game,
1501    full_name,
1502    installed_at_time,
1503  )
1504  .await
1505}
1506
1507/// What an uninstall batch will remove.
1508///
1509/// Mods and loaders are held apart because a caller showing this to a user needs
1510/// to say the loader goes too, and because removing loaders last keeps every
1511/// intermediate state one a user could have reached by hand. Ordinarily there is
1512/// at most one loader, but the registry is keyed on package identity rather than
1513/// game, so nothing rules out a second.
1514#[derive(Debug, Clone, Default)]
1515#[non_exhaustive]
1516pub struct UninstallBatch {
1517  /// Every non-loader identifier to remove, sorted.
1518  pub mods: Vec<String>,
1519  /// Every recognised mod loader to remove, sorted, removed after `mods`.
1520  pub loaders: Vec<String>,
1521  /// Root-relative mod folders the record does not account for.
1522  ///
1523  /// [`uninstall_batch`] keeps all of them unless the caller calls
1524  /// [`UninstallBatch::confirm_untracked`]. With that consent it removes the
1525  /// ones still listed here, so a caller shows this list and trims it to the
1526  /// folders the user agreed to delete.
1527  pub untracked: Vec<PathBuf>,
1528  untracked_confirmed: bool,
1529}
1530
1531impl UninstallBatch {
1532  /// Records that the user agreed to delete the folders in
1533  /// [`UninstallBatch::untracked`]. Without this, [`uninstall_batch`] keeps them.
1534  pub fn confirm_untracked(&mut self) {
1535    self.untracked_confirmed = true;
1536  }
1537
1538  /// Whether [`UninstallBatch::confirm_untracked`] was called.
1539  pub fn untracked_confirmed(&self) -> bool {
1540    self.untracked_confirmed
1541  }
1542}
1543
1544/// Every one of `names` that cannot be removed exactly, with the reason.
1545///
1546/// Separate from [`plan_uninstall_batch`], which refuses outright, so a caller
1547/// can list every problem at once instead of discovering them one at a time. The
1548/// reason is a [`NotRemovable`] rather than an [`Error`] so a caller can word
1549/// each kind of refusal without re-deriving which kind it is.
1550#[cfg(feature = "io")]
1551pub fn check_removable_batch(
1552  target_dir: &Path,
1553  eco: &Ecosystem,
1554  names: &[String],
1555) -> Vec<(String, NotRemovable)> {
1556  names
1557    .iter()
1558    .filter_map(|name| match ensure_removable(target_dir, eco, name) {
1559      Ok(()) => None,
1560      Err(refusal) => Some((name.clone(), refusal)),
1561    })
1562    .collect()
1563}
1564
1565/// Plans an uninstall, refusing before anything is mutated.
1566///
1567/// `names` of `None` means every recorded mod. A name that is not installed, or
1568/// any mod that cannot be removed exactly, is an error rather than a per-item
1569/// failure: this runs before any mutation, so refusing the whole request is what
1570/// keeps a batch from failing partway through.
1571///
1572/// Reads `mods.yml`, each subject's install record, and the namespaced route
1573/// folders, and decides with [`plan_uninstall_batch_from`].
1574#[cfg(feature = "io")]
1575pub fn plan_uninstall_batch(
1576  target_dir: &Path,
1577  eco: &Ecosystem,
1578  game: &str,
1579  names: Option<&[String]>,
1580) -> Result<UninstallBatch> {
1581  let game_profile = eco.require_profile(game)?;
1582
1583  let recorded = modlist::read(target_dir)?;
1584
1585  let mut batch = plan_uninstall_batch_from(
1586    target_dir,
1587    eco,
1588    game,
1589    names,
1590    &recorded,
1591    |name| read_record_state(target_dir, name),
1592    Vec::new(),
1593  )?;
1594
1595  let keep: BTreeSet<String> = recorded.iter().map(|entry| entry.name.clone()).collect();
1596
1597  batch.untracked = crate::install::plan_delisted(game_profile, target_dir, &keep)?;
1598
1599  Ok(batch)
1600}
1601
1602/// Plans an uninstall from already-gathered facts, without touching disk.
1603///
1604/// The rules are [`plan_uninstall_batch`]'s. `recorded` is the target's
1605/// `mods.yml` entries. `record_state` reports each subject's install record (see
1606/// [`RecordState`]), and is called only until the first refusal. `untracked` is
1607/// what the sweep would take, from
1608/// [`plan_delisted_from`](crate::install::plan_delisted_from) with every
1609/// recorded name kept; it is returned as [`UninstallBatch::untracked`].
1610/// `target_dir` only names record paths in a refusal.
1611///
1612/// # Errors
1613///
1614/// [`Error::UnknownGame`] or [`Error::NoGameProfile`] if `eco` has no profile
1615/// for `game`, [`Error::NotInstalled`] if a name in `names` is not recorded,
1616/// and [`Error::Profile`] if a subject cannot be removed exactly.
1617pub fn plan_uninstall_batch_from(
1618  target_dir: &Path,
1619  eco: &Ecosystem,
1620  game: &str,
1621  names: Option<&[String]>,
1622  recorded: &[ProfileMod],
1623  mut record_state: impl FnMut(&str) -> RecordState,
1624  untracked: Vec<PathBuf>,
1625) -> Result<UninstallBatch> {
1626  eco.require_profile(game)?;
1627
1628  let subjects: Vec<String> = match names {
1629    Some(names) => {
1630      for name in names {
1631        if modlist::find(recorded, name).is_none() {
1632          return Err(Error::NotInstalled {
1633            package: name.clone(),
1634          });
1635        }
1636      }
1637
1638      names.to_vec()
1639    }
1640    None => recorded.iter().map(|entry| entry.name.clone()).collect(),
1641  };
1642
1643  for name in &subjects {
1644    if let Err(refusal) = check_removable_from(target_dir, eco, name, record_state(name)) {
1645      return Err(Error::Profile(format!(
1646        "{name} cannot be removed: {refusal}"
1647      )));
1648    }
1649  }
1650
1651  let mut mods: Vec<String> = subjects
1652    .iter()
1653    .filter(|name| eco.modloader_package(name).is_none())
1654    .cloned()
1655    .collect();
1656  let mut loaders: Vec<String> = subjects
1657    .iter()
1658    .filter(|name| eco.modloader_package(name).is_some())
1659    .cloned()
1660    .collect();
1661
1662  mods.sort();
1663  loaders.sort();
1664
1665  Ok(UninstallBatch {
1666    mods,
1667    loaders,
1668    untracked,
1669    untracked_confirmed: false,
1670  })
1671}
1672
1673/// Removes everything `batch` names, loaders last, reporting per-item outcomes.
1674///
1675/// Loaders go last so every intermediate state is coherent. Each folder in
1676/// [`UninstallBatch::untracked`] is then kept and reported in
1677/// [`BatchOutcome::kept_untracked`], unless the caller called
1678/// [`UninstallBatch::confirm_untracked`]. With that consent, each listed
1679/// folder that is still an untracked mod folder is removed; an untracked
1680/// folder the batch does not list is kept, including one that appeared after
1681/// planning. A folder that fails to go is reported in [`BatchOutcome::failed`]
1682/// under its path.
1683///
1684/// Reports nothing and cannot be cancelled; see [`uninstall_batch_with`].
1685#[cfg(feature = "io")]
1686pub fn uninstall_batch(
1687  target_dir: &Path,
1688  eco: &Ecosystem,
1689  game: &str,
1690  batch: &UninstallBatch,
1691) -> Result<BatchOutcome> {
1692  uninstall_batch_with(target_dir, eco, game, batch, &Operation::default())
1693}
1694
1695/// [`uninstall_batch`], reporting each package's [`Stage::Uninstalling`] to
1696/// `operation` and stopping once `operation` is cancelled.
1697///
1698/// A cancel takes effect before the next package: the one being removed
1699/// finishes. The packages not started land in [`BatchOutcome::cancelled`], and
1700/// so does each confirmed untracked folder, since removing them is the last
1701/// step.
1702#[cfg(feature = "io")]
1703pub fn uninstall_batch_with(
1704  target_dir: &Path,
1705  eco: &Ecosystem,
1706  game: &str,
1707  batch: &UninstallBatch,
1708  operation: &Operation,
1709) -> Result<BatchOutcome> {
1710  let mut outcome = BatchOutcome::default();
1711
1712  for full_name in batch.mods.iter().chain(batch.loaders.iter()) {
1713    if operation.is_cancelled() {
1714      outcome.cancelled.push(full_name.clone());
1715
1716      continue;
1717    }
1718
1719    let _uninstalling = operation.stage(full_name, Stage::Uninstalling, None);
1720
1721    match uninstall_mod_in(target_dir, eco, game, full_name) {
1722      Ok(()) => outcome.succeeded.push(full_name.clone()),
1723      Err(error) => outcome.failed.push((full_name.clone(), error)),
1724    }
1725  }
1726
1727  if !batch.untracked_confirmed {
1728    outcome.kept_untracked = batch.untracked.clone();
1729
1730    return Ok(outcome);
1731  }
1732
1733  if batch.untracked.is_empty() {
1734    return Ok(outcome);
1735  }
1736
1737  if operation.is_cancelled() {
1738    let unswept = batch
1739      .untracked
1740      .iter()
1741      .map(|relative| relative.display().to_string());
1742
1743    outcome.cancelled.extend(unswept);
1744
1745    return Ok(outcome);
1746  }
1747
1748  let still_untracked = match still_untracked(target_dir, eco, game) {
1749    Ok(still_untracked) => still_untracked,
1750    Err(error) => {
1751      let unswept = batch
1752        .untracked
1753        .iter()
1754        .map(|relative| (relative.display().to_string(), error.clone()));
1755
1756      outcome.failed.extend(unswept);
1757
1758      return Ok(outcome);
1759    }
1760  };
1761
1762  for relative in still_untracked {
1763    if !batch.untracked.contains(&relative) {
1764      continue;
1765    }
1766
1767    let path = target_dir.join(&relative);
1768
1769    if let Err(error) = std::fs::remove_dir_all(&path) {
1770      outcome.failed.push((
1771        relative.display().to_string(),
1772        crate::util::io_context(format!("removing {}", path.display()), error),
1773      ));
1774    }
1775  }
1776
1777  Ok(outcome)
1778}
1779
1780/// The untracked folders an uninstall sweep may remove now. Re-listed rather
1781/// than trusted: [`UninstallBatch::untracked`] is caller-editable, so only a
1782/// path the sweep itself would pick can be removed through it.
1783#[cfg(feature = "io")]
1784fn still_untracked(target_dir: &Path, eco: &Ecosystem, game: &str) -> Result<Vec<PathBuf>> {
1785  let keep: BTreeSet<String> = modlist::read(target_dir)?
1786    .into_iter()
1787    .map(|entry| entry.name)
1788    .collect();
1789
1790  crate::install::plan_delisted(eco.require_profile(game)?, target_dir, &keep)
1791}
1792
1793/// What a bulk enable or disable will do.
1794///
1795/// Loaders are excluded rather than merely skipped. `set_enabled_in` already
1796/// no-ops a loader, so including one would be harmless, but it would be counted
1797/// as a mod the operation acted on and any summary built from this would overstate
1798/// what happened.
1799#[derive(Debug, Clone, Default)]
1800#[non_exhaustive]
1801pub struct ToggleBatch {
1802  /// Identifiers whose state will change, sorted.
1803  pub changing: Vec<String>,
1804  /// Identifiers already in the requested state, sorted.
1805  pub already: Vec<String>,
1806  /// Recognised loaders, excluded from the toggle entirely, sorted.
1807  pub loaders: Vec<String>,
1808  /// The sense this batch was planned for: `true` to enable, `false` to
1809  /// disable. `set_enabled_batch` applies this instead of taking its own
1810  /// `enabled` argument, so a caller cannot execute a batch against a sense it
1811  /// was not planned for.
1812  pub enabled: bool,
1813}
1814
1815/// Plans a bulk enable or disable. `names` of `None` means every recorded mod.
1816///
1817/// A name in `names` that is not recorded at all is refused outright, in the
1818/// same shape as [`plan_uninstall_batch`]'s refusal, rather than silently
1819/// producing an empty plan: iterating the record and filtering would let an
1820/// unrecorded name simply never appear, indistinguishable from "nothing to
1821/// do".
1822///
1823/// Reads `target_dir`'s `mods.yml` and plans with [`plan_set_enabled_batch_from`].
1824#[cfg(feature = "io")]
1825pub fn plan_set_enabled_batch(
1826  target_dir: &Path,
1827  eco: &Ecosystem,
1828  names: Option<&[String]>,
1829  enabled: bool,
1830) -> Result<ToggleBatch> {
1831  let recorded = modlist::read(target_dir)?;
1832
1833  plan_set_enabled_batch_from(&recorded, eco, names, enabled)
1834}
1835
1836/// Plans a bulk enable or disable against an already-read record, without
1837/// touching disk.
1838///
1839/// The rules are [`plan_set_enabled_batch`]'s; `recorded` is the target's
1840/// `mods.yml` entries.
1841///
1842/// # Errors
1843///
1844/// [`Error::NotInstalled`] if a name in `names` is not recorded.
1845pub fn plan_set_enabled_batch_from(
1846  recorded: &[ProfileMod],
1847  eco: &Ecosystem,
1848  names: Option<&[String]>,
1849  enabled: bool,
1850) -> Result<ToggleBatch> {
1851  if let Some(names) = names {
1852    for name in names {
1853      if modlist::find(recorded, name).is_none() {
1854        return Err(Error::NotInstalled {
1855          package: name.clone(),
1856        });
1857      }
1858    }
1859  }
1860
1861  let mut batch = ToggleBatch {
1862    enabled,
1863    ..ToggleBatch::default()
1864  };
1865
1866  for entry in recorded {
1867    if let Some(names) = names
1868      && !names.iter().any(|name| name == &entry.name)
1869    {
1870      continue;
1871    }
1872
1873    if eco.modloader_package(&entry.name).is_some() {
1874      batch.loaders.push(entry.name.clone());
1875    } else if entry.enabled == enabled {
1876      batch.already.push(entry.name.clone());
1877    } else {
1878      batch.changing.push(entry.name.clone());
1879    }
1880  }
1881
1882  batch.changing.sort();
1883  batch.already.sort();
1884  batch.loaders.sort();
1885
1886  Ok(batch)
1887}
1888
1889/// Applies `batch`, reporting per-item outcomes.
1890///
1891/// One mod's failure does not abort the rest: returning early would leave a
1892/// half-applied toggle with nothing reported. Applies `batch.enabled`, the
1893/// sense it was planned for, rather than taking its own `enabled` argument, so
1894/// the executor cannot disagree with the plan it is executing.
1895///
1896/// Reports nothing and cannot be cancelled; see [`set_enabled_batch_with`].
1897#[cfg(feature = "io")]
1898pub fn set_enabled_batch(
1899  target_dir: &Path,
1900  eco: &Ecosystem,
1901  game: &str,
1902  batch: &ToggleBatch,
1903) -> Result<BatchOutcome> {
1904  set_enabled_batch_with(target_dir, eco, game, batch, &Operation::default())
1905}
1906
1907/// [`set_enabled_batch`], reporting each package's [`Stage::Enabling`] or
1908/// [`Stage::Disabling`] to `operation` and stopping once `operation` is
1909/// cancelled.
1910///
1911/// A cancel takes effect before the next package: the one being toggled
1912/// finishes. The packages not started land in [`BatchOutcome::cancelled`].
1913#[cfg(feature = "io")]
1914pub fn set_enabled_batch_with(
1915  target_dir: &Path,
1916  eco: &Ecosystem,
1917  game: &str,
1918  batch: &ToggleBatch,
1919  operation: &Operation,
1920) -> Result<BatchOutcome> {
1921  let stage = if batch.enabled {
1922    Stage::Enabling
1923  } else {
1924    Stage::Disabling
1925  };
1926  let mut outcome = BatchOutcome::default();
1927
1928  for full_name in &batch.changing {
1929    if operation.is_cancelled() {
1930      outcome.cancelled.push(full_name.clone());
1931
1932      continue;
1933    }
1934
1935    let _toggling = operation.stage(full_name, stage, None);
1936
1937    match set_enabled_in(target_dir, eco, game, full_name, batch.enabled) {
1938      Ok(()) => outcome.succeeded.push(full_name.clone()),
1939      Err(error) => outcome.failed.push((full_name.clone(), error)),
1940    }
1941  }
1942
1943  Ok(outcome)
1944}
1945
1946#[cfg(all(test, feature = "io"))]
1947mod tests {
1948  use super::*;
1949  use crate::ecosystem::Ecosystem;
1950  use crate::install::state_file_path;
1951  use crate::models::Version;
1952  use std::io::{Cursor, Write};
1953  use tempfile::tempdir;
1954  use time::OffsetDateTime;
1955  use zip::write::{FileOptions, ZipWriter};
1956
1957  fn write_file(path: &std::path::Path, bytes: &[u8]) {
1958    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1959    std::fs::File::create(path)
1960      .unwrap()
1961      .write_all(bytes)
1962      .unwrap();
1963  }
1964
1965  fn version(full_name: &str) -> Version {
1966    Version {
1967      name: Some("Mod".to_string()),
1968      full_name: Some(full_name.to_string()),
1969      description: Some("desc".to_string()),
1970      icon: Some("icon.png".to_string()),
1971      version_number: Some("1.2.3".to_string()),
1972      dependencies: vec!["Other-Dep-1.0.0".to_string()],
1973      download_url: Some("https://example.com/dl".to_string()),
1974      downloads: Some(1),
1975      date_created: OffsetDateTime::UNIX_EPOCH,
1976      website_url: Some("https://example.com".to_string()),
1977      is_active: Some(true),
1978      uuid4: Some("u".to_string()),
1979      file_size: Some(1),
1980    }
1981  }
1982
1983  #[test]
1984  fn mod_entry_maps_version_with_r2modman_defaults() {
1985    let entry = mod_entry_from_version("Author-Mod", "Author", &version("Author-Mod"), 123);
1986
1987    assert_eq!(entry.name, "Author-Mod");
1988    assert_eq!(entry.author_name, "Author");
1989    assert_eq!(entry.network_mode, "both");
1990    assert_eq!(entry.package_type, "other");
1991    assert_eq!(entry.install_mode, "managed");
1992    assert_eq!(entry.game_version, "0");
1993    assert_eq!(entry.manifest_version, 1);
1994    assert_eq!(
1995      entry.version_number,
1996      crate::profile::modlist::SemVer {
1997        major: 1,
1998        minor: 2,
1999        patch: 3
2000      }
2001    );
2002    assert_eq!(entry.dependencies, vec!["Other-Dep-1.0.0".to_string()]);
2003    assert_eq!(entry.installed_at_time, 123);
2004    assert!(entry.enabled);
2005  }
2006
2007  #[test]
2008  fn install_extracted_places_files_and_records_mods_yml() {
2009    let eco = Ecosystem::bundled();
2010
2011    let dir = tempdir().unwrap();
2012    let base = dir.path();
2013
2014    let extracted = tempdir().unwrap();
2015    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2016    write_file(&extracted.path().join("manifest.json"), b"{}");
2017
2018    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2019
2020    install_extracted(
2021      base,
2022      &eco,
2023      "valheim",
2024      "Main",
2025      "Author-Mod",
2026      "Author",
2027      &version("Author-Mod"),
2028      extracted.path(),
2029      None,
2030      123,
2031    )
2032    .unwrap();
2033
2034    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2035
2036    assert!(
2037      profile_dir
2038        .join("BepInEx/plugins/Author-Mod/Mod.dll")
2039        .exists()
2040    );
2041
2042    let mods = crate::profile::modlist::read(&profile_dir).unwrap();
2043
2044    assert_eq!(mods.len(), 1);
2045    assert_eq!(mods[0].name, "Author-Mod");
2046    assert!(mods[0].enabled);
2047  }
2048
2049  #[test]
2050  fn uninstall_removes_files_and_mods_yml_entry() {
2051    let eco = Ecosystem::bundled();
2052
2053    let dir = tempdir().unwrap();
2054    let base = dir.path();
2055
2056    let extracted = tempdir().unwrap();
2057    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2058
2059    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2060
2061    install_extracted(
2062      base,
2063      &eco,
2064      "valheim",
2065      "Main",
2066      "Author-Mod",
2067      "Author",
2068      &version("Author-Mod"),
2069      extracted.path(),
2070      None,
2071      1,
2072    )
2073    .unwrap();
2074
2075    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2076
2077    assert!(
2078      profile_dir
2079        .join("BepInEx/plugins/Author-Mod/Mod.dll")
2080        .exists()
2081    );
2082
2083    uninstall_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap();
2084
2085    assert!(!profile_dir.join("BepInEx/plugins/Author-Mod").exists());
2086    assert_eq!(
2087      crate::profile::modlist::read(&profile_dir).unwrap().len(),
2088      0
2089    );
2090  }
2091
2092  #[test]
2093  fn uninstall_refuses_a_mod_whose_install_record_cannot_be_read() {
2094    let eco = Ecosystem::bundled();
2095
2096    let dir = tempdir().unwrap();
2097    let base = dir.path();
2098
2099    let extracted = tempdir().unwrap();
2100    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2101
2102    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2103    install_extracted(
2104      base,
2105      &eco,
2106      "valheim",
2107      "Main",
2108      "Author-Mod",
2109      "Author",
2110      &version("Author-Mod"),
2111      extracted.path(),
2112      None,
2113      1,
2114    )
2115    .unwrap();
2116
2117    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2118
2119    // An ordinary mod routes entirely through its namespaced folder, so it gets
2120    // no tracker of its own. Nothing stops one existing anyway (a stray
2121    // leftover, or one written by hand), so an unparseable one is planted here.
2122    write_file(&state_file_path(&profile_dir, "Author-Mod"), b"not: [valid");
2123
2124    let error = uninstall_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap_err();
2125
2126    // `remove_state_payload` reaches the same unparseable record on its own, but
2127    // only after `remove_mod_folders` has deleted the folder and before `mods.yml`
2128    // is rewritten, which leaves the entry naming files that are already gone.
2129    // Refusing up front is what keeps both sides intact.
2130    assert!(
2131      profile_dir
2132        .join("BepInEx/plugins/Author-Mod/Mod.dll")
2133        .exists(),
2134      "the mod's files must survive a refusal; got error: {error}"
2135    );
2136    assert_eq!(
2137      crate::profile::modlist::read(&profile_dir).unwrap().len(),
2138      1
2139    );
2140  }
2141
2142  #[test]
2143  fn disable_then_enable_updates_disk_and_mods_yml() {
2144    let eco = Ecosystem::bundled();
2145
2146    let dir = tempdir().unwrap();
2147    let base = dir.path();
2148
2149    let extracted = tempdir().unwrap();
2150    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2151
2152    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2153    install_extracted(
2154      base,
2155      &eco,
2156      "valheim",
2157      "Main",
2158      "Author-Mod",
2159      "Author",
2160      &version("Author-Mod"),
2161      extracted.path(),
2162      None,
2163      1,
2164    )
2165    .unwrap();
2166
2167    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2168
2169    disable_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap();
2170
2171    assert!(
2172      profile_dir
2173        .join("BepInEx/plugins/Author-Mod/Mod.dll.old")
2174        .exists()
2175    );
2176    assert!(!crate::profile::modlist::read(&profile_dir).unwrap()[0].enabled);
2177
2178    enable_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap();
2179
2180    assert!(
2181      profile_dir
2182        .join("BepInEx/plugins/Author-Mod/Mod.dll")
2183        .exists()
2184    );
2185    assert!(crate::profile::modlist::read(&profile_dir).unwrap()[0].enabled);
2186  }
2187
2188  #[test]
2189  fn disable_leaves_files_alone_when_the_install_record_cannot_be_read() {
2190    let eco = Ecosystem::bundled();
2191
2192    let dir = tempdir().unwrap();
2193    let base = dir.path();
2194
2195    let extracted = tempdir().unwrap();
2196    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2197
2198    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2199    install_extracted(
2200      base,
2201      &eco,
2202      "valheim",
2203      "Main",
2204      "Author-Mod",
2205      "Author",
2206      &version("Author-Mod"),
2207      extracted.path(),
2208      None,
2209      1,
2210    )
2211    .unwrap();
2212
2213    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2214
2215    write_file(&state_file_path(&profile_dir, "Author-Mod"), b"not: [valid");
2216
2217    let error = disable_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap_err();
2218
2219    // An unreadable record already refused a disable, but only once the `.old`
2220    // rename pass had run, and `mods.yml` is written last of all. That left the
2221    // files disabled on disk and the entry still claiming `enabled`. Reading the
2222    // record up front is what keeps the two in step.
2223    assert!(
2224      profile_dir
2225        .join("BepInEx/plugins/Author-Mod/Mod.dll")
2226        .exists(),
2227      "the mod's files must be left as they were; got error: {error}"
2228    );
2229    assert!(
2230      !profile_dir
2231        .join("BepInEx/plugins/Author-Mod/Mod.dll.old")
2232        .exists()
2233    );
2234    assert!(crate::profile::modlist::read(&profile_dir).unwrap()[0].enabled);
2235  }
2236
2237  #[test]
2238  fn disable_mod_is_noop_for_modloader_pack() {
2239    let eco = Ecosystem::bundled();
2240
2241    let dir = tempdir().unwrap();
2242    let base = dir.path();
2243    let full_name = "denikson-BepInExPack_Valheim";
2244
2245    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2246
2247    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2248    let loader_file = profile_dir.join("winhttp.dll");
2249
2250    write_file(&loader_file, b"dll");
2251
2252    let mut mods = Vec::new();
2253
2254    modlist::upsert(
2255      &mut mods,
2256      mod_entry_from_version(full_name, "denikson", &version(full_name), 1),
2257    );
2258    modlist::write(&profile_dir, &mods).unwrap();
2259
2260    let tracker = crate::install::ModFileTracker {
2261      mod_name: full_name.to_string(),
2262      files: vec![("unused-cache-source".to_string(), "winhttp.dll".to_string())],
2263    };
2264
2265    write_state_file(&profile_dir, &tracker).unwrap();
2266
2267    disable_mod(base, &eco, "valheim", "Main", full_name).unwrap();
2268
2269    assert!(loader_file.exists());
2270    assert!(crate::profile::modlist::read(&profile_dir).unwrap()[0].enabled);
2271  }
2272
2273  #[test]
2274  fn install_mod_fails_on_unresolved_dependency() {
2275    let eco = Ecosystem::bundled();
2276
2277    let package = crate::models::Package {
2278      name: Some("Mod".to_string()),
2279      full_name: Some("Author-Mod".to_string()),
2280      owner: Some("Author".to_string()),
2281      package_url: Some("https://example.com/Author-Mod".to_string()),
2282      date_created: OffsetDateTime::UNIX_EPOCH,
2283      date_updated: OffsetDateTime::UNIX_EPOCH,
2284      uuid4: Some("u".to_string()),
2285      rating_score: Some(0),
2286      is_pinned: Some(false),
2287      is_deprecated: Some(false),
2288      has_nsfw_content: Some(false),
2289      categories: vec![],
2290      versions: vec![Version {
2291        dependencies: vec!["Missing-Dep-1.0.0".to_string()],
2292        ..version("Author-Mod")
2293      }],
2294    };
2295
2296    let index: PackageIndex = vec![package].into();
2297
2298    let dir = tempdir().unwrap();
2299    let base = dir.path();
2300    let cache_dir = tempdir().unwrap();
2301
2302    let client = ThunderstoreClient::builder()
2303      .package_index_url("http://localhost/pkg/")
2304      .cache_dir(cache_dir.path())
2305      .build()
2306      .unwrap();
2307
2308    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2309
2310    let rt = tokio::runtime::Runtime::new().unwrap();
2311    let result = rt.block_on(install_mod(
2312      base,
2313      &eco,
2314      &index,
2315      &client,
2316      "valheim",
2317      "Main",
2318      "Author-Mod",
2319      1,
2320    ));
2321
2322    let err = result.unwrap_err();
2323
2324    assert!(
2325      matches!(
2326        &err,
2327        Error::UnresolvedDependency { package, unresolved }
2328          if package == "Author-Mod" && unresolved == &["Missing-Dep".to_string()]
2329      ),
2330      "unexpected error: {err}"
2331    );
2332    assert_eq!(
2333      err.to_string(),
2334      "Profile error: cannot install Author-Mod: could not resolve Missing-Dep"
2335    );
2336  }
2337
2338  #[test]
2339  fn server_mode_lifecycle_against_bare_target_dir() {
2340    let eco = Ecosystem::bundled();
2341
2342    let dir = tempdir().unwrap();
2343    let target_dir = dir.path();
2344
2345    let extracted = tempdir().unwrap();
2346    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2347
2348    install_extracted_in(
2349      target_dir,
2350      &eco,
2351      "valheim",
2352      "Author-Mod",
2353      "Author",
2354      &version("Author-Mod"),
2355      extracted.path(),
2356      None,
2357      123,
2358    )
2359    .unwrap();
2360
2361    assert!(
2362      target_dir
2363        .join("BepInEx/plugins/Author-Mod/Mod.dll")
2364        .exists()
2365    );
2366    assert!(target_dir.join("mods.yml").exists());
2367
2368    let mods = modlist::read(target_dir).unwrap();
2369
2370    assert_eq!(mods.len(), 1);
2371    assert_eq!(mods[0].name, "Author-Mod");
2372    assert!(mods[0].enabled);
2373
2374    // Simulate a `State`-tracked file alongside the `Subdir`-tracked plugin
2375    // above (e.g. a MelonLoader-style loose `.dll`), proving `_state` I/O
2376    // resolves entirely against `target_dir` with no r2modman profile layout
2377    // involved: the source is a real file so enable's restore-from-cache
2378    // copy succeeds, and the dest starts out present so disable's removal is
2379    // a real effect, not a no-op.
2380    let state_source = extracted
2381      .path()
2382      .join("cache/Author-Mod/1.0.0/state-dest.txt");
2383
2384    write_file(&state_source, b"state-data");
2385    write_file(&target_dir.join("state-dest.txt"), b"state-data");
2386
2387    let tracker = crate::install::ModFileTracker {
2388      mod_name: "Author-Mod".to_string(),
2389      files: vec![(
2390        state_source.to_string_lossy().to_string(),
2391        "state-dest.txt".to_string(),
2392      )],
2393    };
2394
2395    write_state_file(target_dir, &tracker).unwrap();
2396
2397    assert!(state_file_path(target_dir, "Author-Mod").exists());
2398
2399    disable_mod_in(target_dir, &eco, "valheim", "Author-Mod").unwrap();
2400
2401    assert!(
2402      target_dir
2403        .join("BepInEx/plugins/Author-Mod/Mod.dll.old")
2404        .exists()
2405    );
2406    assert!(!target_dir.join("state-dest.txt").exists());
2407    assert!(!modlist::read(target_dir).unwrap()[0].enabled);
2408
2409    enable_mod_in(target_dir, &eco, "valheim", "Author-Mod").unwrap();
2410
2411    assert!(
2412      target_dir
2413        .join("BepInEx/plugins/Author-Mod/Mod.dll")
2414        .exists()
2415    );
2416    assert!(target_dir.join("state-dest.txt").exists());
2417    assert!(modlist::read(target_dir).unwrap()[0].enabled);
2418
2419    uninstall_mod_in(target_dir, &eco, "valheim", "Author-Mod").unwrap();
2420
2421    assert!(!target_dir.join("BepInEx/plugins/Author-Mod").exists());
2422    // The `State`-tracked payload lives under a shared route, so
2423    // `remove_mod_folders` never removes it. Uninstall must remove it from the
2424    // `_state` record before discarding that record, or the file would be
2425    // orphaned untracked.
2426    assert!(!target_dir.join("state-dest.txt").exists());
2427    assert!(!state_file_path(target_dir, "Author-Mod").exists());
2428    assert_eq!(modlist::read(target_dir).unwrap().len(), 0);
2429  }
2430
2431  fn build_mod_zip() -> Vec<u8> {
2432    let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
2433    let opts: FileOptions<'_, ()> =
2434      FileOptions::default().compression_method(zip::CompressionMethod::Stored);
2435
2436    for (name, body) in [
2437      ("manifest.json", &b"{\"version_number\":\"1.0.0\"}"[..]),
2438      ("plugins/CoolMod.dll", &b"dll-bytes"[..]),
2439    ] {
2440      zip.start_file(name, opts).unwrap();
2441      zip.write_all(body).unwrap();
2442    }
2443
2444    zip.finish().unwrap().into_inner()
2445  }
2446
2447  fn index_json(server_url: &str) -> String {
2448    format!(
2449      r#"[{{"name":"CoolMod","full_name":"Author-CoolMod","owner":"Author","package_url":"https://example.com/CoolMod","date_created":"2024-01-01T12:00:00Z","date_updated":"2024-01-02T12:00:00Z","uuid4":"pkg","rating_score":1,"is_pinned":false,"is_deprecated":false,"has_nsfw_content":false,"categories":[],"versions":[{{"name":"CoolMod","full_name":"Author-CoolMod","description":"A cool mod","icon":"icon.png","version_number":"1.0.0","dependencies":[],"download_url":"{server_url}/dl/mod.zip","downloads":1,"date_created":"2024-01-01T12:00:00Z","website_url":"","is_active":true,"uuid4":"ver","file_size":1024}}]}}]"#
2450    )
2451  }
2452
2453  #[test]
2454  fn install_mod_in_extracts_into_cache_base_not_target_dir() {
2455    let mut server = mockito::Server::new();
2456    let zip_bytes = build_mod_zip();
2457
2458    let dl = server
2459      .mock("GET", "/dl/mod.zip")
2460      .with_status(200)
2461      .with_header("Content-Type", "application/zip")
2462      .with_body(zip_bytes)
2463      .create();
2464    let idx = server
2465      .mock("GET", "/pkg/")
2466      .with_status(200)
2467      .with_header("Content-Type", "application/json")
2468      .with_header("Last-Modified", "Wed, 21 Feb 2024 15:30:45 GMT")
2469      .with_body(index_json(&server.url()))
2470      .create();
2471
2472    let http_cache = tempdir().unwrap();
2473    let cache_base = tempdir().unwrap();
2474    let target = tempdir().unwrap();
2475
2476    let client = ThunderstoreClient::builder()
2477      .package_index_url(format!("{}/pkg/", server.url()))
2478      .cache_dir(http_cache.path())
2479      .build()
2480      .unwrap();
2481
2482    let rt = tokio::runtime::Runtime::new().unwrap();
2483    let eco = Ecosystem::bundled();
2484    let index = rt.block_on(client.get_manifest()).unwrap();
2485
2486    let installed = rt
2487      .block_on(install_mod_in(
2488        target.path(),
2489        cache_base.path(),
2490        &eco,
2491        &index,
2492        &client,
2493        "valheim",
2494        "Author-CoolMod",
2495        123,
2496      ))
2497      .unwrap();
2498
2499    assert_eq!(installed, vec!["Author-CoolMod".to_string()]);
2500
2501    assert!(
2502      target
2503        .path()
2504        .join("BepInEx/plugins/Author-CoolMod/CoolMod.dll")
2505        .exists()
2506    );
2507
2508    let cached = cache::package_cache_dir(cache_base.path(), "valheim", "Author-CoolMod", "1.0.0");
2509
2510    assert!(cached.join("plugins/CoolMod.dll").exists());
2511    assert!(!target.path().join("cache").exists());
2512
2513    dl.assert();
2514    idx.assert();
2515  }
2516
2517  /// Builds a minimal [`ProfileMod`] for a hand-built `mods.yml` entry.
2518  /// `ProfileMod` does not derive `Default`, so every field is filled with a
2519  /// plausible value.
2520  fn profile_mod(name: &str) -> ProfileMod {
2521    ProfileMod {
2522      manifest_version: 1,
2523      name: name.to_string(),
2524      author_name: String::new(),
2525      website_url: String::new(),
2526      display_name: name.to_string(),
2527      description: String::new(),
2528      game_version: "0".to_string(),
2529      network_mode: "both".to_string(),
2530      package_type: "other".to_string(),
2531      install_mode: "managed".to_string(),
2532      installed_at_time: 1,
2533      loaders: Vec::new(),
2534      dependencies: Vec::new(),
2535      incompatibilities: Vec::new(),
2536      optional_dependencies: Vec::new(),
2537      version_number: SemVer::parse("1.0.0"),
2538      enabled: true,
2539      icon: String::new(),
2540      online_source: false,
2541      trusted_package: false,
2542    }
2543  }
2544
2545  #[test]
2546  fn uninstalling_a_loader_pack_without_a_state_file_is_refused() {
2547    let dir = tempdir().unwrap();
2548    let target_dir = dir.path();
2549    let eco = crate::ecosystem::Ecosystem::bundled();
2550
2551    // A `mods.yml` naming the loader, with no `_state` tracker beside it: the
2552    // shape `import_r2modman_dir` leaves behind, since r2modman never wrote
2553    // this engine's tracker.
2554    modlist::write(target_dir, &[profile_mod("denikson-BepInExPack_Valheim")]).unwrap();
2555
2556    let result = uninstall_mod_in(target_dir, &eco, "valheim", "denikson-BepInExPack_Valheim");
2557
2558    assert!(result.is_err());
2559
2560    let message = result.unwrap_err().to_string();
2561
2562    assert!(
2563      message.contains("denikson-BepInExPack_Valheim"),
2564      "the error must name the loader; got: {message}"
2565    );
2566    // Refusing must leave the record intact rather than dropping it, which is
2567    // the orphaning this guard exists to prevent.
2568    assert_eq!(modlist::read(target_dir).unwrap().len(), 1);
2569  }
2570
2571  #[test]
2572  fn uninstalling_a_regular_mod_without_a_state_file_still_works() {
2573    let dir = tempdir().unwrap();
2574    let target_dir = dir.path();
2575    let eco = crate::ecosystem::Ecosystem::bundled();
2576
2577    // Valheim's install rules are `subdir` and `none` only, so a regular mod
2578    // never has a `_state` file. That must stay a normal uninstall.
2579    modlist::write(target_dir, &[profile_mod("Owner-Regular")]).unwrap();
2580
2581    uninstall_mod_in(target_dir, &eco, "valheim", "Owner-Regular").unwrap();
2582
2583    assert!(modlist::read(target_dir).unwrap().is_empty());
2584  }
2585
2586  #[test]
2587  fn check_removable_batch_reports_every_unremovable_name_with_its_reason() {
2588    let dir = tempdir().unwrap();
2589    let target_dir = dir.path();
2590    let eco = crate::ecosystem::Ecosystem::bundled();
2591
2592    modlist::write(
2593      target_dir,
2594      &[
2595        profile_mod("denikson-BepInExPack_Valheim"),
2596        profile_mod("Owner-Regular"),
2597      ],
2598    )
2599    .unwrap();
2600
2601    // The loader has no `_state` tracker at all: adopted from disk rather than
2602    // installed, so which files it placed is unknown.
2603    //
2604    // The regular mod's `_state` file is present but unparseable: a stray
2605    // leftover or a hand edit, so its contents are unreadable rather than
2606    // absent. Different reason, same "cannot be removed exactly" outcome.
2607    let state_path = crate::install::state_file_path(target_dir, "Owner-Regular");
2608
2609    std::fs::create_dir_all(state_path.parent().unwrap()).unwrap();
2610    std::fs::write(&state_path, "not: [valid").unwrap();
2611
2612    let names = vec![
2613      "denikson-BepInExPack_Valheim".to_string(),
2614      "Owner-Regular".to_string(),
2615    ];
2616
2617    let blocked = check_removable_batch(target_dir, &eco, &names);
2618
2619    assert_eq!(
2620      blocked.len(),
2621      2,
2622      "both un-removable names must be reported, not just the first; got {blocked:?}"
2623    );
2624
2625    let loader_refusal = blocked
2626      .iter()
2627      .find(|(name, _)| name == "denikson-BepInExPack_Valheim")
2628      .map(|(_, refusal)| refusal)
2629      .unwrap();
2630    let loader_path = state_file_path(target_dir, "denikson-BepInExPack_Valheim");
2631
2632    // The reason is returned rather than flattened into a sentence, so a caller
2633    // decides what to advise from the variant instead of re-statting the record.
2634    assert!(
2635      matches!(loader_refusal, NotRemovable::RecordAbsent { path, .. } if path == &loader_path),
2636      "expected an absent record carrying its expected path; got: {loader_refusal:?}"
2637    );
2638
2639    let regular_refusal = blocked
2640      .iter()
2641      .find(|(name, _)| name == "Owner-Regular")
2642      .map(|(_, refusal)| refusal)
2643      .unwrap();
2644
2645    assert!(
2646      matches!(regular_refusal, NotRemovable::RecordUnreadable { path, .. } if path == &state_path),
2647      "expected an unreadable record carrying the path it could not read; got: {regular_refusal:?}"
2648    );
2649  }
2650
2651  #[test]
2652  fn a_removability_refusal_keeps_todays_wording_when_it_becomes_an_error() {
2653    let dir = tempdir().unwrap();
2654    let target_dir = dir.path();
2655    let eco = crate::ecosystem::Ecosystem::bundled();
2656
2657    modlist::write(target_dir, &[profile_mod("denikson-BepInExPack_Valheim")]).unwrap();
2658
2659    let refusal = ensure_removable(target_dir, &eco, "denikson-BepInExPack_Valheim").unwrap_err();
2660    let path = state_file_path(target_dir, "denikson-BepInExPack_Valheim");
2661
2662    // `uninstall_mod_in` propagates this refusal with `?`, so the sentence a
2663    // caller without its own wording sees has to survive the conversion intact.
2664    assert_eq!(
2665      Error::from(refusal).to_string(),
2666      format!(
2667        "Profile error: denikson-BepInExPack_Valheim is a mod loader with no \
2668         install record at {}, so its files cannot be removed exactly. Reinstall \
2669         it, then uninstall it again, or remove its files by hand.",
2670        path.display()
2671      )
2672    );
2673  }
2674
2675  #[test]
2676  fn a_reinstall_the_caller_did_not_name_keeps_its_disabled_state() {
2677    let eco = Ecosystem::bundled();
2678    let dir = tempdir().unwrap();
2679    let base = dir.path();
2680
2681    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2682
2683    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2684    let extracted = tempdir().unwrap();
2685
2686    write_file(&extracted.path().join("plugins/Base.dll"), b"dll");
2687
2688    install_extracted(
2689      base,
2690      &eco,
2691      "valheim",
2692      "Main",
2693      "Author-Base",
2694      "Author",
2695      &version("Author-Base"),
2696      extracted.path(),
2697      None,
2698      1,
2699    )
2700    .unwrap();
2701
2702    disable_mod(base, &eco, "valheim", "Main", "Author-Base").unwrap();
2703
2704    assert!(!modlist::read(&profile_dir).unwrap()[0].enabled);
2705    assert!(
2706      profile_dir
2707        .join("BepInEx/plugins/Author-Base/Base.dll.old")
2708        .exists(),
2709      "the disable must have suffixed the file, or this test proves nothing"
2710    );
2711
2712    // Reinstalling Author-Base the way a dependency closure would: not named by
2713    // the user, so its disabled state must survive.
2714    let batch = plan_install_batch(&profile_dir, &["Author-Base".to_string()], &[]).unwrap();
2715
2716    assert_eq!(batch.protect_disabled, vec!["Author-Base".to_string()]);
2717
2718    install_extracted(
2719      base,
2720      &eco,
2721      "valheim",
2722      "Main",
2723      "Author-Base",
2724      "Author",
2725      &version("Author-Base"),
2726      extracted.path(),
2727      None,
2728      2,
2729    )
2730    .unwrap();
2731
2732    reapply_batch_disabled(&profile_dir, &eco, "valheim", &batch).unwrap();
2733
2734    let mods = modlist::read(&profile_dir).unwrap();
2735
2736    assert!(
2737      !mods[0].enabled,
2738      "a disabled dependency must not be re-enabled by an incidental reinstall"
2739    );
2740    assert!(
2741      profile_dir
2742        .join("BepInEx/plugins/Author-Base/Base.dll.old")
2743        .exists(),
2744      "the file must be left suffixed, not rewritten un-suffixed and orphaned"
2745    );
2746  }
2747
2748  #[test]
2749  fn planning_an_uninstall_batch_partitions_loaders_and_lists_untracked() {
2750    let eco = Ecosystem::bundled();
2751    let dir = tempdir().unwrap();
2752    let base = dir.path();
2753
2754    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2755
2756    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2757    let extracted = tempdir().unwrap();
2758
2759    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2760    install_extracted(
2761      base,
2762      &eco,
2763      "valheim",
2764      "Main",
2765      "Author-Mod",
2766      "Author",
2767      &version("Author-Mod"),
2768      extracted.path(),
2769      None,
2770      1,
2771    )
2772    .unwrap();
2773
2774    // A folder mods.yml never recorded, which the sweep would take along.
2775    write_file(
2776      &profile_dir.join("BepInEx/plugins/Other-ByHand/x.dll"),
2777      b"dll",
2778    );
2779    // Not `<Owner-Name>`-shaped, so the sweep ignores it and the plan must too.
2780    write_file(&profile_dir.join("BepInEx/plugins/MMHOOK/h.dll"), b"dll");
2781
2782    let batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
2783
2784    assert_eq!(batch.mods, vec!["Author-Mod".to_string()]);
2785    assert!(batch.loaders.is_empty());
2786    assert_eq!(
2787      batch.untracked,
2788      vec![std::path::PathBuf::from("BepInEx/plugins/Other-ByHand")]
2789    );
2790
2791    let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
2792
2793    assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
2794    assert_eq!(outcome.succeeded, vec!["Author-Mod".to_string()]);
2795    assert!(modlist::read(&profile_dir).unwrap().is_empty());
2796    assert!(profile_dir.join("BepInEx/plugins/MMHOOK/h.dll").exists());
2797  }
2798
2799  #[test]
2800  fn an_uninstall_batch_keeps_untracked_folders_unless_confirmed() {
2801    let eco = Ecosystem::bundled();
2802    let dir = tempdir().unwrap();
2803    let base = dir.path();
2804
2805    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2806
2807    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2808    let plugins = profile_dir.join("BepInEx/plugins");
2809
2810    install_plugin(base, &eco, "Author-Gone");
2811    write_file(&plugins.join("Other-ByHand/x.dll"), b"dll");
2812
2813    let batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
2814
2815    assert_eq!(
2816      batch.untracked,
2817      vec![PathBuf::from("BepInEx/plugins/Other-ByHand")]
2818    );
2819
2820    let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
2821
2822    assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
2823    assert_eq!(outcome.succeeded, vec!["Author-Gone".to_string()]);
2824    assert!(!plugins.join("Author-Gone").exists());
2825    assert!(plugins.join("Other-ByHand/x.dll").exists());
2826    assert_eq!(
2827      outcome.kept_untracked,
2828      vec![PathBuf::from("BepInEx/plugins/Other-ByHand")]
2829    );
2830  }
2831
2832  /// Installs a regular mod called `name` with one plugin into `Main`.
2833  fn install_plugin(base: &Path, eco: &Ecosystem, name: &str) {
2834    let extracted = tempdir().unwrap();
2835
2836    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2837    install_extracted(
2838      base,
2839      eco,
2840      "valheim",
2841      "Main",
2842      name,
2843      "Author",
2844      &version(name),
2845      extracted.path(),
2846      None,
2847      1,
2848    )
2849    .unwrap();
2850  }
2851
2852  #[test]
2853  fn an_uninstall_batch_removes_only_the_untracked_folders_it_names() {
2854    let eco = Ecosystem::bundled();
2855    let dir = tempdir().unwrap();
2856    let base = dir.path();
2857
2858    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2859
2860    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2861    let plugins = profile_dir.join("BepInEx/plugins");
2862
2863    install_plugin(base, &eco, "Author-Gone");
2864    install_plugin(base, &eco, "Author-Kept");
2865    write_file(&plugins.join("Other-Confirmed/x.dll"), b"dll");
2866    write_file(&plugins.join("Other-Declined/x.dll"), b"dll");
2867
2868    let mut batch = plan_uninstall_batch(
2869      &profile_dir,
2870      &eco,
2871      "valheim",
2872      Some(&["Author-Gone".to_string()]),
2873    )
2874    .unwrap();
2875
2876    assert_eq!(
2877      batch.untracked,
2878      vec![
2879        PathBuf::from("BepInEx/plugins/Other-Confirmed"),
2880        PathBuf::from("BepInEx/plugins/Other-Declined"),
2881      ]
2882    );
2883
2884    batch
2885      .untracked
2886      .retain(|path| path.ends_with("Other-Confirmed"));
2887
2888    batch.confirm_untracked();
2889
2890    // Appeared after planning, so the caller never saw it.
2891    write_file(&plugins.join("Other-Late/x.dll"), b"dll");
2892
2893    let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
2894
2895    assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
2896    assert!(outcome.kept_untracked.is_empty());
2897    assert!(!plugins.join("Author-Gone").exists());
2898    assert!(!plugins.join("Other-Confirmed").exists());
2899    assert!(plugins.join("Author-Kept/Mod.dll").exists());
2900    assert!(plugins.join("Other-Declined/x.dll").exists());
2901    assert!(plugins.join("Other-Late/x.dll").exists());
2902  }
2903
2904  #[test]
2905  fn a_sweep_that_cannot_reread_the_record_keeps_the_outcome_and_the_folders() {
2906    let eco = Ecosystem::bundled();
2907    let dir = tempdir().unwrap();
2908    let base = dir.path();
2909
2910    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2911
2912    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2913    let untracked = profile_dir.join("BepInEx/plugins/Other-Confirmed");
2914
2915    write_file(&untracked.join("x.dll"), b"dll");
2916
2917    let mut batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
2918
2919    batch.confirm_untracked();
2920    write_file(&profile_dir.join("mods.yml"), b"- [unclosed");
2921
2922    let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
2923    let failed: Vec<PathBuf> = outcome
2924      .failed
2925      .iter()
2926      .map(|(name, _)| PathBuf::from(name))
2927      .collect();
2928
2929    assert_eq!(failed, [PathBuf::from("BepInEx/plugins/Other-Confirmed")]);
2930    assert!(untracked.join("x.dll").exists());
2931  }
2932
2933  #[test]
2934  fn uninstalling_one_mod_leaves_folders_the_record_does_not_name() {
2935    let eco = Ecosystem::bundled();
2936    let dir = tempdir().unwrap();
2937    let base = dir.path();
2938
2939    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2940
2941    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2942    let plugins = profile_dir.join("BepInEx/plugins");
2943
2944    install_plugin(base, &eco, "Author-Gone");
2945    write_file(&plugins.join("Other-ByHand/x.dll"), b"dll");
2946
2947    uninstall_mod(base, &eco, "valheim", "Main", "Author-Gone").unwrap();
2948
2949    assert!(!plugins.join("Author-Gone").exists());
2950    assert!(plugins.join("Other-ByHand/x.dll").exists());
2951    assert!(modlist::read(&profile_dir).unwrap().is_empty());
2952  }
2953
2954  #[test]
2955  fn uninstalling_a_name_the_record_lacks_is_refused_before_anything_is_removed() {
2956    let eco = Ecosystem::bundled();
2957    let dir = tempdir().unwrap();
2958    let base = dir.path();
2959
2960    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2961
2962    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2963    let plugins = profile_dir.join("BepInEx/plugins");
2964
2965    install_plugin(base, &eco, "Author-Kept");
2966    write_file(&plugins.join("Other-ByHand/x.dll"), b"dll");
2967
2968    for name in ["Other-ByHand", "author-kept"] {
2969      let refused = uninstall_mod(base, &eco, "valheim", "Main", name).unwrap_err();
2970
2971      assert!(
2972        matches!(&refused, Error::NotInstalled { package } if package == name),
2973        "got: {refused:?}"
2974      );
2975    }
2976
2977    assert!(plugins.join("Other-ByHand/x.dll").exists());
2978    assert!(plugins.join("Author-Kept").exists());
2979    assert_eq!(modlist::read(&profile_dir).unwrap().len(), 1);
2980  }
2981
2982  #[test]
2983  fn uninstalling_a_batch_removes_the_loader_after_ordinary_mods_and_its_own_files() {
2984    let eco = Ecosystem::bundled();
2985    let dir = tempdir().unwrap();
2986    let base = dir.path();
2987    let loader = "denikson-BepInExPack_Valheim";
2988
2989    crate::profile::layout::create(base, "valheim", "Main").unwrap();
2990
2991    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2992    let extracted = tempdir().unwrap();
2993
2994    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2995    install_extracted(
2996      base,
2997      &eco,
2998      "valheim",
2999      "Main",
3000      "Author-Mod",
3001      "Author",
3002      &version("Author-Mod"),
3003      extracted.path(),
3004      None,
3005      1,
3006    )
3007    .unwrap();
3008
3009    // A recorded loader, fabricated the same way `disable_mod_is_noop_for_modloader_pack`
3010    // does: its files land directly under the profile root, not through
3011    // `install_extracted`, since a real loader package's layout (a
3012    // `rootFolder` wrapper stripped by the download pipeline) is not what
3013    // that helper exercises.
3014    let winhttp = profile_dir.join("winhttp.dll");
3015    let core_dll = profile_dir.join("BepInEx/core/BepInEx.dll");
3016
3017    write_file(&winhttp, b"proxy");
3018    write_file(&core_dll, b"core");
3019
3020    let mut mods = modlist::read(&profile_dir).unwrap();
3021
3022    modlist::upsert(
3023      &mut mods,
3024      mod_entry_from_version(loader, "denikson", &version(loader), 1),
3025    );
3026    modlist::write(&profile_dir, &mods).unwrap();
3027
3028    let tracker = crate::install::ModFileTracker {
3029      mod_name: loader.to_string(),
3030      files: vec![
3031        (
3032          "unused-cache-source-1".to_string(),
3033          "winhttp.dll".to_string(),
3034        ),
3035        (
3036          "unused-cache-source-2".to_string(),
3037          "BepInEx/core/BepInEx.dll".to_string(),
3038        ),
3039      ],
3040    };
3041
3042    write_state_file(&profile_dir, &tracker).unwrap();
3043
3044    let batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
3045
3046    assert_eq!(batch.mods, vec!["Author-Mod".to_string()]);
3047    assert_eq!(batch.loaders, vec![loader.to_string()]);
3048
3049    let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
3050
3051    assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
3052    // `uninstall_batch` chains `batch.mods` before `batch.loaders`, so the
3053    // order items were attempted in is what `succeeded` records them in. Two
3054    // items give no way to observe the timing of one removal relative to the
3055    // other beyond this: there is no shared file or intermediate read that
3056    // would tell mods-then-loader apart from an interleaved or reversed order
3057    // except the order they were pushed onto `succeeded` in, which is exactly
3058    // what this pins.
3059    assert_eq!(
3060      outcome.succeeded,
3061      vec!["Author-Mod".to_string(), loader.to_string()]
3062    );
3063    assert!(modlist::read(&profile_dir).unwrap().is_empty());
3064    // The loader's own `State`-tracked files are gone too, not just its
3065    // `mods.yml` entry.
3066    assert!(!winhttp.exists());
3067    assert!(!core_dll.exists());
3068  }
3069
3070  #[test]
3071  fn planning_an_uninstall_batch_sorts_and_removes_two_recorded_loaders() {
3072    let eco = Ecosystem::bundled();
3073    let dir = tempdir().unwrap();
3074    let base = dir.path();
3075    let first_loader = "denikson-BepInExPack_Valheim";
3076    // A second, unrelated loader pack recognised by the same registry:
3077    // `modloader_package` is a global lookup keyed on package identity, not
3078    // scoped to a game, so nothing about a Valheim profile rules out a second
3079    // recognised loader ending up in its `mods.yml` (a real entry in the
3080    // bundled registry).
3081    let second_loader = "1F31A-BepInEx_Valheim_Full";
3082
3083    crate::profile::layout::create(base, "valheim", "Main").unwrap();
3084
3085    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
3086
3087    let mut mods = Vec::new();
3088
3089    for loader in [first_loader, second_loader] {
3090      modlist::upsert(
3091        &mut mods,
3092        mod_entry_from_version(loader, "owner", &version(loader), 1),
3093      );
3094
3095      // An empty tracker satisfies the install-record precondition without
3096      // claiming ownership of any real file, so removing both loaders cannot
3097      // conflict over shared files.
3098      write_state_file(
3099        &profile_dir,
3100        &crate::install::ModFileTracker {
3101          mod_name: loader.to_string(),
3102          files: Vec::new(),
3103        },
3104      )
3105      .unwrap();
3106    }
3107
3108    modlist::write(&profile_dir, &mods).unwrap();
3109
3110    let batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
3111
3112    assert!(batch.mods.is_empty());
3113    // Sorted, so neither loader is silently dropped by the other overwriting it.
3114    assert_eq!(
3115      batch.loaders,
3116      vec![second_loader.to_string(), first_loader.to_string()]
3117    );
3118
3119    let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
3120
3121    assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
3122    assert!(modlist::read(&profile_dir).unwrap().is_empty());
3123  }
3124
3125  #[test]
3126  fn planning_a_toggle_batch_splits_changing_from_already_and_excludes_loaders() {
3127    let eco = Ecosystem::bundled();
3128    let dir = tempdir().unwrap();
3129    let base = dir.path();
3130    let loader = "denikson-BepInExPack_Valheim";
3131
3132    crate::profile::layout::create(base, "valheim", "Main").unwrap();
3133
3134    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
3135    let extracted = tempdir().unwrap();
3136
3137    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
3138
3139    for name in ["Author-One", "Author-Two"] {
3140      install_extracted(
3141        base,
3142        &eco,
3143        "valheim",
3144        "Main",
3145        name,
3146        "Author",
3147        &version(name),
3148        extracted.path(),
3149        None,
3150        1,
3151      )
3152      .unwrap();
3153    }
3154
3155    // A recorded loader, which has no disabled state and must be excluded.
3156    let mut mods = modlist::read(&profile_dir).unwrap();
3157
3158    mods.push(mod_entry_from_version(
3159      loader,
3160      "denikson",
3161      &version(loader),
3162      1,
3163    ));
3164    modlist::write(&profile_dir, &mods).unwrap();
3165
3166    disable_mod(base, &eco, "valheim", "Main", "Author-One").unwrap();
3167
3168    let batch = plan_set_enabled_batch(&profile_dir, &eco, None, false).unwrap();
3169
3170    assert_eq!(batch.changing, vec!["Author-Two".to_string()]);
3171    assert_eq!(batch.already, vec!["Author-One".to_string()]);
3172    assert_eq!(batch.loaders, vec![loader.to_string()]);
3173
3174    let outcome = set_enabled_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
3175
3176    assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
3177    assert_eq!(outcome.succeeded, vec!["Author-Two".to_string()]);
3178
3179    let after = modlist::read(&profile_dir).unwrap();
3180
3181    assert!(
3182      !after
3183        .iter()
3184        .find(|m| m.name == "Author-Two")
3185        .unwrap()
3186        .enabled
3187    );
3188    // The loader was never touched, so its record still reads enabled.
3189    assert!(after.iter().find(|m| m.name == loader).unwrap().enabled);
3190  }
3191
3192  #[test]
3193  fn plan_set_enabled_batch_refuses_an_unrecorded_name() {
3194    let eco = Ecosystem::bundled();
3195    let dir = tempdir().unwrap();
3196    let base = dir.path();
3197
3198    crate::profile::layout::create(base, "valheim", "Main").unwrap();
3199
3200    let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
3201    let extracted = tempdir().unwrap();
3202
3203    write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
3204
3205    install_extracted(
3206      base,
3207      &eco,
3208      "valheim",
3209      "Main",
3210      "Author-One",
3211      "Author",
3212      &version("Author-One"),
3213      extracted.path(),
3214      None,
3215      1,
3216    )
3217    .unwrap();
3218
3219    let names = vec!["Author-Gone".to_string()];
3220    let error = plan_set_enabled_batch(&profile_dir, &eco, Some(&names), false).unwrap_err();
3221
3222    assert!(error.to_string().contains("Author-Gone"));
3223    assert!(error.to_string().contains("is not installed"));
3224  }
3225
3226  /// Install batches run end to end against a mock Thunderstore: real downloads,
3227  /// extraction, routing and `mods.yml`, so skip, clean and force are checked
3228  /// on disk rather than against a stub.
3229  mod reinstall {
3230    use super::*;
3231    use crate::models::Package;
3232
3233    const MOD: &str = "Author-Mod";
3234    const DEP: &str = "Author-Dep";
3235    const LOADER: &str = "denikson-BepInExPack_Valheim";
3236
3237    /// One published version of a package.
3238    struct Pkg<'a> {
3239      full_name: &'a str,
3240      version: &'a str,
3241      deps: &'a [&'a str],
3242      files: &'a [(&'a str, &'a [u8])],
3243    }
3244
3245    struct Repo {
3246      server: mockito::ServerGuard,
3247      mocks: Vec<mockito::Mock>,
3248      client: ThunderstoreClient,
3249      _http_cache: tempfile::TempDir,
3250      cache_base: tempfile::TempDir,
3251      target: tempfile::TempDir,
3252      eco: Ecosystem,
3253      rt: tokio::runtime::Runtime,
3254      clock: u64,
3255    }
3256
3257    impl Repo {
3258      fn new() -> Self {
3259        let server = mockito::Server::new();
3260        let http_cache = tempdir().unwrap();
3261        let client = ThunderstoreClient::builder()
3262          .package_index_url(format!("{}/pkg/", server.url()))
3263          .cache_dir(http_cache.path())
3264          .build()
3265          .unwrap();
3266
3267        Self {
3268          server,
3269          mocks: Vec::new(),
3270          client,
3271          _http_cache: http_cache,
3272          cache_base: tempdir().unwrap(),
3273          target: tempdir().unwrap(),
3274          eco: Ecosystem::bundled(),
3275          rt: tokio::runtime::Runtime::new().unwrap(),
3276          clock: 0,
3277        }
3278      }
3279
3280      /// Serves each package's archive and returns an index of them. Versions of
3281      /// one package are published in slice order, so the last is the latest.
3282      fn publish(&mut self, pkgs: &[Pkg<'_>]) -> PackageIndex {
3283        let mut packages: Vec<serde_json::Value> = Vec::new();
3284
3285        for (day, pkg) in pkgs.iter().enumerate() {
3286          let path = format!("/dl/{}-{}.zip", pkg.full_name, pkg.version);
3287          let mock = self
3288            .server
3289            .mock("GET", path.as_str())
3290            .with_status(200)
3291            .with_header("Content-Type", "application/zip")
3292            .with_body(zip_of(pkg.files))
3293            .create();
3294
3295          self.mocks.push(mock);
3296
3297          let (owner, name) = pkg.full_name.split_once('-').unwrap();
3298          let created = format!("2024-01-{:02}T12:00:00Z", day + 1);
3299          let version = serde_json::json!({
3300            "name": name, "full_name": pkg.full_name, "description": "d", "icon": "i",
3301            "version_number": pkg.version, "dependencies": pkg.deps,
3302            "download_url": format!("{}{path}", self.server.url()), "downloads": 1,
3303            "date_created": created, "website_url": "", "is_active": true,
3304            "uuid4": "ver", "file_size": 1
3305          });
3306
3307          match packages
3308            .iter_mut()
3309            .find(|p| p["full_name"] == pkg.full_name)
3310          {
3311            Some(package) => package["versions"].as_array_mut().unwrap().push(version),
3312            None => packages.push(serde_json::json!({
3313              "name": name, "full_name": pkg.full_name, "owner": owner,
3314              "package_url": "https://example.com", "date_created": "2024-01-01T12:00:00Z",
3315              "date_updated": "2024-01-02T12:00:00Z", "uuid4": "pkg", "rating_score": 1,
3316              "is_pinned": false, "is_deprecated": false, "has_nsfw_content": false,
3317              "categories": [], "versions": [version]
3318            })),
3319          }
3320        }
3321
3322        let packages = packages
3323          .into_iter()
3324          .map(|json| serde_json::from_value::<Package>(json).unwrap())
3325          .collect::<Vec<_>>();
3326
3327        PackageIndex::from(packages)
3328      }
3329
3330      /// Like [`Self::try_install`], asserting that nothing failed.
3331      fn install(
3332        &mut self,
3333        index: &PackageIndex,
3334        desired: &[&str],
3335        explicit: &[&str],
3336        force: bool,
3337      ) -> BatchOutcome {
3338        let outcome = self.try_install(index, desired, explicit, force);
3339
3340        assert!(outcome.is_ok(), "batch failed: {:?}", outcome.failed);
3341
3342        outcome
3343      }
3344
3345      /// Plans a batch for `desired` (naming `explicit`) and runs it, without
3346      /// asserting that nothing failed.
3347      fn try_install(
3348        &mut self,
3349        index: &PackageIndex,
3350        desired: &[&str],
3351        explicit: &[&str],
3352        force: bool,
3353      ) -> BatchOutcome {
3354        let desired: Vec<String> = desired.iter().map(|s| s.to_string()).collect();
3355        let explicit: Vec<String> = explicit.iter().map(|s| s.to_string()).collect();
3356        let mut batch = plan_install_batch(self.target.path(), &desired, &explicit).unwrap();
3357
3358        batch.force = force;
3359        self.clock += 1;
3360
3361        self
3362          .rt
3363          .block_on(install_batch(
3364            self.target.path(),
3365            self.cache_base.path(),
3366            &self.eco,
3367            index,
3368            &self.client,
3369            "valheim",
3370            &batch,
3371            self.clock,
3372          ))
3373          .unwrap()
3374      }
3375
3376      fn path(&self, rel: &str) -> PathBuf {
3377        self.target.path().join(rel)
3378      }
3379
3380      fn entry(&self, name: &str) -> ProfileMod {
3381        modlist::read(self.target.path())
3382          .unwrap()
3383          .into_iter()
3384          .find(|m| m.name == name)
3385          .unwrap()
3386      }
3387    }
3388
3389    fn zip_of(files: &[(&str, &[u8])]) -> Vec<u8> {
3390      let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
3391      let opts: FileOptions<'_, ()> =
3392        FileOptions::default().compression_method(zip::CompressionMethod::Stored);
3393
3394      for (name, body) in files {
3395        zip.start_file(*name, opts).unwrap();
3396        zip.write_all(body).unwrap();
3397      }
3398
3399      zip.finish().unwrap().into_inner()
3400    }
3401
3402    fn names(list: &[&str]) -> Vec<String> {
3403      list.iter().map(|s| s.to_string()).collect()
3404    }
3405
3406    #[test]
3407    fn an_install_at_the_recorded_version_is_skipped() {
3408      let mut repo = Repo::new();
3409      let index = repo.publish(&[Pkg {
3410        full_name: MOD,
3411        version: "1.0.0",
3412        deps: &[],
3413        files: &[("plugins/Mod.dll", b"v1")],
3414      }]);
3415
3416      repo.install(&index, &[MOD], &[MOD], false);
3417
3418      let user_file = repo.path("BepInEx/plugins/Author-Mod/user.txt");
3419
3420      write_file(&user_file, b"mine");
3421
3422      let installed_at = repo.entry(MOD).installed_at_time;
3423      let outcome = repo.install(&index, &[MOD], &[MOD], false);
3424
3425      assert!(outcome.succeeded.is_empty());
3426      assert_eq!(outcome.unchanged, names(&[MOD]));
3427      assert!(user_file.exists(), "a skipped install must not touch files");
3428      assert_eq!(repo.entry(MOD).installed_at_time, installed_at);
3429    }
3430
3431    #[test]
3432    fn a_version_change_removes_files_only_the_old_version_had() {
3433      let mut repo = Repo::new();
3434      let v1 = repo.publish(&[Pkg {
3435        full_name: MOD,
3436        version: "1.0.0",
3437        deps: &[],
3438        files: &[
3439          ("plugins/Old.dll", b"old"),
3440          ("plugins/german.json", b"flat"),
3441        ],
3442      }]);
3443
3444      repo.install(&v1, &[MOD], &[MOD], false);
3445
3446      assert!(repo.path("BepInEx/plugins/Author-Mod/german.json").exists());
3447
3448      let v2 = repo.publish(&[Pkg {
3449        full_name: MOD,
3450        version: "2.0.0",
3451        deps: &[],
3452        files: &[
3453          ("plugins/Mod.dll", b"new"),
3454          ("plugins/Translations/German/german.json", b"nested"),
3455        ],
3456      }]);
3457      let outcome = repo.install(&v2, &[MOD], &[MOD], false);
3458
3459      assert_eq!(outcome.succeeded, names(&[MOD]));
3460      assert!(!repo.path("BepInEx/plugins/Author-Mod/Old.dll").exists());
3461      assert!(!repo.path("BepInEx/plugins/Author-Mod/german.json").exists());
3462      assert!(
3463        repo
3464          .path("BepInEx/plugins/Author-Mod/Translations/German/german.json")
3465          .exists()
3466      );
3467      assert_eq!(repo.entry(MOD).version_number.to_string(), "2.0.0");
3468    }
3469
3470    #[test]
3471    fn force_reinstalls_the_recorded_version_from_a_clean_folder() {
3472      let mut repo = Repo::new();
3473      let index = repo.publish(&[Pkg {
3474        full_name: MOD,
3475        version: "1.0.0",
3476        deps: &[],
3477        files: &[("plugins/Translations/German/german.json", b"nested")],
3478      }]);
3479
3480      repo.install(&index, &[MOD], &[MOD], false);
3481
3482      // What an install made before nested folders were kept left behind.
3483      let stale = repo.path("BepInEx/plugins/Author-Mod/german.json");
3484
3485      write_file(&stale, b"flat");
3486
3487      let outcome = repo.install(&index, &[MOD], &[MOD], true);
3488
3489      assert_eq!(outcome.succeeded, names(&[MOD]));
3490      assert!(outcome.unchanged.is_empty());
3491      assert!(!stale.exists());
3492      assert!(
3493        repo
3494          .path("BepInEx/plugins/Author-Mod/Translations/German/german.json")
3495          .exists()
3496      );
3497    }
3498
3499    #[test]
3500    fn force_reinstalls_only_the_named_mod_not_its_dependencies() {
3501      let mut repo = Repo::new();
3502      let index = repo.publish(&[
3503        Pkg {
3504          full_name: MOD,
3505          version: "1.0.0",
3506          deps: &["Author-Dep-1.0.0"],
3507          files: &[("plugins/Mod.dll", b"mod")],
3508        },
3509        Pkg {
3510          full_name: DEP,
3511          version: "1.0.0",
3512          deps: &[],
3513          files: &[("plugins/Dep.dll", b"dep")],
3514        },
3515      ]);
3516
3517      repo.install(&index, &[MOD], &[MOD], false);
3518
3519      let dep_marker = repo.path("BepInEx/plugins/Author-Dep/user.txt");
3520
3521      write_file(&dep_marker, b"mine");
3522
3523      let outcome = repo.install(&index, &[MOD], &[MOD], true);
3524
3525      assert_eq!(outcome.succeeded, names(&[MOD]));
3526      assert_eq!(outcome.unchanged, names(&[DEP]));
3527      assert!(
3528        dep_marker.exists(),
3529        "the dependency must not be reinstalled"
3530      );
3531    }
3532
3533    #[test]
3534    fn a_disabled_mod_stays_disabled_through_force_and_an_update() {
3535      let mut repo = Repo::new();
3536      let v1 = repo.publish(&[Pkg {
3537        full_name: MOD,
3538        version: "1.0.0",
3539        deps: &[],
3540        files: &[("plugins/Mod.dll", b"v1"), ("plugins/Old.dll", b"v1")],
3541      }]);
3542
3543      repo.install(&v1, &[MOD], &[MOD], false);
3544
3545      set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3546
3547      // Not named, as an update on the user's behalf runs it.
3548      repo.install(&v1, &[MOD], &[], true);
3549
3550      assert!(!repo.entry(MOD).enabled);
3551      assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll.old").exists());
3552      assert!(!repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3553
3554      let v2 = repo.publish(&[Pkg {
3555        full_name: MOD,
3556        version: "2.0.0",
3557        deps: &[],
3558        files: &[("plugins/Mod.dll", b"v2")],
3559      }]);
3560
3561      repo.install(&v2, &[MOD], &[], false);
3562
3563      assert!(!repo.entry(MOD).enabled);
3564      assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll.old").exists());
3565      assert!(!repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3566      assert!(!repo.path("BepInEx/plugins/Author-Mod/Old.dll.old").exists());
3567    }
3568
3569    #[test]
3570    fn naming_a_disabled_mod_at_its_recorded_version_enables_it() {
3571      let mut repo = Repo::new();
3572      let index = repo.publish(&[Pkg {
3573        full_name: MOD,
3574        version: "1.0.0",
3575        deps: &[],
3576        files: &[("plugins/Mod.dll", b"v1")],
3577      }]);
3578
3579      repo.install(&index, &[MOD], &[MOD], false);
3580
3581      set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3582
3583      let outcome = repo.install(&index, &[MOD], &[MOD], false);
3584
3585      assert_eq!(outcome.unchanged, names(&[MOD]));
3586      assert!(repo.entry(MOD).enabled);
3587      assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3588      assert!(!repo.path("BepInEx/plugins/Author-Mod/Mod.dll.old").exists());
3589    }
3590
3591    #[test]
3592    fn shared_config_survives_force_and_an_update() {
3593      let mut repo = Repo::new();
3594      let v1 = repo.publish(&[Pkg {
3595        full_name: MOD,
3596        version: "1.0.0",
3597        deps: &[],
3598        files: &[("plugins/Mod.dll", b"v1"), ("config/Mod.cfg", b"default")],
3599      }]);
3600
3601      repo.install(&v1, &[MOD], &[MOD], false);
3602
3603      let cfg = repo.path("BepInEx/config/Mod.cfg");
3604
3605      write_file(&cfg, b"edited");
3606      repo.install(&v1, &[MOD], &[MOD], true);
3607
3608      assert_eq!(std::fs::read(&cfg).unwrap(), b"edited");
3609
3610      let v2 = repo.publish(&[Pkg {
3611        full_name: MOD,
3612        version: "2.0.0",
3613        deps: &[],
3614        files: &[("plugins/Mod.dll", b"v2"), ("config/Mod.cfg", b"default")],
3615      }]);
3616
3617      repo.install(&v2, &[MOD], &[MOD], false);
3618
3619      assert_eq!(std::fs::read(&cfg).unwrap(), b"edited");
3620    }
3621
3622    #[test]
3623    fn force_reinstalls_a_loader_pack_and_keeps_its_config() {
3624      let mut repo = Repo::new();
3625      let index = repo.publish(&[Pkg {
3626        full_name: LOADER,
3627        version: "5.4.2333",
3628        deps: &[],
3629        files: &[
3630          ("BepInExPack_Valheim/winhttp.dll", b"proxy"),
3631          ("BepInExPack_Valheim/BepInEx/core/BepInEx.dll", b"core"),
3632          ("BepInExPack_Valheim/BepInEx/config/BepInEx.cfg", b"default"),
3633        ],
3634      }]);
3635
3636      repo.install(&index, &[LOADER], &[LOADER], false);
3637
3638      let cfg = repo.path("BepInEx/config/BepInEx.cfg");
3639      let core = repo.path("BepInEx/core/BepInEx.dll");
3640
3641      write_file(&cfg, b"edited");
3642      write_file(&core, b"tampered");
3643
3644      let outcome = repo.install(&index, &[LOADER], &[LOADER], true);
3645
3646      assert_eq!(outcome.succeeded, names(&[LOADER]));
3647      assert_eq!(std::fs::read(&core).unwrap(), b"core");
3648      assert!(repo.path("winhttp.dll").exists());
3649      assert_eq!(std::fs::read(&cfg).unwrap(), b"edited");
3650      assert!(state_file_path(repo.target.path(), LOADER).exists());
3651    }
3652
3653    #[test]
3654    fn a_recorded_mod_whose_folder_is_gone_is_reinstalled() {
3655      let mut repo = Repo::new();
3656      let index = repo.publish(&[Pkg {
3657        full_name: MOD,
3658        version: "1.0.0",
3659        deps: &[],
3660        files: &[("plugins/Mod.dll", b"v1")],
3661      }]);
3662
3663      repo.install(&index, &[MOD], &[MOD], false);
3664
3665      std::fs::remove_dir_all(repo.path("BepInEx/plugins/Author-Mod")).unwrap();
3666
3667      let outcome = repo.install(&index, &[MOD], &[MOD], false);
3668
3669      assert_eq!(outcome.succeeded, names(&[MOD]));
3670      assert!(outcome.unchanged.is_empty());
3671      assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3672    }
3673
3674    #[test]
3675    fn a_loader_pack_missing_a_tracked_file_is_reinstalled() {
3676      let mut repo = Repo::new();
3677      let index = repo.publish(&[Pkg {
3678        full_name: LOADER,
3679        version: "5.4.2333",
3680        deps: &[],
3681        files: &[
3682          ("BepInExPack_Valheim/winhttp.dll", b"proxy"),
3683          ("BepInExPack_Valheim/BepInEx/core/BepInEx.dll", b"core"),
3684        ],
3685      }]);
3686
3687      repo.install(&index, &[LOADER], &[LOADER], false);
3688
3689      std::fs::remove_file(repo.path("winhttp.dll")).unwrap();
3690
3691      let outcome = repo.install(&index, &[LOADER], &[LOADER], false);
3692
3693      assert_eq!(outcome.succeeded, names(&[LOADER]));
3694      assert!(repo.path("winhttp.dll").exists());
3695    }
3696
3697    #[test]
3698    fn a_recorded_mod_with_no_files_to_place_is_skipped() {
3699      let mut repo = Repo::new();
3700      let index = repo.publish(&[Pkg {
3701        full_name: MOD,
3702        version: "1.0.0",
3703        deps: &[],
3704        files: &[("manifest.json", b"{}"), ("README.md", b"modpack")],
3705      }]);
3706
3707      repo.install(&index, &[MOD], &[MOD], false);
3708
3709      let outcome = repo.install(&index, &[MOD], &[MOD], false);
3710
3711      assert!(outcome.succeeded.is_empty());
3712      assert_eq!(outcome.unchanged, names(&[MOD]));
3713    }
3714
3715    #[cfg(unix)]
3716    #[test]
3717    fn a_failed_enable_is_reported_per_item_without_losing_the_batch() {
3718      use std::os::unix::fs::PermissionsExt;
3719
3720      let mut repo = Repo::new();
3721      let index = repo.publish(&[
3722        Pkg {
3723          full_name: MOD,
3724          version: "1.0.0",
3725          deps: &[],
3726          files: &[("plugins/Mod.dll", b"v1")],
3727        },
3728        Pkg {
3729          full_name: DEP,
3730          version: "1.0.0",
3731          deps: &[],
3732          files: &[("plugins/Dep.dll", b"dep")],
3733        },
3734      ]);
3735
3736      repo.install(&index, &[MOD], &[MOD], false);
3737
3738      set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3739
3740      // A read-only folder makes the `.old` rename fail, as a locked file would.
3741      let folder = repo.path("BepInEx/plugins/Author-Mod");
3742
3743      std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o555)).unwrap();
3744
3745      if std::fs::write(folder.join("probe"), b"").is_ok() {
3746        // Running as root: permissions cannot force the failure.
3747        return;
3748      }
3749
3750      let desired = names(&[MOD, DEP]);
3751      let batch = plan_install_batch(repo.target.path(), &desired, &desired).unwrap();
3752      let result = repo.rt.block_on(install_batch(
3753        repo.target.path(),
3754        repo.cache_base.path(),
3755        &repo.eco,
3756        &index,
3757        &repo.client,
3758        "valheim",
3759        &batch,
3760        1,
3761      ));
3762
3763      std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap();
3764
3765      let outcome = result.expect("a failed enable must not discard the batch");
3766      let failed: Vec<&str> = outcome.failed.iter().map(|(n, _)| n.as_str()).collect();
3767
3768      assert_eq!(failed, vec![MOD]);
3769      assert_eq!(outcome.succeeded, names(&[DEP]));
3770      assert!(outcome.unchanged.is_empty());
3771    }
3772
3773    #[test]
3774    fn a_disabled_mod_not_named_is_still_skipped() {
3775      let mut repo = Repo::new();
3776      let index = repo.publish(&[Pkg {
3777        full_name: MOD,
3778        version: "1.0.0",
3779        deps: &[],
3780        files: &[("plugins/Mod.dll", b"v1")],
3781      }]);
3782
3783      repo.install(&index, &[MOD], &[MOD], false);
3784
3785      set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3786
3787      let outcome = repo.install(&index, &[MOD], &[], false);
3788
3789      assert_eq!(outcome.unchanged, names(&[MOD]));
3790      assert!(!repo.entry(MOD).enabled);
3791      assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll.old").exists());
3792    }
3793
3794    #[test]
3795    fn a_mod_left_half_disabled_is_reinstalled() {
3796      let mut repo = Repo::new();
3797      let index = repo.publish(&[Pkg {
3798        full_name: MOD,
3799        version: "1.0.0",
3800        deps: &[],
3801        files: &[("plugins/Mod.dll", b"v1"), ("plugins/Extra.dll", b"v1")],
3802      }]);
3803
3804      repo.install(&index, &[MOD], &[MOD], false);
3805
3806      // A disable that failed after its first rename: one file toggled, the
3807      // other not, and `mods.yml` still recording the mod as enabled.
3808      let extra = repo.path("BepInEx/plugins/Author-Mod/Extra.dll");
3809
3810      std::fs::rename(
3811        &extra,
3812        repo.path("BepInEx/plugins/Author-Mod/Extra.dll.old"),
3813      )
3814      .unwrap();
3815
3816      let outcome = repo.install(&index, &[MOD], &[MOD], false);
3817
3818      assert_eq!(outcome.succeeded, names(&[MOD]));
3819      assert!(outcome.unchanged.is_empty());
3820      assert!(extra.exists());
3821      assert!(
3822        !repo
3823          .path("BepInEx/plugins/Author-Mod/Extra.dll.old")
3824          .exists()
3825      );
3826      assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3827    }
3828
3829    #[cfg(unix)]
3830    #[test]
3831    fn a_failed_loader_reinstall_keeps_it_uninstallable() {
3832      let mut repo = Repo::new();
3833      let v1 = repo.publish(&[Pkg {
3834        full_name: LOADER,
3835        version: "5.4.2333",
3836        deps: &[],
3837        files: &[
3838          ("BepInExPack_Valheim/winhttp.dll", b"proxy"),
3839          ("BepInExPack_Valheim/BepInEx/core/BepInEx.dll", b"core"),
3840        ],
3841      }]);
3842
3843      repo.install(&v1, &[LOADER], &[LOADER], false);
3844
3845      let v2 = repo.publish(&[Pkg {
3846        full_name: LOADER,
3847        version: "5.4.2334",
3848        deps: &[],
3849        files: &[
3850          ("BepInExPack_Valheim/winhttp.dll", b"proxy"),
3851          ("BepInExPack_Valheim/BepInEx/core/BepInEx.dll", b"core"),
3852          ("BepInExPack_Valheim/BepInEx/core/Extra.dll", b"extra"),
3853        ],
3854      }]);
3855
3856      // A symlink at a destination only the new version writes makes the apply
3857      // refuse after the old payload is already gone.
3858      std::os::unix::fs::symlink(
3859        repo.path("elsewhere.dll"),
3860        repo.path("BepInEx/core/Extra.dll"),
3861      )
3862      .unwrap();
3863
3864      let desired = names(&[LOADER]);
3865      let batch = plan_install_batch(repo.target.path(), &desired, &desired).unwrap();
3866      let outcome = repo
3867        .rt
3868        .block_on(install_batch(
3869          repo.target.path(),
3870          repo.cache_base.path(),
3871          &repo.eco,
3872          &v2,
3873          &repo.client,
3874          "valheim",
3875          &batch,
3876          2,
3877        ))
3878        .unwrap();
3879      let failed: Vec<&str> = outcome.failed.iter().map(|(n, _)| n.as_str()).collect();
3880
3881      assert_eq!(failed, vec![LOADER]);
3882      assert!(state_file_path(repo.target.path(), LOADER).exists());
3883
3884      uninstall_mod_in(repo.target.path(), &repo.eco, "valheim", LOADER).unwrap();
3885
3886      assert!(modlist::read(repo.target.path()).unwrap().is_empty());
3887      assert!(!state_file_path(repo.target.path(), LOADER).exists());
3888    }
3889
3890    fn mod_history<'a>() -> [Pkg<'a>; 2] {
3891      [
3892        Pkg {
3893          full_name: MOD,
3894          version: "1.0.0",
3895          deps: &[],
3896          files: &[("plugins/Mod.dll", b"v1")],
3897        },
3898        Pkg {
3899          full_name: MOD,
3900          version: "2.0.0",
3901          deps: &[],
3902          files: &[("plugins/Mod.dll", b"v2")],
3903        },
3904      ]
3905    }
3906
3907    #[test]
3908    fn a_pinned_install_lands_the_requested_version_not_the_latest() {
3909      let mut repo = Repo::new();
3910      let index = repo.publish(&mod_history());
3911      let dll = repo.path("BepInEx/plugins/Author-Mod/Mod.dll");
3912
3913      let outcome = repo.install(&index, &["Author-Mod-1.0.0"], &["Author-Mod-1.0.0"], false);
3914
3915      assert_eq!(outcome.succeeded, names(&[MOD]));
3916      assert_eq!(repo.entry(MOD).version_number.to_string(), "1.0.0");
3917      assert_eq!(std::fs::read(&dll).unwrap(), b"v1");
3918
3919      repo.install(&index, &[MOD], &[MOD], false);
3920
3921      assert_eq!(repo.entry(MOD).version_number.to_string(), "2.0.0");
3922      assert_eq!(std::fs::read(&dll).unwrap(), b"v2");
3923
3924      repo.install(&index, &["Author-Mod-1.0.0"], &["Author-Mod-1.0.0"], false);
3925
3926      assert_eq!(repo.entry(MOD).version_number.to_string(), "1.0.0");
3927      assert_eq!(std::fs::read(&dll).unwrap(), b"v1");
3928    }
3929
3930    #[test]
3931    fn a_pin_holds_for_another_item_in_the_batch_that_depends_on_it() {
3932      let mut repo = Repo::new();
3933      let index = repo.publish(&[
3934        Pkg {
3935          full_name: DEP,
3936          version: "1.0.0",
3937          deps: &[],
3938          files: &[("plugins/Dep.dll", b"dep1")],
3939        },
3940        Pkg {
3941          full_name: DEP,
3942          version: "2.0.0",
3943          deps: &[],
3944          files: &[("plugins/Dep.dll", b"dep2")],
3945        },
3946        Pkg {
3947          full_name: MOD,
3948          version: "1.0.0",
3949          deps: &["Author-Dep-2.0.0"],
3950          files: &[("plugins/Mod.dll", b"v1")],
3951        },
3952      ]);
3953
3954      let desired = ["Author-Dep-1.0.0", MOD];
3955
3956      repo.install(&index, &desired, &desired, false);
3957
3958      assert_eq!(repo.entry(DEP).version_number.to_string(), "1.0.0");
3959      assert_eq!(repo.entry(MOD).version_number.to_string(), "1.0.0");
3960    }
3961
3962    #[test]
3963    fn a_missing_pinned_version_fails_rather_than_installing_the_latest() {
3964      let mut repo = Repo::new();
3965      let index = repo.publish(&mod_history());
3966      let outcome = repo.try_install(&index, &["Author-Mod-9.9.9"], &["Author-Mod-9.9.9"], false);
3967
3968      assert!(outcome.succeeded.is_empty());
3969      assert_eq!(outcome.failed.len(), 1);
3970      assert_eq!(outcome.failed[0].0, "Author-Mod-9.9.9");
3971      assert!(
3972        matches!(
3973          &outcome.failed[0].1,
3974          Error::MissingVersion { package, version }
3975            if package == "Author-Mod" && version == "9.9.9"
3976        ),
3977        "{}",
3978        outcome.failed[0].1
3979      );
3980      assert_eq!(
3981        outcome.failed[0].1.to_string(),
3982        "Profile error: cannot install Author-Mod-9.9.9: Author-Mod has no version 9.9.9"
3983      );
3984      assert!(
3985        modlist::read(repo.target.path())
3986          .unwrap_or_default()
3987          .is_empty()
3988      );
3989    }
3990
3991    #[test]
3992    fn naming_a_disabled_mod_with_a_version_enables_it() {
3993      let mut repo = Repo::new();
3994      let index = repo.publish(&mod_history());
3995
3996      repo.install(&index, &["Author-Mod-1.0.0"], &["Author-Mod-1.0.0"], false);
3997      set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3998
3999      assert!(!repo.entry(MOD).enabled);
4000
4001      let outcome = repo.install(&index, &["Author-Mod-1.0.0"], &["Author-Mod-1.0.0"], false);
4002
4003      assert_eq!(outcome.unchanged, names(&[MOD]));
4004      assert!(repo.entry(MOD).enabled);
4005    }
4006  }
4007}
4008
4009#[cfg(test)]
4010mod planning_tests {
4011  use super::*;
4012  use time::OffsetDateTime;
4013
4014  const LOADER: &str = "denikson-BepInExPack_Valheim";
4015
4016  fn recorded(name: &str, enabled: bool) -> ProfileMod {
4017    let version = Version {
4018      name: None,
4019      full_name: Some(name.to_string()),
4020      description: None,
4021      icon: None,
4022      version_number: Some("1.0.0".to_string()),
4023      dependencies: Vec::new(),
4024      download_url: None,
4025      downloads: None,
4026      date_created: OffsetDateTime::UNIX_EPOCH,
4027      website_url: None,
4028      is_active: None,
4029      uuid4: None,
4030      file_size: None,
4031    };
4032    let mut entry = mod_entry_from_version(name, "Owner", &version, 0);
4033
4034    entry.enabled = enabled;
4035
4036    entry
4037  }
4038
4039  fn names(list: &[&str]) -> Vec<String> {
4040    list.iter().map(|name| name.to_string()).collect()
4041  }
4042
4043  #[test]
4044  fn install_batch_from_restores_disabled_mods_unless_named() {
4045    let record = [
4046      recorded("Owner-Named", false),
4047      recorded("Owner-Other", false),
4048      recorded("Owner-On", true),
4049    ];
4050
4051    let batch = plan_install_batch_from(
4052      &record,
4053      &names(&["Owner-Named-1.0.0", "Owner-New"]),
4054      &names(&["Owner-Named-1.0.0"]),
4055    );
4056
4057    assert_eq!(batch.desired, names(&["Owner-Named-1.0.0", "Owner-New"]));
4058    assert_eq!(batch.enable_requested, names(&["Owner-Named"]));
4059    assert_eq!(batch.protect_disabled, names(&["Owner-Other"]));
4060    assert!(!batch.force);
4061  }
4062
4063  #[test]
4064  fn set_enabled_batch_from_sorts_mods_and_sets_loaders_aside() {
4065    let eco = Ecosystem::bundled();
4066    let record = [
4067      recorded("Owner-B", true),
4068      recorded("Owner-A", true),
4069      recorded("Owner-Off", false),
4070      recorded(LOADER, true),
4071    ];
4072
4073    let batch = plan_set_enabled_batch_from(&record, &eco, None, false).unwrap();
4074
4075    assert_eq!(batch.changing, names(&["Owner-A", "Owner-B"]));
4076    assert_eq!(batch.already, names(&["Owner-Off"]));
4077    assert_eq!(batch.loaders, names(&[LOADER]));
4078    assert!(!batch.enabled);
4079  }
4080
4081  #[test]
4082  fn set_enabled_batch_from_refuses_an_unrecorded_name() {
4083    let eco = Ecosystem::bundled();
4084    let record = [recorded("Owner-A", true)];
4085
4086    let result = plan_set_enabled_batch_from(&record, &eco, Some(&names(&["Owner-Missing"])), true);
4087
4088    let error = result.unwrap_err();
4089
4090    assert!(matches!(&error, Error::NotInstalled { package } if package == "Owner-Missing"));
4091    assert_eq!(
4092      error.to_string(),
4093      "Profile error: Owner-Missing is not installed"
4094    );
4095  }
4096
4097  #[test]
4098  fn check_removable_from_refuses_only_unknowable_records() {
4099    let eco = Ecosystem::bundled();
4100    let dir = Path::new("/profiles/main");
4101
4102    assert!(check_removable_from(dir, &eco, LOADER, RecordState::Present).is_ok());
4103    assert!(check_removable_from(dir, &eco, "Owner-Mod", RecordState::Absent).is_ok());
4104    assert!(matches!(
4105      check_removable_from(dir, &eco, LOADER, RecordState::Absent),
4106      Err(NotRemovable::RecordAbsent { path, .. })
4107        if path == crate::install::state_file_path(dir, LOADER)
4108    ));
4109    assert!(matches!(
4110      check_removable_from(
4111        dir,
4112        &eco,
4113        "Owner-Mod",
4114        RecordState::Unreadable(Error::Install("bad yaml".to_string()))
4115      ),
4116      Err(NotRemovable::RecordUnreadable { .. })
4117    ));
4118  }
4119
4120  #[test]
4121  fn uninstall_batch_from_splits_loaders_and_keeps_untracked() {
4122    let eco = Ecosystem::bundled();
4123    let record = [
4124      recorded("Owner-B", true),
4125      recorded("Owner-A", true),
4126      recorded(LOADER, true),
4127    ];
4128    let untracked = vec![PathBuf::from("BepInEx/plugins/Stray-Mod")];
4129
4130    let batch = plan_uninstall_batch_from(
4131      Path::new("/profiles/main"),
4132      &eco,
4133      "valheim",
4134      None,
4135      &record,
4136      |_| RecordState::Present,
4137      untracked.clone(),
4138    )
4139    .unwrap();
4140
4141    assert_eq!(batch.mods, names(&["Owner-A", "Owner-B"]));
4142    assert_eq!(batch.loaders, names(&[LOADER]));
4143    assert_eq!(batch.untracked, untracked);
4144  }
4145
4146  #[test]
4147  fn uninstall_batch_from_stops_at_the_first_refusal() {
4148    let eco = Ecosystem::bundled();
4149    let record = [recorded(LOADER, true), recorded("Owner-A", true)];
4150    let mut asked = Vec::new();
4151
4152    let result = plan_uninstall_batch_from(
4153      Path::new("/profiles/main"),
4154      &eco,
4155      "valheim",
4156      Some(&names(&[LOADER, "Owner-A"])),
4157      &record,
4158      |name| {
4159        asked.push(name.to_string());
4160
4161        RecordState::Absent
4162      },
4163      Vec::new(),
4164    );
4165
4166    assert!(
4167      matches!(result, Err(Error::Profile(message)) if message.contains("cannot be removed"))
4168    );
4169    assert_eq!(asked, names(&[LOADER]));
4170  }
4171
4172  #[test]
4173  fn uninstall_batch_from_refuses_unrecorded_names_and_unknown_games() {
4174    let eco = Ecosystem::bundled();
4175    let record = [recorded("Owner-A", true)];
4176
4177    let unrecorded = plan_uninstall_batch_from(
4178      Path::new("/profiles/main"),
4179      &eco,
4180      "valheim",
4181      Some(&names(&["Owner-Missing"])),
4182      &record,
4183      |_| RecordState::Present,
4184      Vec::new(),
4185    );
4186    let unknown_game = plan_uninstall_batch_from(
4187      Path::new("/profiles/main"),
4188      &eco,
4189      "no-such-game",
4190      None,
4191      &record,
4192      |_| RecordState::Present,
4193      Vec::new(),
4194    );
4195
4196    assert!(
4197      matches!(unrecorded, Err(Error::NotInstalled { package }) if package == "Owner-Missing")
4198    );
4199    assert!(matches!(unknown_game, Err(Error::UnknownGame { game }) if game == "no-such-game"));
4200  }
4201}