1#![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#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40#[non_exhaustive]
41pub struct ModFileTracker {
42 pub mod_name: String,
44 pub files: Vec<(String, String)>,
46}
47
48pub 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#[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
112pub 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#[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#[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#[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#[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#[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
192fn 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#[derive(Debug, Clone, PartialEq, Eq)]
216#[non_exhaustive]
217pub struct InstallEntry {
218 pub source: PathBuf,
221 pub dest_relative: PathBuf,
223 pub tracking: TrackingMethod,
226}
227
228#[derive(Debug, Clone, Default)]
230#[non_exhaustive]
231pub struct InstallPlan {
232 pub entries: Vec<InstallEntry>,
234}
235
236#[derive(Debug, Clone, Default)]
238#[non_exhaustive]
239pub struct FileManifest {
240 pub written: Vec<PathBuf>,
242}
243
244#[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
297pub 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
367fn 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#[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
387fn 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
394fn 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
447fn 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
482fn 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 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
526fn 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#[derive(Debug, Clone, PartialEq, Eq)]
548enum RouteOutcome {
549 Route {
552 dest_relative: PathBuf,
553 tracking: TrackingMethod,
554 },
555 Skip(SkipReason),
557}
558
559#[derive(Debug, Clone, PartialEq, Eq)]
561enum SkipReason {
562 NoName,
564 Excluded,
566 NoRoute,
568 UnsupportedTracking(TrackingMethod),
571}
572
573fn 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
627fn 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
641fn 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
665struct FlatRule<'a> {
667 full_route: PathBuf,
668 rule: &'a InstallRule,
669}
670
671#[derive(Debug, Clone, PartialEq, Eq)]
674struct RouteResolution {
675 route: PathBuf,
676 tracking: TrackingMethod,
677 remainder: PathBuf,
678}
679
680fn 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
697fn 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
717fn 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 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 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
772fn 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
788fn 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
809fn 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
827fn build_dest(
831 route: &Path,
832 tracking: TrackingMethod,
833 ident: &str,
834 remainder: &Path,
835) -> Option<PathBuf> {
836 match tracking {
837 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
848fn route_leaf(route: &str) -> &str {
851 route.rsplit(['/', '\\']).next().unwrap_or(route)
852}
853
854fn 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
865fn 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
881fn 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#[cfg(feature = "io")]
928pub fn apply_install(plan: &InstallPlan, root: &Path) -> Result<FileManifest> {
929 apply_install_reporting(plan, root, &mut |_, _| {})
930}
931
932#[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 ApplyAction::SkipExistingConfig => continue,
964 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
998#[cfg(feature = "io")]
999enum ApplyAction {
1000 Write { record: bool },
1003 SkipExistingConfig,
1005 RefuseSymlink,
1007}
1008
1009#[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#[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#[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#[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#[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
1170pub 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#[derive(Debug, Clone, PartialEq, Eq)]
1198#[non_exhaustive]
1199pub struct RouteEntry {
1200 pub path: PathBuf,
1203 pub is_dir: bool,
1205 pub is_symlink: bool,
1207}
1208
1209impl RouteEntry {
1210 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
1220pub 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#[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#[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
1332fn 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
1359fn 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#[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(¤t)
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 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
1407pub 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#[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#[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#[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#[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#[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#[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#[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#[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 assert!(dests.contains(&"BepInEx/plugins/Author-MyMod/manifest.json".to_string()));
1667 assert!(dests.contains(&"BepInEx/config/MyMod.cfg".to_string()));
1669 assert!(dests.contains(&"BepInEx/patchers/Author-MyMod/MyPatcher.dll".to_string()));
1671 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 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 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 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 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 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 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 let listing = vec![
1775 (PathBuf::from("Author-Keep"), true, false), (PathBuf::from("Author-Drop"), true, false), (PathBuf::from("MMHOOK"), true, false), (PathBuf::from("Author-Link"), true, true), (PathBuf::from("Author-File"), false, false), ];
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 assert_eq!(
1794 classify_loader_file(Path::new("manifest.json"), &untracked, &exclusions).unwrap(),
1795 None
1796 );
1797
1798 assert_eq!(
1800 classify_loader_file(Path::new("LICENCE"), &untracked, &exclusions).unwrap(),
1801 None
1802 );
1803
1804 assert_eq!(
1806 classify_loader_file(Path::new("BepInEx/config/x.cfg"), &untracked, &exclusions).unwrap(),
1807 Some(TrackingMethod::None)
1808 );
1809
1810 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 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 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 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 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 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 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 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 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 let profile = profile(&eco, "boneworks");
2197
2198 let pkg = tempdir().unwrap();
2199 let root = pkg.path();
2200
2201 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 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 assert!(result.is_err());
2310 assert!(!root.join("BepInEx/plugins/Author-Mod/good.dll").exists());
2311 assert!(!root.join("BepInEx/plugins/Author-Mod").exists());
2314 assert!(!root.join("BepInEx/plugins").exists());
2315 assert!(!root.join("BepInEx").exists());
2316 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 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 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 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 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 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 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 assert_eq!(
2444 planned,
2445 vec![
2446 PathBuf::from("BepInEx/plugins/Owner-ModB"),
2447 PathBuf::from("BepInEx/plugins/Owner-ModC"),
2448 ]
2449 );
2450 assert!(root.join("BepInEx/plugins/Owner-ModB/B.dll").exists());
2452 assert!(root.join("BepInEx/plugins/Owner-ModC/C.dll").exists());
2453
2454 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 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 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 assert!(dests.contains(&"Mods/MyMod.dll".to_string()));
2504 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 write(&root.join("cool.melon"), b"item");
2538 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 assert!(dests.contains(&"R2Northstar/mods/Author.Mod/mod.json".to_string()));
2565 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 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 (
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 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 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 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 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 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 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(®ular),
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}