Skip to main content

thunderstore_engine/
install.rs

1//! Schema-driven, root-relative mod install routing.
2//!
3//! Given a package's extracted contents and a game's
4//! [`GameProfile`](crate::ecosystem::GameProfile) from the Thunderstore ecosystem
5//! schema, this module computes an [`InstallPlan`](crate::install::InstallPlan): a
6//! list of source files mapped to destination paths *relative to a profile/loader
7//! root*. The caller supplies the absolute root and applies the plan with
8//! [`apply_install`](crate::install::apply_install), which records a
9//! [`FileManifest`](crate::install::FileManifest) of every written path so
10//! uninstall is exact and reversible.
11//!
12//! Routing is driven entirely by the schema's install rules (no per-game code):
13//! a package's override folders route by matching a rule's route leaf, loose files
14//! route by longest-matching extension, and anything else falls to the rule flagged
15//! as the default location. A package that appears in the ecosystem's mod-loader
16//! registry ([`Ecosystem::modloader_package`](crate::ecosystem::Ecosystem::modloader_package))
17//! is instead unpacked to the root.
18//!
19//! Deliberately, this module does NOT resolve the absolute game directory, do
20//! Steam/Epic discovery, or place the loader proxy next to the executable — those
21//! are game-specific concerns left to the caller.
22
23#![deny(missing_docs)]
24
25use crate::ecosystem::{Ecosystem, GameProfile, InstallRule, ModloaderPackage, TrackingMethod};
26use crate::error::{Error, Result};
27#[cfg(feature = "io")]
28use crate::util::io_context;
29use serde::{Deserialize, Serialize};
30use std::collections::{BTreeMap, BTreeSet};
31#[cfg(feature = "io")]
32use std::fs;
33use std::path::{Component, Path, PathBuf};
34
35/// Records the files a `State`-tracked mod installed, so enable/disable can undo
36/// and redo them. Mirrors r2modman's `_state/<mod>-state.yml` `ModFileTracker`:
37/// each pair is `(cache source path, profile-relative install path)`.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40#[non_exhaustive]
41pub struct ModFileTracker {
42  /// The mod's `Owner-Name` identifier.
43  pub mod_name: String,
44  /// `(source, install-relative)` pairs, in plan order.
45  pub files: Vec<(String, String)>,
46}
47
48/// Collects the `State`-tracked entries of `plan` into a [`ModFileTracker`], or
49/// `None` when the plan installs no `State` files. Pure — no I/O.
50pub fn state_tracker_from_plan(plan: &InstallPlan, mod_name: &str) -> Option<ModFileTracker> {
51  let files: Vec<(String, String)> = plan
52    .entries
53    .iter()
54    .filter(|e| e.tracking == TrackingMethod::State)
55    .map(|e| {
56      (
57        e.source.to_string_lossy().to_string(),
58        e.dest_relative.to_string_lossy().replace('\\', "/"),
59      )
60    })
61    .collect();
62
63  if files.is_empty() {
64    return None;
65  }
66
67  Some(ModFileTracker {
68    mod_name: mod_name.to_string(),
69    files,
70  })
71}
72
73/// Whether every file `plan` tracks is still on disk under `root`, so a mod
74/// recorded at the planned version can be skipped instead of reinstalled.
75///
76/// A namespaced file must be at `name` while the mod is `enabled` and at
77/// `name.old` while it is not, since disabling renames it. A name that already
78/// ends in `.old` is never renamed, so it is checked as is. A mix of the two (a
79/// toggle that failed partway) is not on disk, so the reinstall repairs it. A
80/// `State` file needs the mod's `_state` tracker, and is only required on
81/// disk while the mod is `enabled`, since disabling removes it. Shared `none`
82/// files are not checked: a user may delete a config on purpose. A plan that
83/// tracks nothing (a modpack of only metadata) is trivially on disk.
84#[cfg(feature = "io")]
85pub fn plan_is_on_disk(plan: &InstallPlan, root: &Path, mod_name: &str, enabled: bool) -> bool {
86  let has_tracker = state_file_path(root, mod_name).exists();
87
88  plan.entries.iter().all(|entry| {
89    let dest = root.join(&entry.dest_relative);
90
91    match entry.tracking {
92      TrackingMethod::None => true,
93      TrackingMethod::State => has_tracker && (!enabled || dest.exists()),
94      tracking if tracking.is_namespaced() => {
95        let already_old = dest.to_string_lossy().to_lowercase().ends_with(".old");
96
97        if enabled || already_old {
98          return dest.exists();
99        }
100
101        let mut disabled = dest.clone().into_os_string();
102
103        disabled.push(".old");
104
105        Path::new(&disabled).exists()
106      }
107      _ => dest.exists(),
108    }
109  })
110}
111
112/// The `_state/<mod_name>-state.yml` path within a profile directory.
113pub fn state_file_path(profile_dir: &Path, mod_name: &str) -> PathBuf {
114  profile_dir
115    .join("_state")
116    .join(format!("{mod_name}-state.yml"))
117}
118
119/// Writes a mod's state tracker to `<profile_dir>/_state/<mod>-state.yml`.
120#[cfg(feature = "io")]
121pub fn write_state_file(profile_dir: &Path, tracker: &ModFileTracker) -> Result<()> {
122  let path = state_file_path(profile_dir, &tracker.mod_name);
123
124  if let Some(parent) = path.parent() {
125    fs::create_dir_all(parent)
126      .map_err(|e| io_context(format!("creating {}", parent.display()), e))?;
127  }
128
129  let text = serde_yaml_ng::to_string(tracker)
130    .map_err(|e| Error::Install(format!("serializing state file: {e}")))?;
131
132  fs::write(&path, text).map_err(|e| io_context(format!("writing {}", path.display()), e))
133}
134
135/// Reads a mod's state tracker, or `None` if the file does not exist.
136#[cfg(feature = "io")]
137pub fn read_state_file(profile_dir: &Path, mod_name: &str) -> Result<Option<ModFileTracker>> {
138  let path = state_file_path(profile_dir, mod_name);
139
140  if !path.exists() {
141    return Ok(None);
142  }
143
144  let text =
145    fs::read_to_string(&path).map_err(|e| io_context(format!("reading {}", path.display()), e))?;
146  let tracker = serde_yaml_ng::from_str(&text)
147    .map_err(|e| Error::Install(format!("parsing {}: {e}", path.display())))?;
148
149  Ok(Some(tracker))
150}
151
152/// Removes a mod's `State`-tracked payload files and then its `_state` file, so
153/// an uninstall leaves nothing behind for a mod whose files live under
154/// non-namespaced routes (which [`remove_delisted`] does not reconcile).
155///
156/// A missing `_state` file is a no-op — the mod tracked no `State` files. A
157/// payload file that is already gone (e.g. the mod was disabled first) is
158/// skipped. Unlike [`disable_mod`], this also deletes the tracker itself, since
159/// after an uninstall there is nothing left to restore.
160#[cfg(feature = "io")]
161pub fn remove_state_payload(profile_dir: &Path, mod_name: &str) -> Result<()> {
162  clear_state_files(profile_dir, mod_name)?;
163
164  remove_state_file(profile_dir, mod_name)
165}
166
167/// Removes a mod's `State`-tracked payload files but keeps its `_state` file, so
168/// a reinstall that fails before writing a new one still leaves the record that
169/// [`remove_state_payload`] needs to uninstall the mod. A missing `_state` file
170/// is a no-op.
171#[cfg(feature = "io")]
172pub fn clear_state_files(profile_dir: &Path, mod_name: &str) -> Result<()> {
173  match read_state_file(profile_dir, mod_name)? {
174    Some(tracker) => remove_state_files(profile_dir, &tracker),
175    None => Ok(()),
176  }
177}
178
179/// Removes a mod's `_state` file, if it has one, leaving any payload files it
180/// names in place.
181#[cfg(feature = "io")]
182pub fn remove_state_file(profile_dir: &Path, mod_name: &str) -> Result<()> {
183  let path = state_file_path(profile_dir, mod_name);
184
185  if !path.exists() {
186    return Ok(());
187  }
188
189  fs::remove_file(&path).map_err(|e| io_context(format!("removing {}", path.display()), e))
190}
191
192/// Validates that `dest` is a safe root-relative path: it must not be absolute,
193/// carry a path prefix/root, or use `..` to climb out of the install root.
194///
195/// This guards every destination computed from untrusted inputs — a package's
196/// `Owner-Name` identifier and the ecosystem schema's route `target` — so a
197/// malicious or malformed package cannot read or write outside the caller's root.
198fn ensure_safe_relative(dest: &Path) -> Result<()> {
199  for component in dest.components() {
200    match component {
201      Component::Normal(_) | Component::CurDir => {}
202      Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
203        return Err(Error::Install(format!(
204          "unsafe install path escapes the install root: {}",
205          dest.display()
206        )));
207      }
208    }
209  }
210
211  Ok(())
212}
213
214/// A single source -> destination mapping within an install plan.
215#[derive(Debug, Clone, PartialEq, Eq)]
216#[non_exhaustive]
217pub struct InstallEntry {
218  /// Absolute path to the source file within the extracted package (or, for a
219  /// `package-zip` install, the package archive itself).
220  pub source: PathBuf,
221  /// Destination path relative to the profile/loader root.
222  pub dest_relative: PathBuf,
223  /// How this file is tracked, which governs whether it is namespaced, recorded
224  /// for uninstall, and whether an existing file is preserved.
225  pub tracking: TrackingMethod,
226}
227
228/// A computed, root-relative plan for installing one package.
229#[derive(Debug, Clone, Default)]
230#[non_exhaustive]
231pub struct InstallPlan {
232  /// The ordered source -> destination mappings for this package's files.
233  pub entries: Vec<InstallEntry>,
234}
235
236/// Records every path written by [`apply_install`], for exact uninstall.
237#[derive(Debug, Clone, Default)]
238#[non_exhaustive]
239pub struct FileManifest {
240  /// Paths written, relative to the root passed to [`apply_install`].
241  pub written: Vec<PathBuf>,
242}
243
244/// Builds an [`InstallPlan`] for a package extracted at `extracted_root`.
245///
246/// Walks the extracted directory and plans from what it finds; see
247/// [`plan_install_from`] for the routing rules and for planning from a file list
248/// without touching disk. `archive_path` is the package's original zip, needed
249/// only for `package-zip` loaders (e.g. GodotML); pass `None` when unavailable.
250#[cfg(feature = "io")]
251pub fn plan_install(
252  ecosystem: &Ecosystem,
253  profile: &GameProfile,
254  package_full_name: &str,
255  extracted_root: &Path,
256  archive_path: Option<&Path>,
257) -> Result<InstallPlan> {
258  let walk_root = match ecosystem.modloader_package(package_full_name) {
259    Some(pack) if !pack.root_folder.is_empty() => match extracted_root.join(&pack.root_folder) {
260      nested if nested.is_dir() => nested,
261      _ => extracted_root.to_path_buf(),
262    },
263    Some(_) => extracted_root.to_path_buf(),
264    None if installs_whole_archive(profile) => {
265      return plan_install_from(
266        ecosystem,
267        profile,
268        package_full_name,
269        extracted_root,
270        &[],
271        archive_path,
272      );
273    }
274    None => extracted_root.to_path_buf(),
275  };
276
277  let files: Vec<PathBuf> = walk_files(&walk_root)?
278    .into_iter()
279    .map(|file| {
280      file
281        .strip_prefix(extracted_root)
282        .map(Path::to_path_buf)
283        .unwrap_or(file)
284    })
285    .collect();
286
287  plan_install_from(
288    ecosystem,
289    profile,
290    package_full_name,
291    extracted_root,
292    &files,
293    archive_path,
294  )
295}
296
297/// Builds an [`InstallPlan`] for a package from its file list, without touching
298/// disk.
299///
300/// `files` lists the package's regular files as paths relative to
301/// `extracted_root`, in any order; an archive's entry names work as they are,
302/// and its folder entries (empty, or ending in `/` or `\`) are skipped.
303/// Each planned [`InstallEntry::source`] is `extracted_root` joined with one of
304/// them, so `extracted_root` should be where the files are, or will be, extracted.
305///
306/// If `package_full_name` is in the ecosystem's mod-loader registry, the package
307/// is a loader pack and unpacks to the root; otherwise its files are routed by the
308/// profile's [`InstallRule`]s. `archive_path` is the package's original zip, needed
309/// only for `package-zip` loaders (e.g. GodotML); pass `None` when unavailable.
310///
311/// # Errors
312///
313/// [`Error::Install`] if a listed path is absolute or climbs out with `..`, if a
314/// destination would escape the install root, or if two files route to the same
315/// destination.
316///
317/// # Examples
318///
319/// ```
320/// use std::path::{Path, PathBuf};
321/// use thunderstore_engine::ecosystem::Ecosystem;
322/// use thunderstore_engine::install::plan_install_from;
323///
324/// let eco = Ecosystem::bundled();
325/// let profile = eco.game("valheim").and_then(|game| game.profile()).unwrap();
326/// let files = [PathBuf::from("plugins/Mod.dll")];
327///
328/// let plan = plan_install_from(&eco, profile, "Owner-Mod", Path::new("/cache/Owner-Mod"), &files, None)?;
329///
330/// assert_eq!(plan.entries[0].source, Path::new("/cache/Owner-Mod/plugins/Mod.dll"));
331/// assert_eq!(plan.entries[0].dest_relative, Path::new("BepInEx/plugins/Owner-Mod/Mod.dll"));
332/// # Ok::<(), thunderstore_engine::Error>(())
333/// ```
334pub fn plan_install_from(
335  ecosystem: &Ecosystem,
336  profile: &GameProfile,
337  package_full_name: &str,
338  extracted_root: &Path,
339  files: &[PathBuf],
340  archive_path: Option<&Path>,
341) -> Result<InstallPlan> {
342  let mut files: Vec<PathBuf> = files
343    .iter()
344    .filter(|file| !names_a_folder(file))
345    .cloned()
346    .collect();
347
348  for file in &files {
349    ensure_safe_relative(file)?;
350  }
351
352  files.sort();
353
354  if let Some(pack) = ecosystem.modloader_package(package_full_name) {
355    return plan_loader_pack(pack, profile, extracted_root, &files);
356  }
357
358  plan_regular_mod(
359    profile,
360    package_full_name,
361    extracted_root,
362    &files,
363    archive_path,
364  )
365}
366
367/// Whether `file` is an archive's folder entry rather than a file: empty, or
368/// ending in a separator.
369fn names_a_folder(file: &Path) -> bool {
370  matches!(
371    file.as_os_str().as_encoded_bytes().last(),
372    None | Some(b'/' | b'\\')
373  )
374}
375
376/// Whether `profile` installs a regular mod as its whole archive (a `package-zip`
377/// default rule), in which case planning needs no file list.
378#[cfg(feature = "io")]
379fn installs_whole_archive(profile: &GameProfile) -> bool {
380  let mut flat = Vec::new();
381
382  flatten_rules(&profile.install_rules, Path::new(""), &mut flat);
383
384  whole_archive_rule(&flat).is_some()
385}
386
387/// The `package-zip` default rule, if the profile has one.
388fn whole_archive_rule<'a, 'b>(flat: &'b [FlatRule<'a>]) -> Option<&'b FlatRule<'a>> {
389  flat
390    .iter()
391    .find(|r| r.rule.is_default_location && r.rule.tracking_method == TrackingMethod::PackageZip)
392}
393
394/// Plans a loader pack: unpack its payload to the profile root.
395///
396/// Many packs nest their payload under a single subfolder;
397/// [`ModloaderPackage::root_folder`](crate::ecosystem::ModloaderPackage::root_folder)
398/// names it so the folder's *contents* land at the root. The subfolder is used
399/// when any listed file sits under it; otherwise the package root is. Package-root
400/// metadata (`manifest.json`, `icon.png`, `README.md`) is dropped. Files landing
401/// under an untracked route (e.g. the pack's own `BepInEx/config/`) are preserved
402/// across reinstalls; the rest are recorded so the loader can be uninstalled
403/// exactly.
404fn plan_loader_pack(
405  pack: &ModloaderPackage,
406  profile: &GameProfile,
407  extracted_root: &Path,
408  files: &[PathBuf],
409) -> Result<InstallPlan> {
410  let nested = Path::new(&pack.root_folder);
411  let has_nested = !pack.root_folder.is_empty()
412    && files
413      .iter()
414      .any(|file| file.starts_with(nested) && file != nested);
415  let base = if has_nested { nested } else { Path::new("") };
416
417  let mut untracked = Vec::new();
418
419  collect_routes(
420    &profile.install_rules,
421    Path::new(""),
422    &|rule| rule.tracking_method == TrackingMethod::None,
423    &mut untracked,
424  );
425
426  let mut entries = Vec::new();
427
428  for file in files {
429    let Ok(rel) = file.strip_prefix(base) else {
430      continue;
431    };
432
433    if let Some(tracking) =
434      classify_loader_file(rel, &untracked, &profile.relative_file_exclusions)?
435    {
436      entries.push(InstallEntry {
437        source: extracted_root.join(file),
438        dest_relative: rel.to_path_buf(),
439        tracking,
440      });
441    }
442  }
443
444  Ok(InstallPlan { entries })
445}
446
447/// Decides whether and how a loader-pack file (path `rel`, relative to the pack
448/// payload root) is installed.
449///
450/// Returns `None` for package-root metadata (`manifest.json`, `icon.png`,
451/// `README.md`) and for a file whose name is in `exclusions` (e.g. `LICENCE`).
452/// Otherwise it returns the tracking method: `none` (shared config, preserved
453/// across reinstalls) when the file lands under one of the pack's own `untracked`
454/// routes, else `state` (recorded for exact uninstall). The safety check on `rel`
455/// is surfaced as an `Err`. Pure — no filesystem access.
456fn classify_loader_file(
457  rel: &Path,
458  untracked: &[PathBuf],
459  exclusions: &[String],
460) -> Result<Option<TrackingMethod>> {
461  if is_package_metadata(rel) {
462    return Ok(None);
463  }
464
465  if let Some(name) = rel.file_name().and_then(|n| n.to_str())
466    && exclusions.iter().any(|e| e == name)
467  {
468    return Ok(None);
469  }
470
471  ensure_safe_relative(rel)?;
472
473  let tracking = if untracked.iter().any(|route| rel.starts_with(route)) {
474    TrackingMethod::None
475  } else {
476    TrackingMethod::State
477  };
478
479  Ok(Some(tracking))
480}
481
482/// Plans a regular mod install by routing each file through the profile's rules.
483fn plan_regular_mod(
484  profile: &GameProfile,
485  ident: &str,
486  extracted_root: &Path,
487  files: &[PathBuf],
488  archive_path: Option<&Path>,
489) -> Result<InstallPlan> {
490  let mut flat = Vec::new();
491
492  flatten_rules(&profile.install_rules, Path::new(""), &mut flat);
493
494  // Whole-package zip loaders (e.g. GodotML): the catch-all rule is `package-zip`,
495  // so the entire archive is installed as a single file rather than per-file.
496  if let Some(rule) = whole_archive_rule(&flat) {
497    return plan_package_zip(&rule.full_route, ident, archive_path);
498  }
499
500  let mut entries = Vec::new();
501  let mut claimed: BTreeMap<PathBuf, PathBuf> = BTreeMap::new();
502
503  for rel in files {
504    match route_file(profile, &flat, ident, rel)? {
505      RouteOutcome::Route {
506        dest_relative,
507        tracking,
508      } => {
509        if let Some(earlier) = claimed.insert(dest_relative.clone(), rel.clone()) {
510          return Err(colliding_files(&earlier, rel, &dest_relative));
511        }
512
513        entries.push(InstallEntry {
514          source: extracted_root.join(rel),
515          dest_relative,
516          tracking,
517        });
518      }
519      RouteOutcome::Skip(reason) => log_route_skip(rel, reason),
520    }
521  }
522
523  Ok(InstallPlan { entries })
524}
525
526/// The error for two package files routed onto one destination, which would
527/// otherwise let the later copy silently overwrite the earlier one.
528///
529/// This happens when files sit in ordinary folders: like r2modman, those files
530/// are flattened to their name under the mod's folder, so only an override
531/// folder such as `plugins/` keeps them apart. Refusing the package names the
532/// conflict instead of installing a mod that is missing a file.
533fn colliding_files(first: &Path, second: &Path, dest: &Path) -> Error {
534  let show = |path: &Path| path.to_string_lossy().replace('\\', "/");
535
536  Error::Install(format!(
537    "package files {} and {} would both install to {}; files outside an override \
538     folder such as plugins/ are flattened to their name, so the package must ship \
539     them under one to keep them apart",
540    show(first),
541    show(second),
542    show(dest)
543  ))
544}
545
546/// The outcome of routing a single extracted file through a profile's rules.
547#[derive(Debug, Clone, PartialEq, Eq)]
548enum RouteOutcome {
549  /// Route the file to `dest_relative` (relative to the profile root) tracked
550  /// as `tracking`.
551  Route {
552    dest_relative: PathBuf,
553    tracking: TrackingMethod,
554  },
555  /// The file is not installed, for the given reason.
556  Skip(SkipReason),
557}
558
559/// Why [`route_file`] declined to install a file.
560#[derive(Debug, Clone, PartialEq, Eq)]
561enum SkipReason {
562  /// The path has no usable file name.
563  NoName,
564  /// The file matched the profile's file exclusions (e.g. `LICENCE`).
565  Excluded,
566  /// No install rule claimed the file.
567  NoRoute,
568  /// The file routed to a rule whose tracking method has no per-file placement
569  /// (e.g. `package-zip`).
570  UnsupportedTracking(TrackingMethod),
571}
572
573/// Routes one extracted file (path `rel`, relative to the package root) through
574/// the profile's rules, returning where it should land or why it is skipped.
575///
576/// This is the whole per-file routing decision, lifted out of the filesystem
577/// walk in [`plan_regular_mod`]: it touches no disk, so the entire routing table
578/// — override-folder matching, longest-extension routing, the default location,
579/// exclusions, and `<ident>` namespacing — is unit-testable against string paths.
580/// The safety check on the computed destination is still enforced, surfaced as an
581/// `Err`.
582fn route_file(
583  profile: &GameProfile,
584  flat: &[FlatRule<'_>],
585  ident: &str,
586  rel: &Path,
587) -> Result<RouteOutcome> {
588  let name = match rel.file_name().and_then(|n| n.to_str()) {
589    Some(n) => n,
590    None => return Ok(RouteOutcome::Skip(SkipReason::NoName)),
591  };
592
593  if profile.relative_file_exclusions.iter().any(|e| e == name) {
594    return Ok(RouteOutcome::Skip(SkipReason::Excluded));
595  }
596
597  let resolution = resolve_override(&profile.install_rules, rel)
598    .or_else(|| loose_file_route(flat, name))
599    .or_else(|| default_route(flat, rel, name));
600
601  let RouteResolution {
602    route,
603    tracking,
604    remainder,
605  } = match resolution {
606    Some(resolved) => resolved,
607    None => return Ok(RouteOutcome::Skip(SkipReason::NoRoute)),
608  };
609
610  let dest = match build_dest(&route, tracking, ident, &remainder) {
611    Some(dest) => dest,
612    None => {
613      return Ok(RouteOutcome::Skip(SkipReason::UnsupportedTracking(
614        tracking,
615      )));
616    }
617  };
618
619  ensure_safe_relative(&dest)?;
620
621  Ok(RouteOutcome::Route {
622    dest_relative: dest,
623    tracking,
624  })
625}
626
627/// Emits the same skip warnings the inline routing loop used to, for the reasons
628/// worth surfacing (a file with no route, or an unsupported tracking method).
629fn log_route_skip(rel: &Path, reason: SkipReason) {
630  match reason {
631    SkipReason::NoRoute => tracing::warn!("no install route for {}; skipping", rel.display()),
632    SkipReason::UnsupportedTracking(tracking) => tracing::warn!(
633      "unsupported tracking {:?} for {}; skipping",
634      tracking,
635      rel.display()
636    ),
637    SkipReason::Excluded | SkipReason::NoName => {}
638  }
639}
640
641/// Plans a `package-zip` install: copy the original archive into the route.
642fn plan_package_zip(route: &Path, ident: &str, archive_path: Option<&Path>) -> Result<InstallPlan> {
643  let archive = match archive_path {
644    Some(archive) => archive,
645    None => {
646      tracing::warn!("package-zip loader requires the original archive; skipping install");
647
648      return Ok(InstallPlan::default());
649    }
650  };
651
652  let dest = route.join(format!("{ident}.zip"));
653
654  ensure_safe_relative(&dest)?;
655
656  Ok(InstallPlan {
657    entries: vec![InstallEntry {
658      source: archive.to_path_buf(),
659      dest_relative: dest,
660      tracking: TrackingMethod::PackageZip,
661    }],
662  })
663}
664
665/// A single rule with its route resolved to a full profile-root-relative path.
666struct FlatRule<'a> {
667  full_route: PathBuf,
668  rule: &'a InstallRule,
669}
670
671/// A resolved route for one file: the destination route, how it is tracked, and
672/// the remaining sub-path to place under the route.
673#[derive(Debug, Clone, PartialEq, Eq)]
674struct RouteResolution {
675  route: PathBuf,
676  tracking: TrackingMethod,
677  remainder: PathBuf,
678}
679
680/// Flattens the rule forest into `(full_route, rule)` pairs, resolving each nested
681/// rule's route against its parent so subroute routes become absolute.
682fn flatten_rules<'a>(rules: &'a [InstallRule], parent: &Path, out: &mut Vec<FlatRule<'a>>) {
683  for rule in rules {
684    let full = join_route(parent, &rule.route);
685
686    out.push(FlatRule {
687      full_route: full.clone(),
688      rule,
689    });
690
691    if !rule.sub_routes.is_empty() {
692      flatten_rules(&rule.sub_routes, &full, out);
693    }
694  }
695}
696
697/// Resolves a file through an override folder at any depth. When the top folder
698/// is not one (e.g. a wrapper such as `BepInEx/` or `ZenUI/`), the walk steps
699/// inside it and tries again, dropping the wrapper, as r2modman's
700/// buildInstallForRuleSubtype recurses into ordinary folders. Once a folder
701/// matches, everything beneath it is placed by [`resolve_dir`].
702fn resolve_override(rules: &[InstallRule], rel: &Path) -> Option<RouteResolution> {
703  let mut current = rel;
704
705  loop {
706    if let Some(found) = resolve_dir(rules, Path::new(""), current) {
707      return Some(found);
708    }
709
710    let mut comps = current.components();
711
712    comps.next()?;
713    current = comps.as_path();
714  }
715}
716
717/// Resolves a file whose top component names an override folder (recursively into
718/// subroutes), returning the destination route, its tracking, and the remaining
719/// path to place under it.
720///
721/// Only a directory matches an override folder: a lone file named like one (e.g.
722/// a root file called `plugins`) has nothing beneath it to place, so it is left
723/// to extension or default routing.
724fn resolve_dir(rules: &[InstallRule], parent_full: &Path, rel: &Path) -> Option<RouteResolution> {
725  let mut comps = rel.components();
726  let first = comps.next()?.as_os_str().to_str()?;
727  let rest = comps.as_path();
728
729  // A lone file (nothing beneath `first`) is not a folder match.
730  rest.components().next()?;
731
732  for rule in rules {
733    if !route_leaf(&rule.route).eq_ignore_ascii_case(first) {
734      continue;
735    }
736
737    let full = join_route(parent_full, &rule.route);
738
739    if !rule.sub_routes.is_empty() {
740      if let Some(found) = resolve_dir(&rule.sub_routes, &full, rest) {
741        return Some(found);
742      }
743
744      // A loose file directly inside this folder routes by subroute extension.
745      if rest.components().count() == 1
746        && let Some(name) = rest.file_name().and_then(|n| n.to_str())
747      {
748        let mut sub_flat = Vec::new();
749
750        flatten_rules(&rule.sub_routes, &full, &mut sub_flat);
751
752        if let Some(matched) = best_extension(&sub_flat, name) {
753          return Some(RouteResolution {
754            route: matched.full_route.clone(),
755            tracking: matched.rule.tracking_method,
756            remainder: PathBuf::from(name),
757          });
758        }
759      }
760    }
761
762    return Some(RouteResolution {
763      route: full,
764      tracking: rule.tracking_method,
765      remainder: rest.to_path_buf(),
766    });
767  }
768
769  None
770}
771
772/// Routes a file not claimed by an override folder by longest-matching extension.
773///
774/// This applies to any file — a root file or one inside an ordinary subfolder
775/// (e.g. `Wrapper/Hook.mm.dll` still routes to the `.mm.dll` rule) — so a matched
776/// file lands in its extension's route by base name rather than falling through to
777/// the default location.
778fn loose_file_route(flat: &[FlatRule<'_>], name: &str) -> Option<RouteResolution> {
779  let matched = best_extension(flat, name)?;
780
781  Some(RouteResolution {
782    route: matched.full_route.clone(),
783    tracking: matched.rule.tracking_method,
784    remainder: PathBuf::from(name),
785  })
786}
787
788/// Routes a file that matched nothing to the profile's default-location rule.
789///
790/// A `subdir` default flattens the file to its base name (`name`), as r2modman's
791/// installSubDir does for a file it reached by walking into ordinary folders;
792/// every other method preserves the full relative path under the route.
793fn default_route(flat: &[FlatRule<'_>], rel: &Path, name: &str) -> Option<RouteResolution> {
794  let matched = flat.iter().find(|r| r.rule.is_default_location)?;
795  let tracking = matched.rule.tracking_method;
796
797  let remainder = match tracking {
798    TrackingMethod::Subdir => PathBuf::from(name),
799    _ => rel.to_path_buf(),
800  };
801
802  Some(RouteResolution {
803    route: matched.full_route.clone(),
804    tracking,
805    remainder,
806  })
807}
808
809/// Finds the flattened rule whose longest `default_file_extensions` suffix matches
810/// `name`, so a more specific extension (e.g. `.lib.dll`) wins over `.dll`.
811fn best_extension<'a>(flat: &'a [FlatRule<'a>], name: &str) -> Option<&'a FlatRule<'a>> {
812  flat
813    .iter()
814    .filter_map(|fr| {
815      fr.rule
816        .default_file_extensions
817        .iter()
818        .filter(|ext| name.ends_with(ext.as_str()))
819        .map(|ext| ext.len())
820        .max()
821        .map(|len| (len, fr))
822    })
823    .max_by_key(|(len, _)| *len)
824    .map(|(_, fr)| fr)
825}
826
827/// Computes the destination for a routed file, applying `<ident>` namespacing for
828/// per-mod tracking methods. Returns `None` for methods with no per-file placement
829/// (`package-zip`, unknown), which the caller skips.
830fn build_dest(
831  route: &Path,
832  tracking: TrackingMethod,
833  ident: &str,
834  remainder: &Path,
835) -> Option<PathBuf> {
836  match tracking {
837    // Both namespace the file under `route/<ident>/` and keep the remainder as
838    // resolved. Where `subdir` flattens (a file outside an override folder),
839    // the resolver has already reduced the remainder to the base name.
840    TrackingMethod::Subdir | TrackingMethod::SubdirNoFlatten => {
841      Some(route.join(ident).join(remainder))
842    }
843    TrackingMethod::None | TrackingMethod::State => Some(route.join(remainder)),
844    TrackingMethod::PackageZip | TrackingMethod::Other => None,
845  }
846}
847
848/// The final path segment of a route, i.e. the override-folder name matched at a
849/// package's root (`"BepInEx/plugins"` -> `"plugins"`).
850fn route_leaf(route: &str) -> &str {
851  route.rsplit(['/', '\\']).next().unwrap_or(route)
852}
853
854/// Joins a parent full route with a (possibly slash-separated) child route.
855fn join_route(parent_full: &Path, child_route: &str) -> PathBuf {
856  let child = PathBuf::from(child_route);
857
858  if parent_full.as_os_str().is_empty() {
859    child
860  } else {
861    parent_full.join(child)
862  }
863}
864
865/// Whether `rel` is package-root metadata that a loader pack should not install.
866fn is_package_metadata(rel: &Path) -> bool {
867  if rel.components().count() != 1 {
868    return false;
869  }
870
871  match rel.file_name().and_then(|n| n.to_str()) {
872    Some(name) => {
873      let lower = name.to_ascii_lowercase();
874
875      lower == "manifest.json" || lower == "icon.png" || lower == "readme.md"
876    }
877    None => false,
878  }
879}
880
881/// Collects the full routes of every rule (recursively) matching `pred`.
882///
883/// Used with a `none`-tracking predicate to find a loader pack's shared/untracked
884/// routes (preserved on reinstall), and with a namespaced predicate to find the
885/// per-mod `<Owner-Name>/` routes reconciled by [`remove_delisted`].
886fn collect_routes<F: Fn(&InstallRule) -> bool>(
887  rules: &[InstallRule],
888  parent: &Path,
889  pred: &F,
890  out: &mut Vec<PathBuf>,
891) {
892  for rule in rules {
893    let full = join_route(parent, &rule.route);
894
895    if pred(rule) {
896      out.push(full.clone());
897    }
898
899    if !rule.sub_routes.is_empty() {
900      collect_routes(&rule.sub_routes, &full, pred, out);
901    }
902  }
903}
904
905/// Applies an install plan into `root`, copying files and recording what was
906/// written.
907///
908/// `root` is the caller-supplied profile/loader root. Parent directories are
909/// created as needed. Files tracked as `none` (shared config) are written only if
910/// absent and are never recorded, so a user's edits survive reinstalls and they are
911/// never auto-removed; all other files are (over)written and recorded in the
912/// returned [`FileManifest`] (paths relative to `root`).
913///
914/// The apply is all-or-nothing: if any entry fails, every file this call created
915/// is removed before the error is returned — along with any directory tree this
916/// call newly created (now left empty) — so a partial install leaves `root` as it
917/// found it, with no untracked files or empty directories behind.
918///
919/// For a `none`-tracked (shared config) destination that already exists — a
920/// regular file or a symlink the user planted — the entry is skipped and left
921/// untouched, so a user's edits (or their symlinked config) survive. For a
922/// tracked destination, a symlink already sitting there is refused rather than
923/// followed, so a pre-planted leaf link cannot redirect the write. This is
924/// best-effort: it inspects the final path component only (not symlinked parent
925/// directories) and is not race-free against a concurrent attacker mutating
926/// `root` mid-install.
927#[cfg(feature = "io")]
928pub fn apply_install(plan: &InstallPlan, root: &Path) -> Result<FileManifest> {
929  apply_install_reporting(plan, root, &mut |_, _| {})
930}
931
932/// [`apply_install`], calling `on_progress(done, total)` in plan entries before
933/// each entry and once more after the last.
934#[cfg(feature = "io")]
935pub(crate) fn apply_install_reporting(
936  plan: &InstallPlan,
937  root: &Path,
938  on_progress: &mut dyn FnMut(u64, u64),
939) -> Result<FileManifest> {
940  let mut written = Vec::with_capacity(plan.entries.len());
941  let mut created: Vec<PathBuf> = Vec::new();
942  let mut created_dirs: Vec<PathBuf> = Vec::new();
943  let total = plan.entries.len() as u64;
944
945  for (done, entry) in plan.entries.iter().enumerate() {
946    on_progress(done as u64, total);
947
948    if let Err(err) = ensure_safe_relative(&entry.dest_relative) {
949      rollback_partial_install(&created, &created_dirs);
950
951      return Err(err);
952    }
953
954    let dest = root.join(&entry.dest_relative);
955
956    let dest_is_symlink = fs::symlink_metadata(&dest)
957      .map(|metadata| metadata.file_type().is_symlink())
958      .unwrap_or(false);
959
960    match classify_entry(entry.tracking, dest.exists(), dest_is_symlink) {
961      // Shared config already present (a file or a symlink the user planted) is
962      // left untouched so a user's edits survive.
963      ApplyAction::SkipExistingConfig => continue,
964      // A pre-planted symlink at a tracked destination is refused rather than
965      // followed, so it cannot redirect the write elsewhere.
966      ApplyAction::RefuseSymlink => {
967        rollback_partial_install(&created, &created_dirs);
968
969        return Err(Error::Install(format!(
970          "refusing to install through a symlink at {}",
971          dest.display()
972        )));
973      }
974      ApplyAction::Write { record } => {
975        if let Err(err) = copy_entry(entry, &dest, root, &mut created_dirs) {
976          rollback_partial_install(&created, &created_dirs);
977
978          return Err(err);
979        }
980
981        created.push(dest);
982
983        if record {
984          written.push(entry.dest_relative.clone());
985        }
986      }
987    }
988  }
989
990  on_progress(total, total);
991
992  Ok(FileManifest { written })
993}
994
995/// What [`apply_install`] should do with one entry, given the state at its
996/// destination.
997#[derive(Debug, Clone, Copy, PartialEq, Eq)]
998#[cfg(feature = "io")]
999enum ApplyAction {
1000  /// Copy the source into place; `record` says whether to add it to the
1001  /// [`FileManifest`] (tracked files are recorded, shared config is not).
1002  Write { record: bool },
1003  /// Leave an existing shared-config (`none`-tracked) file/symlink untouched.
1004  SkipExistingConfig,
1005  /// Refuse to write through a pre-existing symlink at a tracked destination.
1006  RefuseSymlink,
1007}
1008
1009/// Decides what to do with an entry from its tracking method and whether the
1010/// destination already exists / is a symlink. Pure — no filesystem access — so
1011/// the write/skip/refuse policy is exhaustively table-testable.
1012#[cfg(feature = "io")]
1013fn classify_entry(tracking: TrackingMethod, exists: bool, is_symlink: bool) -> ApplyAction {
1014  if tracking == TrackingMethod::None && (exists || is_symlink) {
1015    return ApplyAction::SkipExistingConfig;
1016  }
1017
1018  if is_symlink {
1019    return ApplyAction::RefuseSymlink;
1020  }
1021
1022  ApplyAction::Write {
1023    record: tracking != TrackingMethod::None,
1024  }
1025}
1026
1027/// Copies one entry's source to `dest`, creating parent directories as needed and
1028/// recording any it newly created in `created_dirs` so a failed apply can undo them.
1029#[cfg(feature = "io")]
1030fn copy_entry(
1031  entry: &InstallEntry,
1032  dest: &Path,
1033  root: &Path,
1034  created_dirs: &mut Vec<PathBuf>,
1035) -> Result<()> {
1036  if let Some(parent) = dest.parent() {
1037    record_created_dirs(parent, root, created_dirs);
1038
1039    fs::create_dir_all(parent).map_err(|e| {
1040      Error::Install(format!(
1041        "failed to create install directory {}: {}",
1042        parent.display(),
1043        e
1044      ))
1045    })?;
1046  }
1047
1048  fs::copy(&entry.source, dest).map_err(|e| {
1049    Error::Install(format!(
1050      "failed to copy {} to {}: {}",
1051      entry.source.display(),
1052      dest.display(),
1053      e
1054    ))
1055  })?;
1056
1057  Ok(())
1058}
1059
1060/// Records, into `created_dirs`, each not-yet-existing ancestor of `dir` (down to
1061/// and including `dir`) that lies strictly below `root`, ordered shallowest first.
1062///
1063/// Called before `create_dir_all` so a failed apply can remove exactly the
1064/// directory trees this call introduced — never `root` itself and never a
1065/// directory that already existed. Already-recorded (now-existing) directories are
1066/// skipped, so entries sharing a parent do not double-record it.
1067#[cfg(feature = "io")]
1068fn record_created_dirs(dir: &Path, root: &Path, created_dirs: &mut Vec<PathBuf>) {
1069  let mut missing = Vec::new();
1070  let mut current = dir;
1071
1072  while current != root && current.starts_with(root) && !current.exists() {
1073    missing.push(current.to_path_buf());
1074
1075    match current.parent() {
1076      Some(parent) => current = parent,
1077      None => break,
1078    }
1079  }
1080
1081  for path in missing.into_iter().rev() {
1082    created_dirs.push(path);
1083  }
1084}
1085
1086/// Best-effort removal of the files an [`apply_install`] created before it
1087/// failed, then the now-empty directory trees it newly created, so a failed apply
1088/// leaves `root` as it found it rather than half applied. Directories are removed
1089/// deepest-first (children before parents) and only if empty, so a pre-existing or
1090/// still-populated directory is never taken. Cleanup errors are logged, not
1091/// propagated: the caller needs to see the original failure, not a secondary one.
1092#[cfg(feature = "io")]
1093fn rollback_partial_install(created: &[PathBuf], created_dirs: &[PathBuf]) {
1094  for path in created.iter().rev() {
1095    if let Err(err) = fs::remove_file(path) {
1096      tracing::warn!(
1097        "failed to roll back partially-installed file {}: {}",
1098        path.display(),
1099        err
1100      );
1101    }
1102  }
1103
1104  for dir in created_dirs.iter().rev() {
1105    if let Err(err) = fs::remove_dir(dir) {
1106      tracing::warn!(
1107        "failed to roll back partially-created directory {}: {}",
1108        dir.display(),
1109        err
1110      );
1111    }
1112  }
1113}
1114
1115/// The `<Owner-Name>`-shaped mod folders under `profile`'s namespaced install
1116/// routes that `keep` does not name, as root-relative paths. These are exactly
1117/// the directories [`remove_delisted`] would delete.
1118///
1119/// Each regular mod installs into its own `<Owner-Name>` folder under a
1120/// namespaced route (e.g. `BepInEx/plugins/<Owner-Name>/`), so the folders
1121/// present under those routes *are* the record of what is installed.
1122/// Non-namespaced areas are never considered, which is why loader files at the
1123/// root and shared/`none` routes like `BepInEx/config` never appear here.
1124///
1125/// Public so a caller can ask what a sweep would take before taking it, which is
1126/// what lets a CLI warn about folders it does not manage. Sharing this with
1127/// [`remove_delisted`] is the point: a second implementation of "what does the
1128/// sweep touch" can drift from the one that actually deletes.
1129///
1130/// Sorted and deduplicated, which `read_dir` order alone does not give, so a
1131/// caller listing these one per line reads the same list every run.
1132///
1133/// Lists each route from [`namespaced_routes`] and decides with
1134/// [`plan_delisted_from`].
1135#[cfg(feature = "io")]
1136pub fn plan_delisted(
1137  profile: &GameProfile,
1138  root: &Path,
1139  keep: &BTreeSet<String>,
1140) -> Result<Vec<PathBuf>> {
1141  let mut entries = Vec::new();
1142
1143  for route in namespaced_routes(profile)? {
1144    let dir = root.join(&route);
1145
1146    if !dir.is_dir() {
1147      continue;
1148    }
1149
1150    for entry in fs::read_dir(&dir)
1151      .map_err(|e| io_context(format!("reading install route {}", dir.display()), e))?
1152    {
1153      let entry =
1154        entry.map_err(|e| io_context(format!("reading an entry under {}", dir.display()), e))?;
1155      let path = entry.path();
1156      let metadata = fs::symlink_metadata(&path)
1157        .map_err(|e| io_context(format!("inspecting {}", path.display()), e))?;
1158
1159      entries.push(RouteEntry::new(
1160        route.join(entry.file_name()),
1161        metadata.is_dir(),
1162        metadata.file_type().is_symlink(),
1163      ));
1164    }
1165  }
1166
1167  Ok(plan_delisted_from(&entries, keep))
1168}
1169
1170/// The root-relative routes under which each regular mod gets its own
1171/// `<Owner-Name>` folder: every rule whose tracking method is namespaced.
1172///
1173/// These are the folders a caller lists to feed [`plan_delisted_from`].
1174///
1175/// # Errors
1176///
1177/// [`Error::Install`] if a route from the schema would escape the install root.
1178pub fn namespaced_routes(profile: &GameProfile) -> Result<Vec<PathBuf>> {
1179  let mut routes = Vec::new();
1180
1181  collect_routes(
1182    &profile.install_rules,
1183    Path::new(""),
1184    &|rule| rule.tracking_method.is_namespaced(),
1185    &mut routes,
1186  );
1187
1188  for route in &routes {
1189    ensure_safe_relative(route)?;
1190  }
1191
1192  Ok(routes)
1193}
1194
1195/// One entry found directly inside a namespaced install route, as input to
1196/// [`plan_delisted_from`].
1197#[derive(Debug, Clone, PartialEq, Eq)]
1198#[non_exhaustive]
1199pub struct RouteEntry {
1200  /// The entry's path relative to the install root, e.g.
1201  /// `BepInEx/plugins/Owner-Mod`.
1202  pub path: PathBuf,
1203  /// Whether the entry is a directory, without following a symlink.
1204  pub is_dir: bool,
1205  /// Whether the entry is a symlink.
1206  pub is_symlink: bool,
1207}
1208
1209impl RouteEntry {
1210  /// Builds a [`RouteEntry`].
1211  pub fn new(path: impl Into<PathBuf>, is_dir: bool, is_symlink: bool) -> Self {
1212    Self {
1213      path: path.into(),
1214      is_dir,
1215      is_symlink,
1216    }
1217  }
1218}
1219
1220/// The mod folders a reconcile sweep would remove, decided from a listing of the
1221/// [`namespaced_routes`] without touching disk.
1222///
1223/// A real directory whose name has the `<Owner-Name>` shape and is not in `keep`
1224/// is selected. Symlinks, files, and folders of any other shape (a loader's
1225/// `MMHOOK`, a user's own folder) are left alone. Returns the selected
1226/// [`RouteEntry::path`]s, sorted and deduplicated.
1227///
1228/// # Examples
1229///
1230/// ```
1231/// use std::collections::BTreeSet;
1232/// use std::path::PathBuf;
1233/// use thunderstore_engine::install::{RouteEntry, plan_delisted_from};
1234///
1235/// let listing = [
1236///   RouteEntry::new("BepInEx/plugins/Owner-Kept", true, false),
1237///   RouteEntry::new("BepInEx/plugins/Owner-Gone", true, false),
1238///   RouteEntry::new("BepInEx/plugins/MMHOOK", true, false),
1239/// ];
1240/// let keep = BTreeSet::from(["Owner-Kept".to_string()]);
1241///
1242/// assert_eq!(
1243///   plan_delisted_from(&listing, &keep),
1244///   vec![PathBuf::from("BepInEx/plugins/Owner-Gone")]
1245/// );
1246/// ```
1247pub fn plan_delisted_from(entries: &[RouteEntry], keep: &BTreeSet<String>) -> Vec<PathBuf> {
1248  let listing: Vec<(PathBuf, bool, bool)> = entries
1249    .iter()
1250    .map(|entry| (entry.path.clone(), entry.is_dir, entry.is_symlink))
1251    .collect();
1252  let planned: BTreeSet<PathBuf> = plan_reconcile(&listing, keep).into_iter().collect();
1253
1254  planned.into_iter().collect()
1255}
1256
1257/// Reconciles the on-disk install to a desired set, removing the folders of mods
1258/// that are no longer wanted, without any sidecar state file.
1259///
1260/// This is [`plan_delisted`] followed by the removal, so there is one enumeration
1261/// and one decision about what the sweep covers. Returns the removed directories
1262/// (relative to `root`), which is exactly what `plan_delisted` returned.
1263#[cfg(feature = "io")]
1264pub fn remove_delisted(
1265  profile: &GameProfile,
1266  root: &Path,
1267  keep: &BTreeSet<String>,
1268) -> Result<Vec<PathBuf>> {
1269  let planned = plan_delisted(profile, root, keep)?;
1270
1271  for relative in &planned {
1272    let path = root.join(relative);
1273
1274    fs::remove_dir_all(&path)
1275      .map_err(|e| io_context(format!("removing delisted mod {}", path.display()), e))?;
1276  }
1277
1278  Ok(planned)
1279}
1280
1281/// Removes one mod's `<route>/<ident>/` folder under every namespaced route, so
1282/// a reinstall starts from an empty folder instead of writing beside files the
1283/// new version no longer ships (or a disabled install's `.old` files).
1284///
1285/// Shared routes (`none`, `state`) are untouched; a mod's `State`-tracked files
1286/// are removed by [`remove_state_payload`] instead. A symlink where the folder
1287/// would be is left alone, never followed, as [`remove_delisted`] does.
1288#[cfg(feature = "io")]
1289pub fn remove_mod_folders(profile: &GameProfile, root: &Path, ident: &str) -> Result<()> {
1290  let mut components = Path::new(ident).components();
1291
1292  if !matches!(
1293    (components.next(), components.next()),
1294    (Some(Component::Normal(_)), None)
1295  ) {
1296    return Err(Error::Install(format!(
1297      "refusing to remove folders for unsafe mod name {ident:?}"
1298    )));
1299  }
1300
1301  let mut routes = Vec::new();
1302
1303  collect_routes(
1304    &profile.install_rules,
1305    Path::new(""),
1306    &|rule| rule.tracking_method.is_namespaced(),
1307    &mut routes,
1308  );
1309
1310  for route in routes {
1311    let relative = route.join(ident);
1312
1313    ensure_safe_relative(&relative)?;
1314
1315    let path = root.join(&relative);
1316
1317    let is_real_dir = match fs::symlink_metadata(&path) {
1318      Ok(metadata) => metadata.is_dir(),
1319      Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
1320      Err(e) => return Err(io_context(format!("inspecting {}", path.display()), e)),
1321    };
1322
1323    if is_real_dir {
1324      fs::remove_dir_all(&path)
1325        .map_err(|e| io_context(format!("removing mod folder {}", path.display()), e))?;
1326    }
1327  }
1328
1329  Ok(())
1330}
1331
1332/// Decides which directories under a namespaced route should be removed, given a
1333/// directory `listing` and the set of mod idents to `keep`.
1334///
1335/// Each tuple is `(path, is_dir, is_symlink)`. A symlink or non-directory is
1336/// ignored — never followed or removed. A real directory whose name has the
1337/// `<Owner-Name>` shape ([`looks_like_mod_ident`]) and is not in `keep` is
1338/// selected for removal; a loader-shipped subfolder (e.g. `MMHOOK`) or a
1339/// user-created folder that does not match that shape is left alone. Pure — no
1340/// filesystem access — so the reconcile decision is testable without planting
1341/// real directory trees.
1342fn plan_reconcile(listing: &[(PathBuf, bool, bool)], keep: &BTreeSet<String>) -> Vec<PathBuf> {
1343  listing
1344    .iter()
1345    .filter(|(path, is_dir, is_symlink)| {
1346      if *is_symlink || !*is_dir {
1347        return false;
1348      }
1349
1350      match path.file_name().and_then(|n| n.to_str()) {
1351        Some(ident) => looks_like_mod_ident(ident) && !keep.contains(ident),
1352        None => false,
1353      }
1354    })
1355    .map(|(path, _, _)| path.clone())
1356    .collect()
1357}
1358
1359/// Whether a directory name has the `<Owner-Name>` shape a mod folder uses: at
1360/// least one `-` separating segments of `[A-Za-z0-9_]`. This is the identifier
1361/// [`build_dest`] namespaces under, so it distinguishes per-mod folders from
1362/// loader-shipped or user-created folders under the same route.
1363fn looks_like_mod_ident(name: &str) -> bool {
1364  name.contains('-')
1365    && name
1366      .chars()
1367      .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
1368}
1369
1370/// Recursively collects all file paths under `dir` (skipping directories).
1371#[cfg(feature = "io")]
1372fn walk_files(dir: &Path) -> Result<Vec<PathBuf>> {
1373  let mut files = Vec::new();
1374  let mut stack = vec![dir.to_path_buf()];
1375
1376  while let Some(current) = stack.pop() {
1377    for entry in fs::read_dir(&current)
1378      .map_err(|e| io_context(format!("reading package dir {}", current.display()), e))?
1379    {
1380      let entry = entry
1381        .map_err(|e| io_context(format!("reading an entry under {}", current.display()), e))?;
1382      let path = entry.path();
1383      let metadata = fs::symlink_metadata(&path)
1384        .map_err(|e| io_context(format!("inspecting {}", path.display()), e))?;
1385
1386      if metadata.file_type().is_symlink() {
1387        // Never follow symlinks: a symlinked directory could let an extracted
1388        // package escape its root or create a traversal cycle.
1389        tracing::warn!("Skipping symlink in package contents: {}", path.display());
1390
1391        continue;
1392      }
1393
1394      if metadata.is_dir() {
1395        stack.push(path);
1396      } else {
1397        files.push(path);
1398      }
1399    }
1400  }
1401
1402  files.sort();
1403
1404  Ok(files)
1405}
1406
1407/// Computes the rename each file needs to toggle its enabled state, omitting
1408/// files already in the desired state. Disabling appends `.old` to a file that
1409/// does not already end in `.old`; enabling strips a trailing `.old`. Pure — no
1410/// I/O — so the policy is table-testable (mirrors `classify_entry`).
1411pub fn plan_suffix_renames(files: &[PathBuf], disable: bool) -> Vec<(PathBuf, PathBuf)> {
1412  let mut renames = Vec::new();
1413
1414  for file in files {
1415    let name = file.to_string_lossy();
1416    let is_old = name.to_lowercase().ends_with(".old");
1417
1418    if disable && !is_old {
1419      renames.push((file.clone(), PathBuf::from(format!("{name}.old"))));
1420    } else if !disable && is_old {
1421      renames.push((file.clone(), PathBuf::from(&name[..name.len() - 4])));
1422    }
1423  }
1424
1425  renames
1426}
1427
1428/// Disables an installed mod: renames its `Subdir`-tracked files to `.old` and
1429/// removes its `State`-tracked files (recoverable via the `_state` file on
1430/// enable). Leaves shared/`none` config and the loader untouched.
1431#[cfg(feature = "io")]
1432pub fn disable_mod(profile: &GameProfile, profile_dir: &Path, mod_name: &str) -> Result<()> {
1433  let tracker = read_safe_state_file(profile_dir, mod_name)?;
1434
1435  toggle_subdir_files(profile, profile_dir, mod_name, true)?;
1436
1437  toggle_state_files(profile_dir, tracker, true)
1438}
1439
1440/// Enables an installed mod: strips `.old` from its `Subdir`-tracked files and
1441/// restores its `State`-tracked files by copying them back from the cache
1442/// sources recorded in the `_state` file.
1443///
1444/// # Errors
1445///
1446/// [`Error::Install`] before anything is touched if the `_state` file names a
1447/// destination outside `profile_dir`, or a source that is not a file of the
1448/// same name in this mod's own package cache (`.../cache/<mod_name>/...`), so a
1449/// tampered or imported record cannot copy any other file into the profile.
1450#[cfg(feature = "io")]
1451pub fn enable_mod(profile: &GameProfile, profile_dir: &Path, mod_name: &str) -> Result<()> {
1452  let tracker = read_safe_state_file(profile_dir, mod_name)?;
1453
1454  for (source, install_rel) in tracker.iter().flat_map(|tracker| &tracker.files) {
1455    ensure_cached_source(mod_name, source, install_rel)?;
1456  }
1457
1458  toggle_subdir_files(profile, profile_dir, mod_name, false)?;
1459
1460  toggle_state_files(profile_dir, tracker, false)
1461}
1462
1463/// [`read_state_file`], refusing a tracker with any destination outside the
1464/// profile so a toggle fails before it moves anything.
1465#[cfg(feature = "io")]
1466fn read_safe_state_file(profile_dir: &Path, mod_name: &str) -> Result<Option<ModFileTracker>> {
1467  let tracker = read_state_file(profile_dir, mod_name)?;
1468
1469  for (_, install_rel) in tracker.iter().flat_map(|tracker| &tracker.files) {
1470    ensure_safe_relative(Path::new(install_rel))?;
1471  }
1472
1473  Ok(tracker)
1474}
1475
1476/// Refuses a `_state` source that installing `mod_name` could not have
1477/// recorded: anything but an absolute path, with no `..`, inside
1478/// `cache/<mod_name>/`, naming a file called what `install_rel` is called.
1479#[cfg(feature = "io")]
1480fn ensure_cached_source(mod_name: &str, source: &str, install_rel: &str) -> Result<()> {
1481  let path = Path::new(source);
1482  let components: Vec<Component> = path.components().collect();
1483  let in_own_cache = components
1484    .windows(2)
1485    .any(|pair| pair[0].as_os_str() == "cache" && pair[1].as_os_str() == mod_name);
1486  let same_name =
1487    path.file_name().is_some() && path.file_name() == Path::new(install_rel).file_name();
1488
1489  if path.is_absolute() && !components.contains(&Component::ParentDir) && in_own_cache && same_name
1490  {
1491    return Ok(());
1492  }
1493
1494  Err(Error::Install(format!(
1495    "the state record for {mod_name} restores {install_rel} from {source}, which is not in its package cache"
1496  )))
1497}
1498
1499/// Applies the `.old` rename policy to every file under each namespaced route's
1500/// `<route>/<mod_name>/` folder.
1501#[cfg(feature = "io")]
1502fn toggle_subdir_files(
1503  profile: &GameProfile,
1504  profile_dir: &Path,
1505  mod_name: &str,
1506  disable: bool,
1507) -> Result<()> {
1508  let mut routes = Vec::new();
1509
1510  collect_routes(
1511    &profile.install_rules,
1512    Path::new(""),
1513    &|rule| rule.tracking_method.is_namespaced(),
1514    &mut routes,
1515  );
1516
1517  for route in routes {
1518    let mod_dir = profile_dir.join(&route).join(mod_name);
1519
1520    if !mod_dir.is_dir() {
1521      continue;
1522    }
1523
1524    let files = walk_files(&mod_dir)?;
1525
1526    for (from, to) in plan_suffix_renames(&files, disable) {
1527      fs::rename(&from, &to).map_err(|e| io_context(format!("toggling {}", from.display()), e))?;
1528    }
1529  }
1530
1531  Ok(())
1532}
1533
1534/// Removes (disable) or restores from cache (enable) the `State`-tracked files
1535/// recorded in `tracker`. `None` is a no-op: the mod tracked no `State` files.
1536///
1537/// Takes an already-read tracker rather than reading one itself so its caller can
1538/// do that read before any other mutation. Reading it here instead meant an
1539/// unreadable record failed only after [`toggle_subdir_files`] had renamed the
1540/// mod's files, leaving them toggled on disk while the caller's `mods.yml` still
1541/// recorded the old state.
1542#[cfg(feature = "io")]
1543fn toggle_state_files(
1544  profile_dir: &Path,
1545  tracker: Option<ModFileTracker>,
1546  disable: bool,
1547) -> Result<()> {
1548  let Some(tracker) = tracker else {
1549    return Ok(());
1550  };
1551
1552  if disable {
1553    return remove_state_files(profile_dir, &tracker);
1554  }
1555
1556  restore_state_files(profile_dir, &tracker)
1557}
1558
1559/// Removes each `State`-tracked destination that still exists, leaving the
1560/// `_state` file itself in place so [`restore_state_files`] can undo this.
1561///
1562/// Each recorded path is re-validated before use: the `_state` file sits in a
1563/// caller-owned directory and could be hand-edited, so a tampered entry must not
1564/// delete a file outside the profile root.
1565#[cfg(feature = "io")]
1566fn remove_state_files(profile_dir: &Path, tracker: &ModFileTracker) -> Result<()> {
1567  for (_, install_rel) in &tracker.files {
1568    ensure_safe_relative(Path::new(install_rel))?;
1569
1570    let dest = profile_dir.join(install_rel);
1571
1572    if !dest.exists() {
1573      continue;
1574    }
1575
1576    fs::remove_file(&dest).map_err(|e| io_context(format!("removing {}", dest.display()), e))?;
1577  }
1578
1579  Ok(())
1580}
1581
1582/// Copies each `State`-tracked file back from its recorded cache source,
1583/// creating any missing destination directories.
1584///
1585/// Each recorded path is re-validated before use, as [`remove_state_files`]
1586/// does, so a tampered entry cannot direct a copy outside the profile root.
1587#[cfg(feature = "io")]
1588fn restore_state_files(profile_dir: &Path, tracker: &ModFileTracker) -> Result<()> {
1589  for (source, install_rel) in &tracker.files {
1590    ensure_safe_relative(Path::new(install_rel))?;
1591
1592    let dest = profile_dir.join(install_rel);
1593
1594    if let Some(parent) = dest.parent() {
1595      fs::create_dir_all(parent)
1596        .map_err(|e| io_context(format!("creating {}", parent.display()), e))?;
1597    }
1598
1599    fs::copy(source, &dest)
1600      .map_err(|e| io_context(format!("restoring {} from {}", dest.display(), source), e))?;
1601  }
1602
1603  Ok(())
1604}
1605
1606#[cfg(test)]
1607mod tests {
1608  use super::*;
1609  use crate::ecosystem::{Ecosystem, GameProfile};
1610  #[cfg(feature = "io")]
1611  use std::fs::File;
1612  #[cfg(feature = "io")]
1613  use std::io::Write;
1614  #[cfg(feature = "io")]
1615  use tempfile::tempdir;
1616
1617  fn eco() -> Ecosystem {
1618    Ecosystem::bundled()
1619  }
1620
1621  fn profile(eco: &Ecosystem, slug: &str) -> GameProfile {
1622    eco.game(slug).unwrap().profile().unwrap().clone()
1623  }
1624
1625  #[cfg(feature = "io")]
1626  fn write(path: &Path, contents: &[u8]) {
1627    if let Some(parent) = path.parent() {
1628      fs::create_dir_all(parent).unwrap();
1629    }
1630
1631    let mut f = File::create(path).unwrap();
1632    f.write_all(contents).unwrap();
1633  }
1634
1635  fn dest_set(plan: &InstallPlan) -> Vec<String> {
1636    let mut v: Vec<String> = plan
1637      .entries
1638      .iter()
1639      .map(|e| e.dest_relative.to_string_lossy().replace('\\', "/"))
1640      .collect();
1641    v.sort();
1642
1643    v
1644  }
1645
1646  #[test]
1647  #[cfg(feature = "io")]
1648  fn test_bepinex_regular_mod_routing() {
1649    let eco = eco();
1650    let profile = profile(&eco, "valheim");
1651
1652    let pkg = tempdir().unwrap();
1653    let root = pkg.path();
1654
1655    write(&root.join("MyMod.dll"), b"dll");
1656    write(&root.join("manifest.json"), b"{}");
1657    write(&root.join("config/MyMod.cfg"), b"cfg");
1658    write(&root.join("patchers/MyPatcher.dll"), b"patch");
1659    write(&root.join("MyHook.mm.dll"), b"hook");
1660
1661    let plan = plan_install(&eco, &profile, "Author-MyMod", root, None).unwrap();
1662    let dests = dest_set(&plan);
1663
1664    assert!(dests.contains(&"BepInEx/plugins/Author-MyMod/MyMod.dll".to_string()));
1665    // BepInEx defines no exclusions, so metadata routes to the plugin folder.
1666    assert!(dests.contains(&"BepInEx/plugins/Author-MyMod/manifest.json".to_string()));
1667    // config is shared/untracked (not namespaced).
1668    assert!(dests.contains(&"BepInEx/config/MyMod.cfg".to_string()));
1669    // override patchers folder routes (namespaced), contents only.
1670    assert!(dests.contains(&"BepInEx/patchers/Author-MyMod/MyPatcher.dll".to_string()));
1671    // .mm.dll extension wins over .dll and routes to monomod.
1672    assert!(dests.contains(&"BepInEx/monomod/Author-MyMod/MyHook.mm.dll".to_string()));
1673  }
1674
1675  #[test]
1676  fn route_file_routes_by_table_without_disk() {
1677    let eco = eco();
1678    let profile = profile(&eco, "valheim");
1679
1680    let mut flat = Vec::new();
1681
1682    flatten_rules(&profile.install_rules, Path::new(""), &mut flat);
1683
1684    let ident = "Author-MyMod";
1685
1686    // A loose DLL routes to the (subdir-tracked, namespaced) plugins folder.
1687    match route_file(&profile, &flat, ident, Path::new("MyMod.dll")).unwrap() {
1688      RouteOutcome::Route {
1689        dest_relative,
1690        tracking,
1691      } => {
1692        assert_eq!(
1693          dest_relative,
1694          PathBuf::from("BepInEx/plugins/Author-MyMod/MyMod.dll")
1695        );
1696        assert_eq!(tracking, TrackingMethod::Subdir);
1697      }
1698      other => panic!("expected a route, got {other:?}"),
1699    }
1700
1701    // The most-specific extension wins: `.mm.dll` beats `.dll` and routes to monomod.
1702    match route_file(&profile, &flat, ident, Path::new("MyHook.mm.dll")).unwrap() {
1703      RouteOutcome::Route { dest_relative, .. } => assert_eq!(
1704        dest_relative,
1705        PathBuf::from("BepInEx/monomod/Author-MyMod/MyHook.mm.dll")
1706      ),
1707      other => panic!("expected a route, got {other:?}"),
1708    }
1709
1710    // A config file is shared/untracked (`none`), not namespaced.
1711    match route_file(&profile, &flat, ident, Path::new("config/MyMod.cfg")).unwrap() {
1712      RouteOutcome::Route {
1713        dest_relative,
1714        tracking,
1715      } => {
1716        assert_eq!(dest_relative, PathBuf::from("BepInEx/config/MyMod.cfg"));
1717        assert_eq!(tracking, TrackingMethod::None);
1718      }
1719      other => panic!("expected a route, got {other:?}"),
1720    }
1721
1722    // A path with no file name is skipped rather than routed.
1723    assert_eq!(
1724      route_file(&profile, &flat, ident, Path::new("")).unwrap(),
1725      RouteOutcome::Skip(SkipReason::NoName)
1726    );
1727  }
1728
1729  #[test]
1730  fn route_leaf_handles_both_separators() {
1731    assert_eq!(route_leaf("BepInEx/plugins"), "plugins");
1732    assert_eq!(route_leaf("BepInEx\\plugins"), "plugins");
1733    assert_eq!(route_leaf("plugins"), "plugins");
1734  }
1735
1736  #[test]
1737  #[cfg(feature = "io")]
1738  fn classify_entry_truth_table() {
1739    // Shared config (`none`): skip if a file or a symlink already sits there;
1740    // otherwise write it, but never record it in the manifest.
1741    assert_eq!(
1742      classify_entry(TrackingMethod::None, true, false),
1743      ApplyAction::SkipExistingConfig
1744    );
1745    assert_eq!(
1746      classify_entry(TrackingMethod::None, false, true),
1747      ApplyAction::SkipExistingConfig
1748    );
1749    assert_eq!(
1750      classify_entry(TrackingMethod::None, false, false),
1751      ApplyAction::Write { record: false }
1752    );
1753
1754    // Tracked: refuse a pre-existing symlink; otherwise write and record it.
1755    assert_eq!(
1756      classify_entry(TrackingMethod::Subdir, false, true),
1757      ApplyAction::RefuseSymlink
1758    );
1759    assert_eq!(
1760      classify_entry(TrackingMethod::State, true, false),
1761      ApplyAction::Write { record: true }
1762    );
1763    assert_eq!(
1764      classify_entry(TrackingMethod::SubdirNoFlatten, false, false),
1765      ApplyAction::Write { record: true }
1766    );
1767  }
1768
1769  #[test]
1770  fn plan_reconcile_selects_only_unwanted_mod_dirs() {
1771    let keep: BTreeSet<String> = ["Author-Keep".to_string()].into_iter().collect();
1772
1773    // (path, is_dir, is_symlink)
1774    let listing = vec![
1775      (PathBuf::from("Author-Keep"), true, false),  // kept
1776      (PathBuf::from("Author-Drop"), true, false),  // removed
1777      (PathBuf::from("MMHOOK"), true, false),       // not an ident -> ignored
1778      (PathBuf::from("Author-Link"), true, true),   // symlink -> ignored
1779      (PathBuf::from("Author-File"), false, false), // not a dir -> ignored
1780    ];
1781
1782    let removable = plan_reconcile(&listing, &keep);
1783
1784    assert_eq!(removable, vec![PathBuf::from("Author-Drop")]);
1785  }
1786
1787  #[test]
1788  fn classify_loader_file_drops_metadata_excluded_and_routes_rest() {
1789    let untracked = vec![PathBuf::from("BepInEx/config")];
1790    let exclusions = vec!["LICENCE".to_string()];
1791
1792    // Package-root metadata is dropped.
1793    assert_eq!(
1794      classify_loader_file(Path::new("manifest.json"), &untracked, &exclusions).unwrap(),
1795      None
1796    );
1797
1798    // An excluded file is dropped.
1799    assert_eq!(
1800      classify_loader_file(Path::new("LICENCE"), &untracked, &exclusions).unwrap(),
1801      None
1802    );
1803
1804    // A file under an untracked route is preserved (`none` tracking).
1805    assert_eq!(
1806      classify_loader_file(Path::new("BepInEx/config/x.cfg"), &untracked, &exclusions).unwrap(),
1807      Some(TrackingMethod::None)
1808    );
1809
1810    // Anything else is recorded (`state` tracking).
1811    assert_eq!(
1812      classify_loader_file(
1813        Path::new("BepInEx/core/loader.dll"),
1814        &untracked,
1815        &exclusions
1816      )
1817      .unwrap(),
1818      Some(TrackingMethod::State)
1819    );
1820
1821    // A traversal path is rejected.
1822    assert!(classify_loader_file(Path::new("../evil"), &untracked, &exclusions).is_err());
1823  }
1824
1825  #[test]
1826  #[cfg(feature = "io")]
1827  fn apply_install_empty_plan_writes_nothing() {
1828    let root = tempdir().unwrap();
1829
1830    let manifest = apply_install(&InstallPlan::default(), root.path()).unwrap();
1831
1832    assert!(manifest.written.is_empty());
1833  }
1834
1835  #[test]
1836  #[cfg(feature = "io")]
1837  fn test_subdir_override_folder_preserves_subpath() {
1838    let eco = eco();
1839    let profile = profile(&eco, "valheim");
1840
1841    let pkg = tempdir().unwrap();
1842    let root = pkg.path();
1843
1844    // A file nested inside the subdir-tracked plugins override folder keeps its
1845    // path beneath that folder; only the matched `plugins/` itself is stripped.
1846    write(&root.join("plugins/nested/Deep.dll"), b"deep");
1847    write(&root.join("plugins/Translations/German/german.json"), b"de");
1848
1849    let plan = plan_install(&eco, &profile, "Author-MyMod", root, None).unwrap();
1850    let dests = dest_set(&plan);
1851
1852    assert!(dests.contains(&"BepInEx/plugins/Author-MyMod/nested/Deep.dll".to_string()));
1853    assert!(
1854      dests.contains(&"BepInEx/plugins/Author-MyMod/Translations/German/german.json".to_string())
1855    );
1856  }
1857
1858  #[test]
1859  #[cfg(feature = "io")]
1860  fn test_subdir_override_folder_keeps_same_named_files_apart() {
1861    let eco = eco();
1862    let profile = profile(&eco, "valheim");
1863
1864    let pkg = tempdir().unwrap();
1865    let root = pkg.path();
1866
1867    write(&root.join("plugins/English/strings.json"), b"en");
1868    write(&root.join("plugins/German/strings.json"), b"de");
1869
1870    let plan = plan_install(&eco, &profile, "Author-MyMod", root, None).unwrap();
1871    let dests = dest_set(&plan);
1872
1873    assert_eq!(
1874      dests,
1875      vec![
1876        "BepInEx/plugins/Author-MyMod/English/strings.json".to_string(),
1877        "BepInEx/plugins/Author-MyMod/German/strings.json".to_string(),
1878      ]
1879    );
1880  }
1881
1882  #[test]
1883  #[cfg(feature = "io")]
1884  fn test_override_folder_inside_a_wrapper_folder_is_matched() {
1885    let eco = eco();
1886    let profile = profile(&eco, "valheim");
1887
1888    let pkg = tempdir().unwrap();
1889    let root = pkg.path();
1890
1891    // r2modman walks into a folder that is not an override folder and matches
1892    // one further down, dropping the wrapper.
1893    write(&root.join("BepInEx/plugins/Mod.dll"), b"dll");
1894    write(&root.join("BepInEx/config/Mod.cfg"), b"cfg");
1895    write(
1896      &root.join("ZenUI/plugins/Translations/German/strings.json"),
1897      b"de",
1898    );
1899    write(
1900      &root.join("ZenUI/plugins/Translations/English/strings.json"),
1901      b"en",
1902    );
1903
1904    let plan = plan_install(&eco, &profile, "Author-Mod", root, None).unwrap();
1905    let dests = dest_set(&plan);
1906
1907    assert_eq!(
1908      dests,
1909      vec![
1910        "BepInEx/config/Mod.cfg".to_string(),
1911        "BepInEx/plugins/Author-Mod/Mod.dll".to_string(),
1912        "BepInEx/plugins/Author-Mod/Translations/English/strings.json".to_string(),
1913        "BepInEx/plugins/Author-Mod/Translations/German/strings.json".to_string(),
1914      ]
1915    );
1916
1917    let cfg = plan
1918      .entries
1919      .iter()
1920      .find(|e| e.dest_relative == Path::new("BepInEx/config/Mod.cfg"))
1921      .unwrap();
1922
1923    assert_eq!(cfg.tracking, TrackingMethod::None);
1924  }
1925
1926  #[test]
1927  #[cfg(feature = "io")]
1928  fn test_wrapper_folder_without_an_override_folder_still_flattens() {
1929    let eco = eco();
1930    let profile = profile(&eco, "valheim");
1931
1932    let pkg = tempdir().unwrap();
1933    let root = pkg.path();
1934
1935    write(&root.join("Wrapper/assets/bundle.dat"), b"data");
1936    write(&root.join("Wrapper/Hook.mm.dll"), b"hook");
1937
1938    let plan = plan_install(&eco, &profile, "Author-Mod", root, None).unwrap();
1939    let dests = dest_set(&plan);
1940
1941    assert_eq!(
1942      dests,
1943      vec![
1944        "BepInEx/monomod/Author-Mod/Hook.mm.dll".to_string(),
1945        "BepInEx/plugins/Author-Mod/bundle.dat".to_string(),
1946      ]
1947    );
1948  }
1949
1950  #[test]
1951  #[cfg(feature = "io")]
1952  fn test_subdir_default_route_flattens_nested_file() {
1953    let eco = eco();
1954    let profile = profile(&eco, "valheim");
1955
1956    let pkg = tempdir().unwrap();
1957    let root = pkg.path();
1958
1959    // `web` is not an override folder, so its files fall through to the default
1960    // (subdir-tracked) plugins route one by one and land by base name, matching
1961    // r2modman, which flattens files it reaches by walking into ordinary folders.
1962    write(&root.join("web/js/card.js"), b"card");
1963
1964    let plan = plan_install(&eco, &profile, "Author-Mod", root, None).unwrap();
1965    let dests = dest_set(&plan);
1966
1967    assert_eq!(
1968      dests,
1969      vec!["BepInEx/plugins/Author-Mod/card.js".to_string()]
1970    );
1971  }
1972
1973  #[test]
1974  #[cfg(feature = "io")]
1975  fn test_plan_refuses_files_flattened_onto_the_same_destination() {
1976    let eco = eco();
1977    let profile = profile(&eco, "valheim");
1978
1979    let pkg = tempdir().unwrap();
1980    let root = pkg.path();
1981
1982    write(&root.join("web/a/index.js"), b"a");
1983    write(&root.join("web/b/index.js"), b"b");
1984
1985    let error = plan_install(&eco, &profile, "Author-Mod", root, None).unwrap_err();
1986    let message = error.to_string();
1987
1988    assert!(
1989      message.contains("BepInEx/plugins/Author-Mod/index.js"),
1990      "{message}"
1991    );
1992    assert!(message.contains("web/a/index.js"), "{message}");
1993    assert!(message.contains("web/b/index.js"), "{message}");
1994  }
1995
1996  #[test]
1997  #[cfg(feature = "io")]
1998  fn test_root_file_named_like_override_folder_is_not_a_folder_match() {
1999    let eco = eco();
2000    let profile = profile(&eco, "valheim");
2001
2002    let pkg = tempdir().unwrap();
2003    let root = pkg.path();
2004
2005    // Only a directory matches an override folder. A loose file that happens to be
2006    // named `plugins` routes like any other file instead of resolving to an empty
2007    // remainder (which would place it at the route folder itself).
2008    write(&root.join("plugins"), b"not a folder");
2009
2010    let plan = plan_install(&eco, &profile, "Author-Mod", root, None).unwrap();
2011    let dests = dest_set(&plan);
2012
2013    assert_eq!(
2014      dests,
2015      vec!["BepInEx/plugins/Author-Mod/plugins".to_string()]
2016    );
2017  }
2018
2019  #[test]
2020  #[cfg(feature = "io")]
2021  fn test_toggle_and_uninstall_handle_nested_subdir_files() {
2022    let eco = eco();
2023    let profile = profile(&eco, "valheim");
2024
2025    let pkg = tempdir().unwrap();
2026    write(&pkg.path().join("plugins/Mod.dll"), b"dll");
2027    write(
2028      &pkg.path().join("plugins/Translations/German/german.json"),
2029      b"de",
2030    );
2031
2032    let plan = plan_install(&eco, &profile, "Author-Mod", pkg.path(), None).unwrap();
2033
2034    let profile_dir = tempdir().unwrap();
2035    let root = profile_dir.path();
2036
2037    apply_install(&plan, root).unwrap();
2038
2039    let mod_dir = root.join("BepInEx/plugins/Author-Mod");
2040    let nested = mod_dir.join("Translations/German/german.json");
2041
2042    assert!(nested.exists());
2043
2044    disable_mod(&profile, root, "Author-Mod").unwrap();
2045
2046    assert!(!nested.exists());
2047    assert!(mod_dir.join("Translations/German/german.json.old").exists());
2048    assert!(mod_dir.join("Mod.dll.old").exists());
2049
2050    enable_mod(&profile, root, "Author-Mod").unwrap();
2051
2052    assert!(nested.exists());
2053    assert!(!mod_dir.join("Translations/German/german.json.old").exists());
2054    assert!(mod_dir.join("Mod.dll").exists());
2055
2056    remove_delisted(&profile, root, &BTreeSet::new()).unwrap();
2057
2058    assert!(!mod_dir.exists());
2059  }
2060
2061  #[test]
2062  #[cfg(feature = "io")]
2063  fn test_subdir_no_flatten_preserves_subpath() {
2064    let eco = eco();
2065    let profile = profile(&eco, "rumble");
2066
2067    let pkg = tempdir().unwrap();
2068    let root = pkg.path();
2069
2070    // rumble's default location (UserData/ModManager) is subdir-no-flatten, so a
2071    // nested file keeps its relative sub-path under the mod's namespaced folder.
2072    write(&root.join("data/nested/asset.bin"), b"asset");
2073
2074    let plan = plan_install(&eco, &profile, "Author-Mod", root, None).unwrap();
2075    let dests = dest_set(&plan);
2076
2077    assert!(dests.contains(&"UserData/ModManager/Author-Mod/data/nested/asset.bin".to_string()));
2078  }
2079
2080  #[test]
2081  #[cfg(feature = "io")]
2082  fn test_extension_routing_applies_to_nested_files() {
2083    let eco = eco();
2084    let profile = profile(&eco, "valheim");
2085
2086    let pkg = tempdir().unwrap();
2087    let root = pkg.path();
2088
2089    // A .mm.dll inside an ordinary (non-override) subfolder still routes by its
2090    // extension to monomod rather than falling to the default plugins route; the
2091    // subdir flatten then drops the wrapper directory.
2092    write(&root.join("Wrapper/Hook.mm.dll"), b"hook");
2093
2094    let plan = plan_install(&eco, &profile, "Author-MyMod", root, None).unwrap();
2095    let dests = dest_set(&plan);
2096
2097    assert!(dests.contains(&"BepInEx/monomod/Author-MyMod/Hook.mm.dll".to_string()));
2098    assert!(!dests.iter().any(|d| d.contains("Wrapper")));
2099  }
2100
2101  #[test]
2102  #[cfg(feature = "io")]
2103  fn test_loader_pack_unpacks_to_root_stripping_nested_subfolder() {
2104    let eco = eco();
2105    let profile = profile(&eco, "valheim");
2106
2107    let pkg = tempdir().unwrap();
2108    let root = pkg.path();
2109
2110    write(&root.join("BepInExPack_Valheim/winhttp.dll"), b"proxy");
2111    write(
2112      &root.join("BepInExPack_Valheim/BepInEx/core/BepInEx.dll"),
2113      b"core",
2114    );
2115    write(&root.join("manifest.json"), b"{}");
2116    write(&root.join("icon.png"), b"png");
2117
2118    let plan = plan_install(&eco, &profile, "denikson-BepInExPack_Valheim", root, None).unwrap();
2119    let dests = dest_set(&plan);
2120
2121    assert!(dests.contains(&"winhttp.dll".to_string()));
2122    assert!(dests.contains(&"BepInEx/core/BepInEx.dll".to_string()));
2123    assert!(!dests.iter().any(|d| d.contains("manifest.json")));
2124    assert!(!dests.iter().any(|d| d.contains("BepInExPack_Valheim")));
2125    assert!(!dests.iter().any(|d| d.contains("icon.png")));
2126  }
2127
2128  #[test]
2129  #[cfg(feature = "io")]
2130  fn test_loader_pack_preserves_config_on_reinstall() {
2131    let eco = eco();
2132    let profile = profile(&eco, "valheim");
2133
2134    let pkg = tempdir().unwrap();
2135    let pkg_root = pkg.path();
2136    write(&pkg_root.join("BepInExPack_Valheim/winhttp.dll"), b"proxy");
2137    write(
2138      &pkg_root.join("BepInExPack_Valheim/BepInEx/config/BepInEx.cfg"),
2139      b"default",
2140    );
2141
2142    let profile_dir = tempdir().unwrap();
2143    let root = profile_dir.path();
2144
2145    let plan = plan_install(
2146      &eco,
2147      &profile,
2148      "denikson-BepInExPack_Valheim",
2149      pkg_root,
2150      None,
2151    )
2152    .unwrap();
2153    apply_install(&plan, root).unwrap();
2154
2155    let cfg = root.join("BepInEx/config/BepInEx.cfg");
2156    write(&cfg, b"user-edited");
2157
2158    let plan = plan_install(
2159      &eco,
2160      &profile,
2161      "denikson-BepInExPack_Valheim",
2162      pkg_root,
2163      None,
2164    )
2165    .unwrap();
2166    apply_install(&plan, root).unwrap();
2167
2168    assert_eq!(fs::read_to_string(&cfg).unwrap(), "user-edited");
2169    assert!(root.join("winhttp.dll").exists());
2170  }
2171
2172  #[test]
2173  #[cfg(feature = "io")]
2174  fn test_loader_pack_without_nesting_falls_back_to_root() {
2175    let eco = eco();
2176    let profile = profile(&eco, "valheim");
2177
2178    let pkg = tempdir().unwrap();
2179    let root = pkg.path();
2180
2181    // The pack declares a nested root folder, but it is absent here: copy the
2182    // package root directly.
2183    write(&root.join("winhttp.dll"), b"proxy");
2184
2185    let plan = plan_install(&eco, &profile, "denikson-BepInExPack_Valheim", root, None).unwrap();
2186    let dests = dest_set(&plan);
2187
2188    assert!(dests.contains(&"winhttp.dll".to_string()));
2189  }
2190
2191  #[test]
2192  #[cfg(feature = "io")]
2193  fn test_loader_pack_skips_relative_file_exclusions() {
2194    let eco = eco();
2195    // The boneworks profile lists LICENCE in relativeFileExclusions.
2196    let profile = profile(&eco, "boneworks");
2197
2198    let pkg = tempdir().unwrap();
2199    let root = pkg.path();
2200
2201    // A loader pack from the bundled registry whose declared root folder is absent,
2202    // so its own root is copied directly.
2203    write(&root.join("winhttp.dll"), b"proxy");
2204    write(&root.join("LICENCE"), b"license text");
2205
2206    let plan = plan_install(&eco, &profile, "denikson-BepInExPack_Valheim", root, None).unwrap();
2207    let dests = dest_set(&plan);
2208
2209    assert!(dests.contains(&"winhttp.dll".to_string()));
2210    // The profile-excluded LICENCE file is neither installed nor recorded, just
2211    // like plan_regular_mod honors the same exclusions.
2212    assert!(!dests.iter().any(|d| d.contains("LICENCE")));
2213  }
2214
2215  #[test]
2216  #[cfg(feature = "io")]
2217  fn test_config_is_preserved_across_reinstall() {
2218    let eco = eco();
2219    let profile = profile(&eco, "valheim");
2220
2221    let pkg = tempdir().unwrap();
2222    let pkg_root = pkg.path();
2223    write(&pkg_root.join("MyMod.dll"), b"dll");
2224    write(&pkg_root.join("config/MyMod.cfg"), b"default-config");
2225
2226    let profile_dir = tempdir().unwrap();
2227    let root = profile_dir.path();
2228
2229    let plan = plan_install(&eco, &profile, "Author-MyMod", pkg_root, None).unwrap();
2230    let first = apply_install(&plan, root).unwrap();
2231
2232    assert_eq!(first.written.len(), 1);
2233    assert!(root.join("BepInEx/config/MyMod.cfg").exists());
2234
2235    let cfg = root.join("BepInEx/config/MyMod.cfg");
2236    write(&cfg, b"user-edited");
2237
2238    let plan = plan_install(&eco, &profile, "Author-MyMod", pkg_root, None).unwrap();
2239    let second = apply_install(&plan, root).unwrap();
2240
2241    assert_eq!(fs::read_to_string(&cfg).unwrap(), "user-edited");
2242    assert!(second.written.iter().any(|p| p.ends_with("MyMod.dll")));
2243    assert!(
2244      !second
2245        .written
2246        .iter()
2247        .any(|p| p.to_string_lossy().contains("MyMod.cfg"))
2248    );
2249  }
2250
2251  #[test]
2252  #[cfg(feature = "io")]
2253  fn test_apply_and_manifest_roundtrip() {
2254    let eco = eco();
2255    let profile = profile(&eco, "valheim");
2256
2257    let pkg = tempdir().unwrap();
2258    let pkg_root = pkg.path();
2259    write(&pkg_root.join("MyMod.dll"), b"dll");
2260    write(&pkg_root.join("config/MyMod.cfg"), b"cfg");
2261
2262    let plan = plan_install(&eco, &profile, "Author-MyMod", pkg_root, None).unwrap();
2263
2264    let profile_dir = tempdir().unwrap();
2265    let root = profile_dir.path();
2266    let manifest = apply_install(&plan, root).unwrap();
2267
2268    assert_eq!(manifest.written.len(), 1);
2269    assert!(root.join("BepInEx/plugins/Author-MyMod/MyMod.dll").exists());
2270    assert!(root.join("BepInEx/config/MyMod.cfg").exists());
2271
2272    for rel in &manifest.written {
2273      fs::remove_file(root.join(rel)).unwrap();
2274    }
2275
2276    assert!(!root.join("BepInEx/plugins/Author-MyMod/MyMod.dll").exists());
2277  }
2278
2279  #[test]
2280  #[cfg(feature = "io")]
2281  fn test_apply_install_rolls_back_on_failure() {
2282    let src = tempdir().unwrap();
2283
2284    let good = src.path().join("good.dll");
2285    write(&good, b"good");
2286
2287    let plan = InstallPlan {
2288      entries: vec![
2289        InstallEntry {
2290          source: good,
2291          dest_relative: PathBuf::from("BepInEx/plugins/Author-Mod/good.dll"),
2292          tracking: TrackingMethod::State,
2293        },
2294        InstallEntry {
2295          source: src.path().join("does_not_exist.dll"),
2296          dest_relative: PathBuf::from("BepInEx/plugins/Author-Mod/missing.dll"),
2297          tracking: TrackingMethod::State,
2298        },
2299      ],
2300    };
2301
2302    let profile_dir = tempdir().unwrap();
2303    let root = profile_dir.path();
2304
2305    let result = apply_install(&plan, root);
2306
2307    // The second entry fails to copy (its source is absent); the first,
2308    // already-written file is rolled back so no untracked file is left behind.
2309    assert!(result.is_err());
2310    assert!(!root.join("BepInEx/plugins/Author-Mod/good.dll").exists());
2311    // The directory tree this apply newly created is removed too, so no empty
2312    // directories are left behind.
2313    assert!(!root.join("BepInEx/plugins/Author-Mod").exists());
2314    assert!(!root.join("BepInEx/plugins").exists());
2315    assert!(!root.join("BepInEx").exists());
2316    // The caller-supplied root itself is left in place.
2317    assert!(root.exists());
2318  }
2319
2320  #[test]
2321  #[cfg(unix)]
2322  #[cfg(feature = "io")]
2323  fn test_apply_install_preserves_symlinked_shared_config() {
2324    use std::os::unix::fs::symlink;
2325
2326    let src = tempdir().unwrap();
2327    let source = src.path().join("mod.cfg");
2328    write(&source, b"packaged-default");
2329
2330    let outside = tempdir().unwrap();
2331    let user_config = outside.path().join("user.cfg");
2332    write(&user_config, b"user-edited");
2333
2334    let profile_dir = tempdir().unwrap();
2335    let root = profile_dir.path();
2336
2337    // The user symlinked their shared config to a file they maintain elsewhere.
2338    let dest_relative = PathBuf::from("BepInEx/config/mod.cfg");
2339    let dest = root.join(&dest_relative);
2340    fs::create_dir_all(dest.parent().unwrap()).unwrap();
2341    symlink(&user_config, &dest).unwrap();
2342
2343    let plan = InstallPlan {
2344      entries: vec![InstallEntry {
2345        source,
2346        dest_relative,
2347        tracking: TrackingMethod::None,
2348      }],
2349    };
2350
2351    let manifest = apply_install(&plan, root).unwrap();
2352
2353    // The install succeeds, the None entry is not recorded, and the user's
2354    // symlinked config is left exactly as it was.
2355    assert!(manifest.written.is_empty());
2356    assert_eq!(fs::read_to_string(&user_config).unwrap(), "user-edited");
2357  }
2358
2359  #[test]
2360  #[cfg(unix)]
2361  #[cfg(feature = "io")]
2362  fn test_apply_install_refuses_to_write_through_symlink() {
2363    use std::os::unix::fs::symlink;
2364
2365    let src = tempdir().unwrap();
2366    let source = src.path().join("mod.cfg");
2367    write(&source, b"new-content");
2368
2369    let outside = tempdir().unwrap();
2370    let secret = outside.path().join("secret.txt");
2371    write(&secret, b"original");
2372
2373    let profile_dir = tempdir().unwrap();
2374    let root = profile_dir.path();
2375
2376    // Plant a symlink at the destination pointing outside the root.
2377    let dest_relative = PathBuf::from("BepInEx/config/mod.cfg");
2378    let dest = root.join(&dest_relative);
2379    fs::create_dir_all(dest.parent().unwrap()).unwrap();
2380    symlink(&secret, &dest).unwrap();
2381
2382    let plan = InstallPlan {
2383      entries: vec![InstallEntry {
2384        source,
2385        dest_relative,
2386        tracking: TrackingMethod::State,
2387      }],
2388    };
2389
2390    let result = apply_install(&plan, root);
2391
2392    // The write is refused and the symlink target outside the root is untouched.
2393    assert!(result.is_err());
2394    assert_eq!(fs::read_to_string(&secret).unwrap(), "original");
2395  }
2396
2397  #[test]
2398  #[cfg(feature = "io")]
2399  fn test_remove_delisted_removes_only_unwanted_mod_folders() {
2400    let eco = eco();
2401    let profile = profile(&eco, "valheim");
2402
2403    let profile_dir = tempdir().unwrap();
2404    let root = profile_dir.path();
2405
2406    write(&root.join("BepInEx/plugins/Owner-ModA/A.dll"), b"a");
2407    write(&root.join("BepInEx/plugins/Owner-ModB/B.dll"), b"b");
2408    write(&root.join("BepInEx/core/BepInEx.dll"), b"loader");
2409    write(&root.join("BepInEx/config/BepInEx.cfg"), b"cfg");
2410
2411    let keep: BTreeSet<String> = ["Owner-ModA".to_string()].into_iter().collect();
2412    let removed = remove_delisted(&profile, root, &keep).unwrap();
2413
2414    assert!(root.join("BepInEx/plugins/Owner-ModA/A.dll").exists());
2415    assert!(!root.join("BepInEx/plugins/Owner-ModB").exists());
2416    // A loose loader file in core (not a per-mod folder) and user config survive.
2417    assert!(root.join("BepInEx/core/BepInEx.dll").exists());
2418    assert!(root.join("BepInEx/config/BepInEx.cfg").exists());
2419
2420    assert_eq!(removed.len(), 1);
2421  }
2422
2423  #[test]
2424  #[cfg(feature = "io")]
2425  fn plan_delisted_lists_what_remove_delisted_would_take_without_taking_it() {
2426    let eco = eco();
2427    let profile = profile(&eco, "valheim");
2428
2429    let profile_dir = tempdir().unwrap();
2430    let root = profile_dir.path();
2431
2432    write(&root.join("BepInEx/plugins/Owner-ModA/A.dll"), b"a");
2433    write(&root.join("BepInEx/plugins/Owner-ModB/B.dll"), b"b");
2434    write(&root.join("BepInEx/plugins/Owner-ModC/C.dll"), b"c");
2435    // Not `<Owner-Name>`-shaped, so the sweep never takes it.
2436    write(&root.join("BepInEx/plugins/MMHOOK/hook.dll"), b"hook");
2437
2438    let keep: BTreeSet<String> = ["Owner-ModA".to_string()].into_iter().collect();
2439    let planned = plan_delisted(&profile, root, &keep).unwrap();
2440
2441    // Root-relative and sorted, so a caller listing these one per line gets the
2442    // same order every run rather than whatever `read_dir` happened to yield.
2443    assert_eq!(
2444      planned,
2445      vec![
2446        PathBuf::from("BepInEx/plugins/Owner-ModB"),
2447        PathBuf::from("BepInEx/plugins/Owner-ModC"),
2448      ]
2449    );
2450    // Planning is not applying.
2451    assert!(root.join("BepInEx/plugins/Owner-ModB/B.dll").exists());
2452    assert!(root.join("BepInEx/plugins/Owner-ModC/C.dll").exists());
2453
2454    // What was planned is exactly what the apply takes, because they share the
2455    // one enumeration rather than each deciding for themselves.
2456    let removed = remove_delisted(&profile, root, &keep).unwrap();
2457
2458    assert_eq!(removed, planned);
2459    assert!(!root.join("BepInEx/plugins/Owner-ModB").exists());
2460    assert!(!root.join("BepInEx/plugins/Owner-ModC").exists());
2461    assert!(root.join("BepInEx/plugins/Owner-ModA/A.dll").exists());
2462    assert!(root.join("BepInEx/plugins/MMHOOK/hook.dll").exists());
2463  }
2464
2465  #[test]
2466  #[cfg(feature = "io")]
2467  fn test_remove_delisted_ignores_non_mod_directories() {
2468    let eco = eco();
2469    let profile = profile(&eco, "valheim");
2470
2471    let profile_dir = tempdir().unwrap();
2472    let root = profile_dir.path();
2473
2474    // A per-mod folder (has the `Owner-Name` shape) and a loader-shipped folder
2475    // with no hyphen sitting directly under the namespaced plugins route.
2476    write(&root.join("BepInEx/plugins/Owner-Delete/x.dll"), b"x");
2477    write(&root.join("BepInEx/plugins/MMHOOK/hook.dll"), b"hook");
2478
2479    let keep: BTreeSet<String> = BTreeSet::new();
2480    let removed = remove_delisted(&profile, root, &keep).unwrap();
2481
2482    // The mod folder is reconciled away; the non-ident loader folder is left.
2483    assert!(!root.join("BepInEx/plugins/Owner-Delete").exists());
2484    assert!(root.join("BepInEx/plugins/MMHOOK/hook.dll").exists());
2485    assert_eq!(removed.len(), 1);
2486  }
2487
2488  #[test]
2489  #[cfg(feature = "io")]
2490  fn test_melonloader_flat_routing() {
2491    let eco = eco();
2492    let profile = profile(&eco, "boneworks");
2493
2494    let pkg = tempdir().unwrap();
2495    let root = pkg.path();
2496    write(&root.join("MyMod.dll"), b"dll");
2497    write(&root.join("manifest.json"), b"{}");
2498
2499    let plan = plan_install(&eco, &profile, "Author-MyMod", root, None).unwrap();
2500    let dests = dest_set(&plan);
2501
2502    // .dll routes to Mods (state tracking, not namespaced).
2503    assert!(dests.contains(&"Mods/MyMod.dll".to_string()));
2504    // manifest.json is excluded by the profile's relativeFileExclusions.
2505    assert!(!dests.iter().any(|d| d.contains("manifest.json")));
2506  }
2507
2508  #[test]
2509  #[cfg(feature = "io")]
2510  fn test_melonloader_specific_extension_wins_over_generic() {
2511    let eco = eco();
2512    let profile = profile(&eco, "boneworks");
2513
2514    let pkg = tempdir().unwrap();
2515    let root = pkg.path();
2516
2517    write(&root.join("MyLib.lib.dll"), b"lib");
2518    write(&root.join("MyMod.dll"), b"dll");
2519
2520    let plan = plan_install(&eco, &profile, "Author-MyMod", root, None).unwrap();
2521    let dests = dest_set(&plan);
2522
2523    assert!(dests.contains(&"UserLibs/MyLib.lib.dll".to_string()));
2524    assert!(dests.contains(&"Mods/MyMod.dll".to_string()));
2525  }
2526
2527  #[test]
2528  #[cfg(feature = "io")]
2529  fn test_melonloader_subroute_extension_routing() {
2530    let eco = eco();
2531    let profile = profile(&eco, "bonelab");
2532
2533    let pkg = tempdir().unwrap();
2534    let root = pkg.path();
2535
2536    // A loose .melon routes to the UserData/CustomItems subroute by extension.
2537    write(&root.join("cool.melon"), b"item");
2538    // A file already under UserData routes via folder + subroute extension.
2539    write(&root.join("UserData/other.melon"), b"item2");
2540
2541    let plan = plan_install(&eco, &profile, "Author-MyMod", root, None).unwrap();
2542    let dests = dest_set(&plan);
2543
2544    assert!(dests.contains(&"UserData/CustomItems/cool.melon".to_string()));
2545    assert!(dests.contains(&"UserData/CustomItems/other.melon".to_string()));
2546  }
2547
2548  #[test]
2549  #[cfg(feature = "io")]
2550  fn test_northstar_state_routing_and_exclusions() {
2551    let eco = eco();
2552    let profile = profile(&eco, "northstar");
2553
2554    let pkg = tempdir().unwrap();
2555    let root = pkg.path();
2556
2557    write(&root.join("mods/Author.Mod/mod.json"), b"{}");
2558    write(&root.join("manifest.json"), b"{}");
2559
2560    let plan = plan_install(&eco, &profile, "Author-Mod", root, None).unwrap();
2561    let dests = dest_set(&plan);
2562
2563    // mods/ matches the R2Northstar/mods route (state, structure preserved).
2564    assert!(dests.contains(&"R2Northstar/mods/Author.Mod/mod.json".to_string()));
2565    // manifest.json is excluded.
2566    assert!(!dests.iter().any(|d| d.contains("manifest.json")));
2567  }
2568
2569  #[test]
2570  #[cfg(feature = "io")]
2571  fn test_godotml_package_zip() {
2572    let eco = eco();
2573    let profile = profile(&eco, "brotato");
2574
2575    let pkg = tempdir().unwrap();
2576    let root = pkg.path();
2577    write(&root.join("something.pck"), b"pck");
2578
2579    let archive = pkg.path().join("Author-Mod-1.0.0.zip");
2580    write(&archive, b"zipbytes");
2581
2582    let plan = plan_install(&eco, &profile, "Author-Mod", root, Some(&archive)).unwrap();
2583    let dests = dest_set(&plan);
2584
2585    assert_eq!(dests, vec!["mods/Author-Mod.zip".to_string()]);
2586    assert_eq!(plan.entries[0].tracking, TrackingMethod::PackageZip);
2587
2588    // Without the archive, the package-zip install is skipped rather than wrong.
2589    let empty = plan_install(&eco, &profile, "Author-Mod", root, None).unwrap();
2590    assert!(empty.entries.is_empty());
2591  }
2592
2593  #[test]
2594  #[cfg(feature = "io")]
2595  fn test_plan_install_rejects_traversal_in_package_name() {
2596    let eco = eco();
2597    let profile = profile(&eco, "valheim");
2598
2599    let pkg = tempdir().unwrap();
2600    let root = pkg.path();
2601
2602    write(&root.join("MyMod.dll"), b"dll");
2603
2604    let result = plan_install(&eco, &profile, "../../etc/Author-Evil", root, None);
2605
2606    assert!(result.is_err());
2607  }
2608
2609  #[test]
2610  fn test_ensure_safe_relative_rejects_unsafe_paths() {
2611    assert!(ensure_safe_relative(Path::new("BepInEx/plugins/Author-Mod/x.dll")).is_ok());
2612    assert!(ensure_safe_relative(Path::new("../escape")).is_err());
2613    assert!(ensure_safe_relative(Path::new("a/../../escape")).is_err());
2614    assert!(ensure_safe_relative(Path::new("/abs/path")).is_err());
2615  }
2616
2617  #[cfg(unix)]
2618  #[test]
2619  #[cfg(feature = "io")]
2620  fn test_walk_files_skips_symlinks() {
2621    use std::os::unix::fs::symlink;
2622
2623    let dir = tempdir().unwrap();
2624    let root = dir.path();
2625
2626    write(&root.join("real.txt"), b"real");
2627    symlink("/etc/passwd", root.join("link.txt")).unwrap();
2628
2629    let files = walk_files(root).unwrap();
2630
2631    assert!(files.iter().any(|p| p.ends_with("real.txt")));
2632    assert!(!files.iter().any(|p| p.ends_with("link.txt")));
2633  }
2634
2635  #[test]
2636  fn state_tracker_collects_only_state_entries() {
2637    let plan = InstallPlan {
2638      entries: vec![
2639        InstallEntry {
2640          source: PathBuf::from("/cache/Author-Mod/1.0.0/loader.dll"),
2641          dest_relative: PathBuf::from("BepInEx/core/loader.dll"),
2642          tracking: TrackingMethod::State,
2643        },
2644        InstallEntry {
2645          source: PathBuf::from("/cache/Author-Mod/1.0.0/plugin.dll"),
2646          dest_relative: PathBuf::from("BepInEx/plugins/Author-Mod/plugin.dll"),
2647          tracking: TrackingMethod::Subdir,
2648        },
2649      ],
2650    };
2651
2652    let tracker = state_tracker_from_plan(&plan, "Author-Mod").unwrap();
2653
2654    assert_eq!(tracker.mod_name, "Author-Mod");
2655    assert_eq!(tracker.files.len(), 1);
2656    assert_eq!(tracker.files[0].1, "BepInEx/core/loader.dll");
2657  }
2658
2659  #[test]
2660  fn state_tracker_none_when_no_state_entries() {
2661    let plan = InstallPlan {
2662      entries: vec![InstallEntry {
2663        source: PathBuf::from("/cache/x/plugin.dll"),
2664        dest_relative: PathBuf::from("BepInEx/plugins/Author-Mod/plugin.dll"),
2665        tracking: TrackingMethod::Subdir,
2666      }],
2667    };
2668
2669    assert!(state_tracker_from_plan(&plan, "Author-Mod").is_none());
2670  }
2671
2672  #[test]
2673  #[cfg(feature = "io")]
2674  fn remove_state_payload_deletes_files_then_tracker() {
2675    let dir = tempdir().unwrap();
2676    let root = dir.path();
2677
2678    write(&root.join("BepInEx/core/loader.dll"), b"loader");
2679
2680    let tracker = ModFileTracker {
2681      mod_name: "Author-Loader".to_string(),
2682      files: vec![
2683        (
2684          "/cache/loader.dll".to_string(),
2685          "BepInEx/core/loader.dll".to_string(),
2686        ),
2687        // An already-removed payload (e.g. the mod was disabled first) is skipped.
2688        (
2689          "/cache/gone.dll".to_string(),
2690          "BepInEx/core/gone.dll".to_string(),
2691        ),
2692      ],
2693    };
2694
2695    write_state_file(root, &tracker).unwrap();
2696    remove_state_payload(root, "Author-Loader").unwrap();
2697
2698    assert!(!root.join("BepInEx/core/loader.dll").exists());
2699    assert!(!state_file_path(root, "Author-Loader").exists());
2700
2701    // A mod that tracked no `State` files has no `_state` file: a no-op, not an error.
2702    assert!(remove_state_payload(root, "Author-Untracked").is_ok());
2703  }
2704
2705  #[test]
2706  #[cfg(feature = "io")]
2707  fn remove_state_payload_rejects_traversal_in_tracker() {
2708    let dir = tempdir().unwrap();
2709    let root = dir.path().join("profile");
2710
2711    let outside = dir.path().join("secret.txt");
2712    write(&outside, b"secret");
2713
2714    let tracker = ModFileTracker {
2715      mod_name: "Author-Evil".to_string(),
2716      files: vec![("/cache/x".to_string(), "../secret.txt".to_string())],
2717    };
2718
2719    write_state_file(&root, &tracker).unwrap();
2720
2721    // A hand-edited tracker cannot delete a file outside the profile root.
2722    assert!(remove_state_payload(&root, "Author-Evil").is_err());
2723    assert!(outside.exists());
2724  }
2725
2726  #[test]
2727  #[cfg(feature = "io")]
2728  fn enable_refuses_a_tracker_that_points_outside_the_profile() {
2729    let eco = eco();
2730    let profile = profile(&eco, "valheim");
2731    let dir = tempdir().unwrap();
2732    let root = dir.path().join("profile");
2733    let source = dir.path().join("cache/payload.dll");
2734    let outside = dir.path().join("outside.dll");
2735    let absolute = dir.path().join("absolute.dll");
2736
2737    write(&source, b"payload");
2738    write(
2739      &root.join("BepInEx/plugins/Author-Evil/plugin.dll.old"),
2740      b"dll",
2741    );
2742
2743    for escape in [
2744      "../outside.dll".to_string(),
2745      absolute.to_string_lossy().to_string(),
2746    ] {
2747      let tracker = ModFileTracker {
2748        mod_name: "Author-Evil".to_string(),
2749        files: vec![
2750          (
2751            source.to_string_lossy().to_string(),
2752            "BepInEx/core/ok.dll".to_string(),
2753          ),
2754          (source.to_string_lossy().to_string(), escape.clone()),
2755        ],
2756      };
2757
2758      write_state_file(&root, &tracker).unwrap();
2759
2760      assert!(
2761        enable_mod(&profile, &root, "Author-Evil").is_err(),
2762        "{escape:?} must be refused"
2763      );
2764      assert!(!outside.exists() && !absolute.exists(), "for {escape:?}");
2765      // Refused before anything moved, so the mod is still wholly disabled.
2766      assert!(!root.join("BepInEx/core/ok.dll").exists(), "for {escape:?}");
2767      assert!(
2768        root
2769          .join("BepInEx/plugins/Author-Evil/plugin.dll.old")
2770          .exists(),
2771        "for {escape:?}"
2772      );
2773    }
2774  }
2775
2776  #[test]
2777  #[cfg(feature = "io")]
2778  fn enable_restores_only_files_from_the_mods_own_package_cache() {
2779    let eco = eco();
2780    let profile = profile(&eco, "valheim");
2781    let dir = tempdir().unwrap();
2782    let root = dir.path().join("profile");
2783    let cached = dir.path().join("cache/Author-Evil/1.0.0");
2784    let secret = dir.path().join("home/.ssh/id_rsa");
2785
2786    write(&cached.join("ok.dll"), b"payload");
2787    write(&cached.join("evil.cfg"), b"imported");
2788    write(&secret, b"secret");
2789
2790    for (source, dest) in [
2791      (secret.clone(), "BepInEx/config/id_rsa"),
2792      (cached.join("evil.cfg"), "BepInEx/core/evil.dll"),
2793      (
2794        dir.path().join("cache/Other-Mod/1.0.0/ok.dll"),
2795        "BepInEx/core/ok.dll",
2796      ),
2797    ] {
2798      let tracker = ModFileTracker {
2799        mod_name: "Author-Evil".to_string(),
2800        files: vec![(source.to_string_lossy().to_string(), dest.to_string())],
2801      };
2802
2803      write_state_file(&root, &tracker).unwrap();
2804
2805      assert!(
2806        enable_mod(&profile, &root, "Author-Evil").is_err(),
2807        "{source:?} must be refused"
2808      );
2809      assert!(!root.join(dest).exists(), "for {source:?}");
2810    }
2811
2812    let tracker = ModFileTracker {
2813      mod_name: "Author-Evil".to_string(),
2814      files: vec![(
2815        cached.join("ok.dll").to_string_lossy().to_string(),
2816        "BepInEx/core/ok.dll".to_string(),
2817      )],
2818    };
2819
2820    write_state_file(&root, &tracker).unwrap();
2821    enable_mod(&profile, &root, "Author-Evil").unwrap();
2822
2823    assert_eq!(
2824      fs::read(root.join("BepInEx/core/ok.dll")).unwrap(),
2825      b"payload"
2826    );
2827  }
2828
2829  #[test]
2830  #[cfg(feature = "io")]
2831  fn state_file_round_trips() {
2832    let dir = tempdir().unwrap();
2833    let tracker = ModFileTracker {
2834      mod_name: "Author-Mod".to_string(),
2835      files: vec![("/cache/a".to_string(), "BepInEx/core/a.dll".to_string())],
2836    };
2837
2838    write_state_file(dir.path(), &tracker).unwrap();
2839
2840    assert!(dir.path().join("_state/Author-Mod-state.yml").exists());
2841
2842    let back = read_state_file(dir.path(), "Author-Mod").unwrap().unwrap();
2843
2844    assert_eq!(back.mod_name, "Author-Mod");
2845    assert_eq!(back.files, tracker.files);
2846    assert!(read_state_file(dir.path(), "Missing").unwrap().is_none());
2847  }
2848
2849  #[test]
2850  fn plan_suffix_renames_adds_and_strips_old() {
2851    let files = vec![
2852      PathBuf::from("a/b/plugin.dll"),
2853      PathBuf::from("a/b/data.cfg.old"),
2854    ];
2855
2856    let disable = plan_suffix_renames(&files, true);
2857
2858    // plugin.dll -> plugin.dll.old ; the already-.old file is left alone (omitted).
2859    assert_eq!(
2860      disable,
2861      vec![(
2862        PathBuf::from("a/b/plugin.dll"),
2863        PathBuf::from("a/b/plugin.dll.old"),
2864      )]
2865    );
2866
2867    let enable = plan_suffix_renames(&files, false);
2868
2869    // data.cfg.old -> data.cfg ; the non-.old file is left alone.
2870    assert_eq!(
2871      enable,
2872      vec![(
2873        PathBuf::from("a/b/data.cfg.old"),
2874        PathBuf::from("a/b/data.cfg"),
2875      )]
2876    );
2877  }
2878
2879  #[test]
2880  #[cfg(feature = "io")]
2881  fn disable_enable_subdir_renames_files() {
2882    let eco = eco();
2883    let profile = profile(&eco, "valheim");
2884
2885    let profile_dir = tempdir().unwrap();
2886    let root = profile_dir.path();
2887    write(&root.join("BepInEx/plugins/Author-Mod/plugin.dll"), b"x");
2888
2889    disable_mod(&profile, root, "Author-Mod").unwrap();
2890
2891    assert!(!root.join("BepInEx/plugins/Author-Mod/plugin.dll").exists());
2892    assert!(
2893      root
2894        .join("BepInEx/plugins/Author-Mod/plugin.dll.old")
2895        .exists()
2896    );
2897
2898    enable_mod(&profile, root, "Author-Mod").unwrap();
2899
2900    assert!(root.join("BepInEx/plugins/Author-Mod/plugin.dll").exists());
2901  }
2902
2903  #[test]
2904  #[cfg(feature = "io")]
2905  fn disable_enable_state_removes_and_restores_from_cache() {
2906    let eco = eco();
2907    let profile = profile(&eco, "valheim");
2908
2909    let profile_dir = tempdir().unwrap();
2910    let root = profile_dir.path();
2911
2912    // A cached source file and its installed copy under a State route.
2913    let cache = tempdir().unwrap();
2914    let src = cache.path().join("cache/Author-Loader/1.0.0/loader.dll");
2915    write(&src, b"loader");
2916    write(&root.join("BepInEx/core/loader.dll"), b"loader");
2917
2918    let tracker = ModFileTracker {
2919      mod_name: "Author-Loader".to_string(),
2920      files: vec![(
2921        src.to_string_lossy().to_string(),
2922        "BepInEx/core/loader.dll".to_string(),
2923      )],
2924    };
2925    write_state_file(root, &tracker).unwrap();
2926
2927    disable_mod(&profile, root, "Author-Loader").unwrap();
2928
2929    assert!(!root.join("BepInEx/core/loader.dll").exists());
2930
2931    enable_mod(&profile, root, "Author-Loader").unwrap();
2932
2933    assert!(root.join("BepInEx/core/loader.dll").exists());
2934  }
2935
2936  fn listed(files: &[&str]) -> Vec<PathBuf> {
2937    files.iter().map(PathBuf::from).collect()
2938  }
2939
2940  #[test]
2941  fn plan_install_from_routes_a_listed_regular_mod() {
2942    let eco = eco();
2943    let profile = profile(&eco, "valheim");
2944    let root = Path::new("/cache/Author-Mod/1.0.0");
2945
2946    let plan = plan_install_from(
2947      &eco,
2948      &profile,
2949      "Author-Mod",
2950      root,
2951      &listed(&["plugins/Mod.dll", "config/Mod.cfg"]),
2952      None,
2953    )
2954    .unwrap();
2955
2956    let routed = plan
2957      .entries
2958      .iter()
2959      .find(|entry| entry.dest_relative == Path::new("BepInEx/plugins/Author-Mod/Mod.dll"))
2960      .unwrap();
2961
2962    assert_eq!(routed.source, root.join("plugins/Mod.dll"));
2963    assert!(dest_set(&plan).contains(&"BepInEx/config/Mod.cfg".to_string()));
2964  }
2965
2966  #[test]
2967  fn plan_install_from_skips_the_folder_entries_an_archive_lists() {
2968    let eco = eco();
2969    let profile = profile(&eco, "valheim");
2970
2971    let regular = plan_install_from(
2972      &eco,
2973      &profile,
2974      "Author-Mod",
2975      Path::new("/cache/Author-Mod/1.0.0"),
2976      &listed(&["plugins/", "plugins/Mod.dll", "config\\", "config/Mod.cfg"]),
2977      None,
2978    )
2979    .unwrap();
2980    let pack = plan_install_from(
2981      &eco,
2982      &profile,
2983      "denikson-BepInExPack_Valheim",
2984      Path::new("/cache/pack"),
2985      &listed(&[
2986        "BepInExPack_Valheim/",
2987        "BepInExPack_Valheim/BepInEx/",
2988        "BepInExPack_Valheim/BepInEx/core/BepInEx.dll",
2989      ]),
2990      None,
2991    )
2992    .unwrap();
2993
2994    assert_eq!(
2995      dest_set(&regular),
2996      [
2997        "BepInEx/config/Mod.cfg",
2998        "BepInEx/plugins/Author-Mod/Mod.dll"
2999      ]
3000    );
3001    assert_eq!(dest_set(&pack), ["BepInEx/core/BepInEx.dll"]);
3002  }
3003
3004  #[test]
3005  fn plan_install_from_is_independent_of_listing_order() {
3006    let eco = eco();
3007    let profile = profile(&eco, "valheim");
3008    let root = Path::new("/cache/Author-Mod");
3009    let files = listed(&["plugins/b.dll", "plugins/a.dll", "README.md"]);
3010    let mut reversed = files.clone();
3011
3012    reversed.reverse();
3013
3014    let forward = plan_install_from(&eco, &profile, "Author-Mod", root, &files, None).unwrap();
3015    let backward = plan_install_from(&eco, &profile, "Author-Mod", root, &reversed, None).unwrap();
3016
3017    assert_eq!(forward.entries, backward.entries);
3018  }
3019
3020  #[test]
3021  fn plan_install_from_unpacks_a_listed_loader_pack_from_its_root_folder() {
3022    let eco = eco();
3023    let profile = profile(&eco, "valheim");
3024    let root = Path::new("/cache/pack");
3025
3026    let plan = plan_install_from(
3027      &eco,
3028      &profile,
3029      "denikson-BepInExPack_Valheim",
3030      root,
3031      &listed(&[
3032        "manifest.json",
3033        "icon.png",
3034        "BepInExPack_Valheim/winhttp.dll",
3035        "BepInExPack_Valheim/BepInEx/core/BepInEx.dll",
3036      ]),
3037      None,
3038    )
3039    .unwrap();
3040
3041    assert_eq!(
3042      dest_set(&plan),
3043      vec![
3044        "BepInEx/core/BepInEx.dll".to_string(),
3045        "winhttp.dll".to_string()
3046      ]
3047    );
3048    assert!(
3049      plan
3050        .entries
3051        .iter()
3052        .any(|entry| entry.source == root.join("BepInExPack_Valheim/winhttp.dll"))
3053    );
3054  }
3055
3056  #[test]
3057  fn plan_install_from_falls_back_to_the_package_root_without_the_root_folder() {
3058    let eco = eco();
3059    let profile = profile(&eco, "valheim");
3060
3061    let plan = plan_install_from(
3062      &eco,
3063      &profile,
3064      "denikson-BepInExPack_Valheim",
3065      Path::new("/cache/pack"),
3066      &listed(&["manifest.json", "winhttp.dll", "BepInEx/core/BepInEx.dll"]),
3067      None,
3068    )
3069    .unwrap();
3070
3071    assert_eq!(
3072      dest_set(&plan),
3073      vec![
3074        "BepInEx/core/BepInEx.dll".to_string(),
3075        "winhttp.dll".to_string()
3076      ]
3077    );
3078  }
3079
3080  #[test]
3081  fn plan_install_from_rejects_listed_paths_that_escape_the_root() {
3082    let eco = eco();
3083    let profile = profile(&eco, "valheim");
3084    let root = Path::new("/cache/Author-Mod");
3085
3086    for bad in ["../outside.dll", "/etc/passwd"] {
3087      let result = plan_install_from(&eco, &profile, "Author-Mod", root, &listed(&[bad]), None);
3088
3089      assert!(
3090        matches!(result, Err(Error::Install(_))),
3091        "{bad} was accepted"
3092      );
3093    }
3094  }
3095
3096  #[test]
3097  fn plan_install_from_refuses_files_flattened_onto_one_destination() {
3098    let eco = eco();
3099    let profile = profile(&eco, "valheim");
3100
3101    let result = plan_install_from(
3102      &eco,
3103      &profile,
3104      "Author-Mod",
3105      Path::new("/cache/Author-Mod"),
3106      &listed(&["one/Mod.dll", "two/Mod.dll"]),
3107      None,
3108    );
3109
3110    assert!(matches!(result, Err(Error::Install(_))));
3111  }
3112
3113  #[test]
3114  fn plan_install_from_needs_no_listing_for_a_whole_archive_install() {
3115    let eco = eco();
3116    let profile = profile(&eco, "brotato");
3117    let archive = Path::new("/downloads/Author-Mod-1.0.0.zip");
3118
3119    let plan = plan_install_from(
3120      &eco,
3121      &profile,
3122      "Author-Mod",
3123      Path::new("/cache/Author-Mod"),
3124      &[],
3125      Some(archive),
3126    )
3127    .unwrap();
3128
3129    assert_eq!(dest_set(&plan), vec!["mods/Author-Mod.zip".to_string()]);
3130    assert_eq!(plan.entries[0].source, archive);
3131  }
3132
3133  #[test]
3134  #[cfg(feature = "io")]
3135  fn plan_install_matches_plan_install_from_over_the_walked_files() {
3136    let eco = eco();
3137    let profile = profile(&eco, "valheim");
3138    let pkg = tempdir().unwrap();
3139    let root = pkg.path();
3140
3141    write(&root.join("manifest.json"), b"{}");
3142    write(&root.join("plugins/Mod.dll"), b"dll");
3143    write(&root.join("plugins/sub/Extra.dll"), b"dll");
3144    write(&root.join("config/Mod.cfg"), b"cfg");
3145
3146    let walked = plan_install(&eco, &profile, "Author-Mod", root, None).unwrap();
3147    let listed = plan_install_from(
3148      &eco,
3149      &profile,
3150      "Author-Mod",
3151      root,
3152      &listed(&[
3153        "config/Mod.cfg",
3154        "manifest.json",
3155        "plugins/Mod.dll",
3156        "plugins/sub/Extra.dll",
3157      ]),
3158      None,
3159    )
3160    .unwrap();
3161
3162    assert_eq!(walked.entries, listed.entries);
3163  }
3164
3165  #[test]
3166  fn namespaced_routes_lists_each_per_mod_route() {
3167    let eco = eco();
3168    let routes = namespaced_routes(&profile(&eco, "valheim")).unwrap();
3169
3170    assert!(routes.contains(&PathBuf::from("BepInEx/plugins")));
3171    assert!(!routes.contains(&PathBuf::from("BepInEx/config")));
3172  }
3173
3174  #[test]
3175  fn plan_delisted_from_selects_unkept_mod_folders_only() {
3176    let keep = BTreeSet::from(["Owner-Kept".to_string()]);
3177    let listing = [
3178      RouteEntry::new("BepInEx/plugins/Owner-Kept", true, false),
3179      RouteEntry::new("BepInEx/plugins/Owner-Gone", true, false),
3180      RouteEntry::new("BepInEx/patchers/Owner-Gone", true, false),
3181      RouteEntry::new("BepInEx/plugins/Owner-Linked", true, true),
3182      RouteEntry::new("BepInEx/plugins/Owner-File", false, false),
3183      RouteEntry::new("BepInEx/plugins/MMHOOK", true, false),
3184      RouteEntry::new("BepInEx/plugins/Owner-Gone", true, false),
3185    ];
3186
3187    assert_eq!(
3188      plan_delisted_from(&listing, &keep),
3189      vec![
3190        PathBuf::from("BepInEx/patchers/Owner-Gone"),
3191        PathBuf::from("BepInEx/plugins/Owner-Gone"),
3192      ]
3193    );
3194  }
3195}