1#![deny(missing_docs)]
47
48pub mod cache;
50pub mod launch;
52pub mod layout;
54pub mod modlist;
56pub mod portability;
58#[cfg(feature = "io")]
60pub mod target;
61
62#[cfg(feature = "io")]
63use crate::client::ThunderstoreClient;
64use crate::ecosystem::Ecosystem;
65use crate::error::{Error, Result};
66#[cfg(feature = "io")]
67use crate::extract::parse_package_filename;
68#[cfg(feature = "io")]
69use crate::install::{
70 apply_install_reporting, clear_state_files, plan_install, remove_mod_folders, remove_state_file,
71 remove_state_payload, state_tracker_from_plan, write_state_file,
72};
73use crate::models::Version;
74#[cfg(feature = "io")]
75use crate::models::{DependencyGraph, PackageIndex};
76#[cfg(feature = "io")]
77use crate::progress::{Operation, Stage, StageProgress};
78use modlist::{ProfileMod, SemVer};
79#[cfg(feature = "io")]
80use std::collections::BTreeSet;
81#[cfg(feature = "io")]
82use std::collections::HashMap;
83use std::path::{Path, PathBuf};
84#[cfg(feature = "io")]
85use std::sync::Arc;
86
87pub fn mod_entry_from_version(
92 full_name: &str,
93 owner: &str,
94 version: &Version,
95 installed_at_time: u64,
96) -> ProfileMod {
97 let version_number = version
98 .version_number
99 .as_deref()
100 .map(SemVer::parse)
101 .unwrap_or(SemVer {
102 major: 0,
103 minor: 0,
104 patch: 0,
105 });
106
107 ProfileMod {
108 manifest_version: 1,
109 name: full_name.to_string(),
110 author_name: owner.to_string(),
111 website_url: version.website_url.clone().unwrap_or_default(),
112 display_name: version
113 .name
114 .clone()
115 .unwrap_or_else(|| full_name.to_string()),
116 description: version.description.clone().unwrap_or_default(),
117 game_version: "0".to_string(),
118 network_mode: "both".to_string(),
119 package_type: "other".to_string(),
120 install_mode: "managed".to_string(),
121 installed_at_time,
122 loaders: Vec::new(),
123 dependencies: version.dependencies.clone(),
124 incompatibilities: Vec::new(),
125 optional_dependencies: Vec::new(),
126 version_number,
127 enabled: true,
128 icon: version.icon.clone().unwrap_or_default(),
129 online_source: true,
130 trusted_package: false,
131 }
132}
133
134#[derive(Debug, Clone, Default)]
140#[non_exhaustive]
141pub struct BatchOutcome {
142 pub succeeded: Vec<String>,
154 pub unchanged: Vec<String>,
159 pub failed: Vec<(String, Error)>,
161 pub kept_untracked: Vec<PathBuf>,
165 pub cancelled: Vec<String>,
173 pub re_enabled: Vec<String>,
177 pub kept_disabled: Vec<String>,
182}
183
184impl BatchOutcome {
185 pub fn is_ok(&self) -> bool {
187 self.failed.is_empty() && self.cancelled.is_empty()
188 }
189}
190
191#[derive(Debug, Clone, Default)]
194#[non_exhaustive]
195pub struct InstallBatch {
196 pub desired: Vec<String>,
199 pub protect_disabled: Vec<String>,
205 pub enable_requested: Vec<String>,
212 pub force: bool,
216}
217
218impl InstallBatch {
219 pub fn new(desired: Vec<String>, protect_disabled: Vec<String>) -> Self {
223 Self {
224 desired,
225 protect_disabled,
226 ..Self::default()
227 }
228 }
229}
230
231#[cfg(feature = "io")]
241pub fn plan_install_batch(
242 target_dir: &Path,
243 desired: &[String],
244 explicit: &[String],
245) -> Result<InstallBatch> {
246 let recorded = modlist::read(target_dir)?;
247
248 Ok(plan_install_batch_from(&recorded, desired, explicit))
249}
250
251pub fn plan_install_batch_from(
259 recorded: &[ProfileMod],
260 desired: &[String],
261 explicit: &[String],
262) -> InstallBatch {
263 let (enable_requested, protect_disabled): (Vec<String>, Vec<String>) = recorded
264 .iter()
265 .filter(|entry| !entry.enabled)
266 .map(|entry| entry.name.clone())
267 .partition(|name| {
268 explicit
269 .iter()
270 .any(|requested| crate::util::full_name_prefix(requested) == name.as_str())
271 });
272
273 InstallBatch {
274 desired: desired.to_vec(),
275 protect_disabled,
276 enable_requested,
277 force: false,
278 }
279}
280
281#[cfg(feature = "io")]
290pub fn reapply_batch_disabled(
291 target_dir: &Path,
292 eco: &Ecosystem,
293 game: &str,
294 batch: &InstallBatch,
295) -> Result<()> {
296 let recorded = modlist::read(target_dir)?;
297
298 for full_name in &batch.protect_disabled {
299 if !recorded.iter().any(|entry| &entry.name == full_name) {
300 continue;
301 }
302
303 set_enabled_in(target_dir, eco, game, full_name, false)?;
304 }
305
306 Ok(())
307}
308
309#[allow(clippy::too_many_arguments)]
323#[cfg(feature = "io")]
324pub fn install_extracted_in(
325 target_dir: &Path,
326 eco: &Ecosystem,
327 game: &str,
328 full_name: &str,
329 owner: &str,
330 version: &Version,
331 extracted_dir: &Path,
332 archive: Option<&Path>,
333 installed_at_time: u64,
334) -> Result<()> {
335 install_extracted_reporting(
336 target_dir,
337 eco,
338 game,
339 full_name,
340 owner,
341 version,
342 extracted_dir,
343 archive,
344 installed_at_time,
345 &mut |_, _| {},
346 )
347}
348
349#[allow(clippy::too_many_arguments)]
351#[cfg(feature = "io")]
352fn install_extracted_reporting(
353 target_dir: &Path,
354 eco: &Ecosystem,
355 game: &str,
356 full_name: &str,
357 owner: &str,
358 version: &Version,
359 extracted_dir: &Path,
360 archive: Option<&Path>,
361 installed_at_time: u64,
362 on_progress: &mut dyn FnMut(u64, u64),
363) -> Result<()> {
364 let game_profile = eco.require_profile(game)?;
365
366 let plan = plan_install(eco, game_profile, full_name, extracted_dir, archive)?;
367
368 clear_state_files(target_dir, full_name)?;
374 remove_mod_folders(game_profile, target_dir, full_name)?;
375 apply_install_reporting(&plan, target_dir, on_progress)?;
376
377 match state_tracker_from_plan(&plan, full_name) {
378 Some(tracker) => write_state_file(target_dir, &tracker)?,
379 None => remove_state_file(target_dir, full_name)?,
380 }
381
382 let mut mods = modlist::read(target_dir)?;
383
384 modlist::upsert(
385 &mut mods,
386 mod_entry_from_version(full_name, owner, version, installed_at_time),
387 );
388
389 modlist::write(target_dir, &mods)
390}
391
392#[allow(clippy::too_many_arguments)]
395#[cfg(feature = "io")]
396pub fn install_extracted(
397 base: &Path,
398 eco: &Ecosystem,
399 game: &str,
400 profile_name: &str,
401 full_name: &str,
402 owner: &str,
403 version: &Version,
404 extracted_dir: &Path,
405 archive: Option<&Path>,
406 installed_at_time: u64,
407) -> Result<()> {
408 install_extracted_in(
409 &layout::profile_dir(base, game, profile_name),
410 eco,
411 game,
412 full_name,
413 owner,
414 version,
415 extracted_dir,
416 archive,
417 installed_at_time,
418 )
419}
420
421#[derive(Debug)]
436pub enum NotRemovable {
437 RecordAbsent {
440 name: String,
442 path: PathBuf,
444 },
445 RecordUnreadable {
448 name: String,
450 path: PathBuf,
452 source: Error,
454 },
455}
456
457impl std::fmt::Display for NotRemovable {
458 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
459 match self {
460 Self::RecordAbsent { name, path } => write!(
461 f,
462 "{name} is a mod loader with no install record at {}, so its files \
463 cannot be removed exactly. Reinstall it, then uninstall it again, or \
464 remove its files by hand.",
465 path.display()
466 ),
467 Self::RecordUnreadable { name, path, source } => write!(
468 f,
469 "{name} has an install record at {} that cannot be read, so its files \
470 cannot be removed exactly: {source}",
471 path.display()
472 ),
473 }
474 }
475}
476
477impl From<NotRemovable> for Error {
478 fn from(value: NotRemovable) -> Self {
479 Error::Profile(value.to_string())
480 }
481}
482
483#[cfg(feature = "io")]
519pub fn ensure_removable(
520 target_dir: &Path,
521 eco: &Ecosystem,
522 full_name: &str,
523) -> std::result::Result<(), NotRemovable> {
524 check_removable_from(
525 target_dir,
526 eco,
527 full_name,
528 read_record_state(target_dir, full_name),
529 )
530}
531
532#[derive(Debug)]
537pub enum RecordState {
538 Present,
540 Absent,
542 Unreadable(Error),
544}
545
546#[cfg(feature = "io")]
549pub fn read_record_state(target_dir: &Path, full_name: &str) -> RecordState {
550 match crate::install::read_state_file(target_dir, full_name) {
551 Ok(Some(_)) => RecordState::Present,
552 Ok(None) => RecordState::Absent,
553 Err(source) => RecordState::Unreadable(source),
554 }
555}
556
557pub fn check_removable_from(
564 target_dir: &Path,
565 eco: &Ecosystem,
566 full_name: &str,
567 record: RecordState,
568) -> std::result::Result<(), NotRemovable> {
569 match record {
570 RecordState::Present => return Ok(()),
571 RecordState::Absent => {}
572 RecordState::Unreadable(source) => {
573 return Err(NotRemovable::RecordUnreadable {
574 name: full_name.to_string(),
575 path: crate::install::state_file_path(target_dir, full_name),
576 source,
577 });
578 }
579 }
580
581 if eco.modloader_package(full_name).is_none() {
582 return Ok(());
583 }
584
585 Err(NotRemovable::RecordAbsent {
586 name: full_name.to_string(),
587 path: crate::install::state_file_path(target_dir, full_name),
588 })
589}
590
591#[cfg(feature = "io")]
612pub fn uninstall_mod_in(
613 target_dir: &Path,
614 eco: &Ecosystem,
615 game: &str,
616 full_name: &str,
617) -> Result<()> {
618 let game_profile = eco.require_profile(game)?;
619
620 ensure_removable(target_dir, eco, full_name)?;
626
627 let mut mods = modlist::read(target_dir)?;
628
629 if modlist::find(&mods, full_name).is_none() {
630 return Err(Error::NotInstalled {
631 package: full_name.to_string(),
632 });
633 }
634
635 mods.retain(|m| m.name != full_name);
636
637 remove_mod_folders(game_profile, target_dir, full_name)?;
638 remove_state_payload(target_dir, full_name)?;
639
640 modlist::write(target_dir, &mods)
641}
642
643#[cfg(feature = "io")]
645pub fn uninstall_mod(
646 base: &Path,
647 eco: &Ecosystem,
648 game: &str,
649 profile_name: &str,
650 full_name: &str,
651) -> Result<()> {
652 uninstall_mod_in(
653 &layout::profile_dir(base, game, profile_name),
654 eco,
655 game,
656 full_name,
657 )
658}
659
660#[cfg(feature = "io")]
668pub fn set_enabled_in(
669 target_dir: &Path,
670 eco: &Ecosystem,
671 game: &str,
672 full_name: &str,
673 enabled: bool,
674) -> Result<()> {
675 let game_profile = eco.require_profile(game)?;
676
677 let mut mods = modlist::read(target_dir)?;
678
679 let entry = mods
680 .iter_mut()
681 .find(|m| m.name == full_name)
682 .ok_or_else(|| Error::NotInstalled {
683 package: full_name.to_string(),
684 })?;
685
686 if eco.modloader_package(full_name).is_some() {
687 return Ok(());
688 }
689
690 if enabled {
691 crate::install::enable_mod(game_profile, target_dir, full_name)?;
692 } else {
693 crate::install::disable_mod(game_profile, target_dir, full_name)?;
694 }
695
696 entry.enabled = enabled;
697
698 modlist::write(target_dir, &mods)
699}
700
701#[cfg(feature = "io")]
704pub fn set_enabled(
705 base: &Path,
706 eco: &Ecosystem,
707 game: &str,
708 profile_name: &str,
709 full_name: &str,
710 enabled: bool,
711) -> Result<()> {
712 set_enabled_in(
713 &layout::profile_dir(base, game, profile_name),
714 eco,
715 game,
716 full_name,
717 enabled,
718 )
719}
720
721#[cfg(feature = "io")]
723pub fn enable_mod_in(
724 target_dir: &Path,
725 eco: &Ecosystem,
726 game: &str,
727 full_name: &str,
728) -> Result<()> {
729 set_enabled_in(target_dir, eco, game, full_name, true)
730}
731
732#[cfg(feature = "io")]
734pub fn disable_mod_in(
735 target_dir: &Path,
736 eco: &Ecosystem,
737 game: &str,
738 full_name: &str,
739) -> Result<()> {
740 set_enabled_in(target_dir, eco, game, full_name, false)
741}
742
743#[cfg(feature = "io")]
745pub fn enable_mod(
746 base: &Path,
747 eco: &Ecosystem,
748 game: &str,
749 profile_name: &str,
750 full_name: &str,
751) -> Result<()> {
752 set_enabled(base, eco, game, profile_name, full_name, true)
753}
754
755#[cfg(feature = "io")]
757pub fn disable_mod(
758 base: &Path,
759 eco: &Ecosystem,
760 game: &str,
761 profile_name: &str,
762 full_name: &str,
763) -> Result<()> {
764 set_enabled(base, eco, game, profile_name, full_name, false)
765}
766
767#[allow(clippy::too_many_arguments)]
784#[cfg(feature = "io")]
785async fn install_one(
786 target_dir: &Path,
787 cache_base: &Path,
788 eco: &Arc<Ecosystem>,
789 index: &PackageIndex,
790 client: &ThunderstoreClient,
791 game: &str,
792 full_name: &str,
793 pins: &[String],
794 force: bool,
795 installed_at_time: u64,
796 operation: &Operation,
797) -> Result<ClosureOutcome> {
798 let resolution = DependencyGraph::new(vec![full_name.to_string()])
799 .pins(pins.iter().cloned())
800 .resolve_report(index);
801
802 if let [unresolved] = resolution.unresolved.as_slice()
805 && unresolved == full_name
806 && let Some((name, version)) = crate::util::split_version(full_name)
807 {
808 return Err(Error::MissingVersion {
809 package: name.to_string(),
810 version: version.to_string(),
811 });
812 }
813
814 if !resolution.unresolved.is_empty() {
815 return Err(Error::UnresolvedDependency {
816 package: full_name.to_string(),
817 unresolved: resolution.unresolved,
818 });
819 }
820
821 let recorded = modlist::read(target_dir)?;
822 let forced = force.then(|| crate::util::full_name_prefix(full_name));
823 let downloads = client.cache_dir().join("downloads");
824 let mut urls = HashMap::new();
825 let mut unchanged = Vec::new();
826
827 for (filename, url) in resolution.urls {
828 let (pkg_full_name, version_str) = parse_package_filename(&filename)
829 .ok_or_else(|| Error::Profile(format!("unparseable package filename {filename:?}")))?;
830
831 let version = SemVer::parse(&version_str);
832 let current = forced != Some(pkg_full_name.as_str())
833 && recorded
834 .iter()
835 .find(|entry| entry.name == pkg_full_name && entry.version_number == version)
836 .is_some_and(|entry| {
837 recorded_files_present(
838 target_dir,
839 cache_base,
840 eco,
841 game,
842 entry,
843 &version_str,
844 &downloads.join(&filename),
845 )
846 });
847
848 if current {
849 unchanged.push(pkg_full_name);
850 } else {
851 urls.insert(filename, url);
852 }
853 }
854
855 client.download_files_for(urls.clone(), operation).await?;
856
857 let mut jobs = Vec::with_capacity(urls.len());
858
859 for filename in urls.keys() {
860 let (pkg_full_name, version_str) = parse_package_filename(filename)
861 .ok_or_else(|| Error::Profile(format!("unparseable package filename {filename:?}")))?;
862
863 let package = index
864 .get_package_by_full_name(&pkg_full_name)
865 .ok_or_else(|| Error::Profile(format!("{pkg_full_name} missing from index")))?;
866
867 let owner = package.owner.clone().unwrap_or_default();
868 let version = package
869 .versions
870 .iter()
871 .find(|v| v.version_number.as_deref() == Some(version_str.as_str()))
872 .or_else(|| package.latest_version())
873 .ok_or_else(|| Error::Profile(format!("{pkg_full_name} has no usable version")))?
874 .clone();
875
876 jobs.push(PackageJob {
877 target_dir: target_dir.to_path_buf(),
878 cache_base: cache_base.to_path_buf(),
879 eco: eco.clone(),
880 game: game.to_string(),
881 full_name: pkg_full_name,
882 owner,
883 version,
884 version_str,
885 archive: downloads.join(filename),
886 installed_at_time,
887 operation: operation.clone(),
888 });
889 }
890
891 let mut closure = ClosureOutcome {
892 unchanged,
893 ..ClosureOutcome::default()
894 };
895
896 for job in dependencies_first(jobs) {
897 let pkg_full_name = job.full_name.clone();
898
899 if operation.is_cancelled() {
900 closure.cancelled.push(pkg_full_name);
901
902 continue;
903 }
904
905 tokio::task::spawn_blocking(move || job.run())
906 .await
907 .map_err(|e| Error::Install(format!("install task for {pkg_full_name} failed: {e}")))??;
908
909 closure.installed.push(pkg_full_name);
910 }
911
912 closure.installed.sort();
913 closure.unchanged.sort();
914 closure.cancelled.sort();
915
916 Ok(closure)
917}
918
919#[cfg(feature = "io")]
922#[derive(Debug, Default)]
923struct ClosureOutcome {
924 installed: Vec<String>,
925 unchanged: Vec<String>,
926 cancelled: Vec<String>,
927}
928
929#[cfg(feature = "io")]
934fn dependencies_first(mut jobs: Vec<PackageJob>) -> Vec<PackageJob> {
935 jobs.sort_by(|a, b| a.full_name.cmp(&b.full_name));
936
937 let position: HashMap<&str, usize> = jobs
938 .iter()
939 .enumerate()
940 .map(|(at, job)| (job.full_name.as_str(), at))
941 .collect();
942 let requires: Vec<Vec<usize>> = jobs
943 .iter()
944 .map(|job| {
945 job
946 .version
947 .dependencies
948 .iter()
949 .filter_map(|dependency| {
950 position
951 .get(crate::util::full_name_prefix(dependency))
952 .copied()
953 })
954 .collect()
955 })
956 .collect();
957 let mut visited = vec![false; jobs.len()];
958 let mut order = Vec::with_capacity(jobs.len());
959
960 for at in 0..jobs.len() {
961 visit_dependencies_first(at, &requires, &mut visited, &mut order);
962 }
963
964 let mut slots: Vec<Option<PackageJob>> = jobs.into_iter().map(Some).collect();
965
966 order
967 .into_iter()
968 .filter_map(|at| slots[at].take())
969 .collect()
970}
971
972#[cfg(feature = "io")]
974fn visit_dependencies_first(
975 at: usize,
976 requires: &[Vec<usize>],
977 visited: &mut [bool],
978 order: &mut Vec<usize>,
979) {
980 if visited[at] {
981 return;
982 }
983
984 visited[at] = true;
985
986 for &dependency in &requires[at] {
987 visit_dependencies_first(dependency, requires, visited, order);
988 }
989
990 order.push(at);
991}
992
993#[cfg(feature = "io")]
997struct PackageJob {
998 target_dir: PathBuf,
999 cache_base: PathBuf,
1000 eco: Arc<Ecosystem>,
1001 game: String,
1002 full_name: String,
1003 owner: String,
1004 version: Version,
1005 version_str: String,
1006 archive: PathBuf,
1007 installed_at_time: u64,
1008 operation: Operation,
1009}
1010
1011#[cfg(feature = "io")]
1012impl PackageJob {
1013 fn run(self) -> Result<()> {
1014 let mut extracting = None;
1015
1016 let extracted = cache::ensure_extracted_reporting(
1017 &self.cache_base,
1018 &self.game,
1019 &self.full_name,
1020 &self.version_str,
1021 &self.archive,
1022 &mut |done, total| self.advance(&mut extracting, Stage::Extracting, done, total),
1023 )?;
1024
1025 drop(extracting);
1026
1027 let mut installing = None;
1028
1029 install_extracted_reporting(
1030 &self.target_dir,
1031 &self.eco,
1032 &self.game,
1033 &self.full_name,
1034 &self.owner,
1035 &self.version,
1036 &extracted,
1037 Some(&self.archive),
1038 self.installed_at_time,
1039 &mut |done, total| self.advance(&mut installing, Stage::Installing, done, total),
1040 )
1041 }
1042
1043 fn advance(&self, slot: &mut Option<StageProgress>, stage: Stage, done: u64, total: u64) {
1045 let progress =
1046 slot.get_or_insert_with(|| self.operation.stage(&self.full_name, stage, Some(total)));
1047
1048 if done > 0 {
1049 progress.advance(done);
1050 }
1051 }
1052}
1053
1054#[cfg(feature = "io")]
1059fn recorded_files_present(
1060 target_dir: &Path,
1061 cache_base: &Path,
1062 eco: &Ecosystem,
1063 game: &str,
1064 entry: &ProfileMod,
1065 version: &str,
1066 archive: &Path,
1067) -> bool {
1068 let extracted = cache::package_cache_dir(cache_base, game, &entry.name, version);
1069
1070 if !extracted.is_dir() {
1071 return false;
1072 }
1073
1074 let Some(game_profile) = eco.game(game).and_then(|g| g.profile()) else {
1075 return false;
1076 };
1077
1078 let archive = archive.exists().then_some(archive);
1079
1080 plan_install(eco, game_profile, &entry.name, &extracted, archive).is_ok_and(|plan| {
1081 crate::install::plan_is_on_disk(&plan, target_dir, &entry.name, entry.enabled)
1082 })
1083}
1084
1085#[allow(clippy::too_many_arguments)]
1101#[cfg(feature = "io")]
1102pub async fn install_batch(
1103 target_dir: &Path,
1104 cache_base: &Path,
1105 eco: &Ecosystem,
1106 index: &PackageIndex,
1107 client: &ThunderstoreClient,
1108 game: &str,
1109 batch: &InstallBatch,
1110 installed_at_time: u64,
1111) -> Result<BatchOutcome> {
1112 install_batch_with(
1113 target_dir,
1114 cache_base,
1115 eco,
1116 index,
1117 client,
1118 game,
1119 batch,
1120 installed_at_time,
1121 &Operation::default(),
1122 )
1123 .await
1124}
1125
1126#[allow(clippy::too_many_arguments)]
1179#[cfg(feature = "io")]
1180pub async fn install_batch_with(
1181 target_dir: &Path,
1182 cache_base: &Path,
1183 eco: &Ecosystem,
1184 index: &PackageIndex,
1185 client: &ThunderstoreClient,
1186 game: &str,
1187 batch: &InstallBatch,
1188 installed_at_time: u64,
1189 operation: &Operation,
1190) -> Result<BatchOutcome> {
1191 let before = modlist::read(target_dir).ok();
1192 let shared_eco = Arc::new(eco.clone());
1193 let mut outcome = BatchOutcome::default();
1194
1195 for full_name in &batch.desired {
1196 if operation.is_cancelled() {
1197 outcome.cancelled.push(full_name.clone());
1198
1199 continue;
1200 }
1201
1202 match install_one(
1203 target_dir,
1204 cache_base,
1205 &shared_eco,
1206 index,
1207 client,
1208 game,
1209 full_name,
1210 &batch.desired,
1211 batch.force,
1212 installed_at_time,
1213 operation,
1214 )
1215 .await
1216 {
1217 Ok(closure) => {
1218 outcome.succeeded.extend(closure.installed);
1219 outcome.unchanged.extend(closure.unchanged);
1220 outcome.cancelled.extend(closure.cancelled);
1221 }
1222 Err(error) => outcome.failed.push((full_name.clone(), error)),
1223 }
1224 }
1225
1226 outcome.succeeded.sort();
1227 outcome.succeeded.dedup();
1228
1229 let restore_failures = reapply_each_disabled(target_dir, eco, game, batch, &outcome.succeeded);
1230
1231 outcome.failed.extend(restore_failures);
1232 outcome.unchanged.sort();
1233 outcome.unchanged.dedup();
1234 outcome
1235 .unchanged
1236 .retain(|name| outcome.succeeded.binary_search(name).is_err());
1237
1238 let to_enable = batch
1241 .enable_requested
1242 .iter()
1243 .filter(|full_name| outcome.unchanged.binary_search(full_name).is_ok());
1244
1245 match modlist::read(target_dir) {
1246 Ok(recorded) => {
1247 for full_name in to_enable {
1248 if modlist::find(&recorded, full_name).is_some_and(|entry| !entry.enabled)
1249 && let Err(error) = set_enabled_in(target_dir, eco, game, full_name, true)
1250 {
1251 outcome.failed.push((full_name.clone(), error));
1252 }
1253 }
1254 }
1255 Err(error) => {
1256 let unconfirmed: Vec<_> = to_enable
1257 .map(|full_name| (full_name.clone(), error.clone()))
1258 .collect();
1259
1260 outcome.failed.extend(unconfirmed);
1261 }
1262 }
1263
1264 let failed: BTreeSet<&String> = outcome.failed.iter().map(|(name, _)| name).collect();
1266
1267 outcome.unchanged.retain(|name| !failed.contains(name));
1268
1269 if let Ok(after) = modlist::read(target_dir) {
1270 (outcome.re_enabled, outcome.kept_disabled) = enabled_state_changes(
1271 before.as_deref(),
1272 &after,
1273 &batch.protect_disabled,
1274 &outcome.succeeded,
1275 );
1276 }
1277
1278 Ok(outcome)
1279}
1280
1281#[cfg(feature = "io")]
1286fn reapply_each_disabled(
1287 target_dir: &Path,
1288 eco: &Ecosystem,
1289 game: &str,
1290 batch: &InstallBatch,
1291 reinstalled: &[String],
1292) -> Vec<(String, Error)> {
1293 let recorded = match modlist::read(target_dir) {
1294 Ok(recorded) => recorded,
1295 Err(error) => {
1296 return batch
1297 .protect_disabled
1298 .iter()
1299 .filter(|full_name| reinstalled.contains(full_name))
1300 .map(|full_name| (full_name.clone(), error.clone()))
1301 .collect();
1302 }
1303 };
1304
1305 batch
1306 .protect_disabled
1307 .iter()
1308 .filter(|full_name| modlist::find(&recorded, full_name).is_some())
1309 .filter_map(|full_name| {
1310 set_enabled_in(target_dir, eco, game, full_name, false)
1311 .err()
1312 .map(|error| (full_name.clone(), error))
1313 })
1314 .collect()
1315}
1316
1317#[cfg(feature = "io")]
1321fn enabled_state_changes(
1322 before: Option<&[ProfileMod]>,
1323 after: &[ProfileMod],
1324 protect_disabled: &[String],
1325 reinstalled: &[String],
1326) -> (Vec<String>, Vec<String>) {
1327 let disabled_before: BTreeSet<&str> = before
1328 .unwrap_or_default()
1329 .iter()
1330 .filter(|entry| !entry.enabled)
1331 .map(|entry| entry.name.as_str())
1332 .collect();
1333
1334 let mut re_enabled: Vec<String> = after
1335 .iter()
1336 .filter(|entry| entry.enabled && disabled_before.contains(entry.name.as_str()))
1337 .map(|entry| entry.name.clone())
1338 .collect();
1339
1340 let mut kept_disabled: Vec<String> = after
1341 .iter()
1342 .filter(|entry| !entry.enabled)
1343 .filter(|entry| protect_disabled.contains(&entry.name) && reinstalled.contains(&entry.name))
1344 .map(|entry| entry.name.clone())
1345 .collect();
1346
1347 re_enabled.sort();
1348 kept_disabled.sort();
1349
1350 (re_enabled, kept_disabled)
1351}
1352
1353#[allow(clippy::too_many_arguments)]
1413#[cfg(feature = "io")]
1414pub async fn install_mod_in(
1415 target_dir: &Path,
1416 cache_base: &Path,
1417 eco: &Ecosystem,
1418 index: &PackageIndex,
1419 client: &ThunderstoreClient,
1420 game: &str,
1421 full_name: &str,
1422 installed_at_time: u64,
1423) -> Result<Vec<String>> {
1424 install_named_in(
1425 target_dir,
1426 cache_base,
1427 eco,
1428 index,
1429 client,
1430 game,
1431 full_name,
1432 false,
1433 installed_at_time,
1434 )
1435 .await
1436}
1437
1438#[allow(clippy::too_many_arguments)]
1443#[cfg(feature = "io")]
1444pub(crate) async fn install_named_in(
1445 target_dir: &Path,
1446 cache_base: &Path,
1447 eco: &Ecosystem,
1448 index: &PackageIndex,
1449 client: &ThunderstoreClient,
1450 game: &str,
1451 full_name: &str,
1452 force: bool,
1453 installed_at_time: u64,
1454) -> Result<Vec<String>> {
1455 let named = [full_name.to_string()];
1456 let mut batch = plan_install_batch(target_dir, &named, &named)?;
1457
1458 batch.force = force;
1459
1460 let outcome = install_batch(
1461 target_dir,
1462 cache_base,
1463 eco,
1464 index,
1465 client,
1466 game,
1467 &batch,
1468 installed_at_time,
1469 )
1470 .await?;
1471
1472 match outcome.failed.into_iter().next() {
1473 Some((_, error)) => Err(error),
1474 None => Ok(outcome.succeeded),
1475 }
1476}
1477
1478#[allow(clippy::too_many_arguments)]
1483#[cfg(feature = "io")]
1484pub async fn install_mod(
1485 base: &Path,
1486 eco: &Ecosystem,
1487 index: &PackageIndex,
1488 client: &ThunderstoreClient,
1489 game: &str,
1490 profile_name: &str,
1491 full_name: &str,
1492 installed_at_time: u64,
1493) -> Result<Vec<String>> {
1494 install_mod_in(
1495 &layout::profile_dir(base, game, profile_name),
1496 base,
1497 eco,
1498 index,
1499 client,
1500 game,
1501 full_name,
1502 installed_at_time,
1503 )
1504 .await
1505}
1506
1507#[derive(Debug, Clone, Default)]
1515#[non_exhaustive]
1516pub struct UninstallBatch {
1517 pub mods: Vec<String>,
1519 pub loaders: Vec<String>,
1521 pub untracked: Vec<PathBuf>,
1528 untracked_confirmed: bool,
1529}
1530
1531impl UninstallBatch {
1532 pub fn confirm_untracked(&mut self) {
1535 self.untracked_confirmed = true;
1536 }
1537
1538 pub fn untracked_confirmed(&self) -> bool {
1540 self.untracked_confirmed
1541 }
1542}
1543
1544#[cfg(feature = "io")]
1551pub fn check_removable_batch(
1552 target_dir: &Path,
1553 eco: &Ecosystem,
1554 names: &[String],
1555) -> Vec<(String, NotRemovable)> {
1556 names
1557 .iter()
1558 .filter_map(|name| match ensure_removable(target_dir, eco, name) {
1559 Ok(()) => None,
1560 Err(refusal) => Some((name.clone(), refusal)),
1561 })
1562 .collect()
1563}
1564
1565#[cfg(feature = "io")]
1575pub fn plan_uninstall_batch(
1576 target_dir: &Path,
1577 eco: &Ecosystem,
1578 game: &str,
1579 names: Option<&[String]>,
1580) -> Result<UninstallBatch> {
1581 let game_profile = eco.require_profile(game)?;
1582
1583 let recorded = modlist::read(target_dir)?;
1584
1585 let mut batch = plan_uninstall_batch_from(
1586 target_dir,
1587 eco,
1588 game,
1589 names,
1590 &recorded,
1591 |name| read_record_state(target_dir, name),
1592 Vec::new(),
1593 )?;
1594
1595 let keep: BTreeSet<String> = recorded.iter().map(|entry| entry.name.clone()).collect();
1596
1597 batch.untracked = crate::install::plan_delisted(game_profile, target_dir, &keep)?;
1598
1599 Ok(batch)
1600}
1601
1602pub fn plan_uninstall_batch_from(
1618 target_dir: &Path,
1619 eco: &Ecosystem,
1620 game: &str,
1621 names: Option<&[String]>,
1622 recorded: &[ProfileMod],
1623 mut record_state: impl FnMut(&str) -> RecordState,
1624 untracked: Vec<PathBuf>,
1625) -> Result<UninstallBatch> {
1626 eco.require_profile(game)?;
1627
1628 let subjects: Vec<String> = match names {
1629 Some(names) => {
1630 for name in names {
1631 if modlist::find(recorded, name).is_none() {
1632 return Err(Error::NotInstalled {
1633 package: name.clone(),
1634 });
1635 }
1636 }
1637
1638 names.to_vec()
1639 }
1640 None => recorded.iter().map(|entry| entry.name.clone()).collect(),
1641 };
1642
1643 for name in &subjects {
1644 if let Err(refusal) = check_removable_from(target_dir, eco, name, record_state(name)) {
1645 return Err(Error::Profile(format!(
1646 "{name} cannot be removed: {refusal}"
1647 )));
1648 }
1649 }
1650
1651 let mut mods: Vec<String> = subjects
1652 .iter()
1653 .filter(|name| eco.modloader_package(name).is_none())
1654 .cloned()
1655 .collect();
1656 let mut loaders: Vec<String> = subjects
1657 .iter()
1658 .filter(|name| eco.modloader_package(name).is_some())
1659 .cloned()
1660 .collect();
1661
1662 mods.sort();
1663 loaders.sort();
1664
1665 Ok(UninstallBatch {
1666 mods,
1667 loaders,
1668 untracked,
1669 untracked_confirmed: false,
1670 })
1671}
1672
1673#[cfg(feature = "io")]
1686pub fn uninstall_batch(
1687 target_dir: &Path,
1688 eco: &Ecosystem,
1689 game: &str,
1690 batch: &UninstallBatch,
1691) -> Result<BatchOutcome> {
1692 uninstall_batch_with(target_dir, eco, game, batch, &Operation::default())
1693}
1694
1695#[cfg(feature = "io")]
1703pub fn uninstall_batch_with(
1704 target_dir: &Path,
1705 eco: &Ecosystem,
1706 game: &str,
1707 batch: &UninstallBatch,
1708 operation: &Operation,
1709) -> Result<BatchOutcome> {
1710 let mut outcome = BatchOutcome::default();
1711
1712 for full_name in batch.mods.iter().chain(batch.loaders.iter()) {
1713 if operation.is_cancelled() {
1714 outcome.cancelled.push(full_name.clone());
1715
1716 continue;
1717 }
1718
1719 let _uninstalling = operation.stage(full_name, Stage::Uninstalling, None);
1720
1721 match uninstall_mod_in(target_dir, eco, game, full_name) {
1722 Ok(()) => outcome.succeeded.push(full_name.clone()),
1723 Err(error) => outcome.failed.push((full_name.clone(), error)),
1724 }
1725 }
1726
1727 if !batch.untracked_confirmed {
1728 outcome.kept_untracked = batch.untracked.clone();
1729
1730 return Ok(outcome);
1731 }
1732
1733 if batch.untracked.is_empty() {
1734 return Ok(outcome);
1735 }
1736
1737 if operation.is_cancelled() {
1738 let unswept = batch
1739 .untracked
1740 .iter()
1741 .map(|relative| relative.display().to_string());
1742
1743 outcome.cancelled.extend(unswept);
1744
1745 return Ok(outcome);
1746 }
1747
1748 let still_untracked = match still_untracked(target_dir, eco, game) {
1749 Ok(still_untracked) => still_untracked,
1750 Err(error) => {
1751 let unswept = batch
1752 .untracked
1753 .iter()
1754 .map(|relative| (relative.display().to_string(), error.clone()));
1755
1756 outcome.failed.extend(unswept);
1757
1758 return Ok(outcome);
1759 }
1760 };
1761
1762 for relative in still_untracked {
1763 if !batch.untracked.contains(&relative) {
1764 continue;
1765 }
1766
1767 let path = target_dir.join(&relative);
1768
1769 if let Err(error) = std::fs::remove_dir_all(&path) {
1770 outcome.failed.push((
1771 relative.display().to_string(),
1772 crate::util::io_context(format!("removing {}", path.display()), error),
1773 ));
1774 }
1775 }
1776
1777 Ok(outcome)
1778}
1779
1780#[cfg(feature = "io")]
1784fn still_untracked(target_dir: &Path, eco: &Ecosystem, game: &str) -> Result<Vec<PathBuf>> {
1785 let keep: BTreeSet<String> = modlist::read(target_dir)?
1786 .into_iter()
1787 .map(|entry| entry.name)
1788 .collect();
1789
1790 crate::install::plan_delisted(eco.require_profile(game)?, target_dir, &keep)
1791}
1792
1793#[derive(Debug, Clone, Default)]
1800#[non_exhaustive]
1801pub struct ToggleBatch {
1802 pub changing: Vec<String>,
1804 pub already: Vec<String>,
1806 pub loaders: Vec<String>,
1808 pub enabled: bool,
1813}
1814
1815#[cfg(feature = "io")]
1825pub fn plan_set_enabled_batch(
1826 target_dir: &Path,
1827 eco: &Ecosystem,
1828 names: Option<&[String]>,
1829 enabled: bool,
1830) -> Result<ToggleBatch> {
1831 let recorded = modlist::read(target_dir)?;
1832
1833 plan_set_enabled_batch_from(&recorded, eco, names, enabled)
1834}
1835
1836pub fn plan_set_enabled_batch_from(
1846 recorded: &[ProfileMod],
1847 eco: &Ecosystem,
1848 names: Option<&[String]>,
1849 enabled: bool,
1850) -> Result<ToggleBatch> {
1851 if let Some(names) = names {
1852 for name in names {
1853 if modlist::find(recorded, name).is_none() {
1854 return Err(Error::NotInstalled {
1855 package: name.clone(),
1856 });
1857 }
1858 }
1859 }
1860
1861 let mut batch = ToggleBatch {
1862 enabled,
1863 ..ToggleBatch::default()
1864 };
1865
1866 for entry in recorded {
1867 if let Some(names) = names
1868 && !names.iter().any(|name| name == &entry.name)
1869 {
1870 continue;
1871 }
1872
1873 if eco.modloader_package(&entry.name).is_some() {
1874 batch.loaders.push(entry.name.clone());
1875 } else if entry.enabled == enabled {
1876 batch.already.push(entry.name.clone());
1877 } else {
1878 batch.changing.push(entry.name.clone());
1879 }
1880 }
1881
1882 batch.changing.sort();
1883 batch.already.sort();
1884 batch.loaders.sort();
1885
1886 Ok(batch)
1887}
1888
1889#[cfg(feature = "io")]
1898pub fn set_enabled_batch(
1899 target_dir: &Path,
1900 eco: &Ecosystem,
1901 game: &str,
1902 batch: &ToggleBatch,
1903) -> Result<BatchOutcome> {
1904 set_enabled_batch_with(target_dir, eco, game, batch, &Operation::default())
1905}
1906
1907#[cfg(feature = "io")]
1914pub fn set_enabled_batch_with(
1915 target_dir: &Path,
1916 eco: &Ecosystem,
1917 game: &str,
1918 batch: &ToggleBatch,
1919 operation: &Operation,
1920) -> Result<BatchOutcome> {
1921 let stage = if batch.enabled {
1922 Stage::Enabling
1923 } else {
1924 Stage::Disabling
1925 };
1926 let mut outcome = BatchOutcome::default();
1927
1928 for full_name in &batch.changing {
1929 if operation.is_cancelled() {
1930 outcome.cancelled.push(full_name.clone());
1931
1932 continue;
1933 }
1934
1935 let _toggling = operation.stage(full_name, stage, None);
1936
1937 match set_enabled_in(target_dir, eco, game, full_name, batch.enabled) {
1938 Ok(()) => outcome.succeeded.push(full_name.clone()),
1939 Err(error) => outcome.failed.push((full_name.clone(), error)),
1940 }
1941 }
1942
1943 Ok(outcome)
1944}
1945
1946#[cfg(all(test, feature = "io"))]
1947mod tests {
1948 use super::*;
1949 use crate::ecosystem::Ecosystem;
1950 use crate::install::state_file_path;
1951 use crate::models::Version;
1952 use std::io::{Cursor, Write};
1953 use tempfile::tempdir;
1954 use time::OffsetDateTime;
1955 use zip::write::{FileOptions, ZipWriter};
1956
1957 fn write_file(path: &std::path::Path, bytes: &[u8]) {
1958 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1959 std::fs::File::create(path)
1960 .unwrap()
1961 .write_all(bytes)
1962 .unwrap();
1963 }
1964
1965 fn version(full_name: &str) -> Version {
1966 Version {
1967 name: Some("Mod".to_string()),
1968 full_name: Some(full_name.to_string()),
1969 description: Some("desc".to_string()),
1970 icon: Some("icon.png".to_string()),
1971 version_number: Some("1.2.3".to_string()),
1972 dependencies: vec!["Other-Dep-1.0.0".to_string()],
1973 download_url: Some("https://example.com/dl".to_string()),
1974 downloads: Some(1),
1975 date_created: OffsetDateTime::UNIX_EPOCH,
1976 website_url: Some("https://example.com".to_string()),
1977 is_active: Some(true),
1978 uuid4: Some("u".to_string()),
1979 file_size: Some(1),
1980 }
1981 }
1982
1983 #[test]
1984 fn mod_entry_maps_version_with_r2modman_defaults() {
1985 let entry = mod_entry_from_version("Author-Mod", "Author", &version("Author-Mod"), 123);
1986
1987 assert_eq!(entry.name, "Author-Mod");
1988 assert_eq!(entry.author_name, "Author");
1989 assert_eq!(entry.network_mode, "both");
1990 assert_eq!(entry.package_type, "other");
1991 assert_eq!(entry.install_mode, "managed");
1992 assert_eq!(entry.game_version, "0");
1993 assert_eq!(entry.manifest_version, 1);
1994 assert_eq!(
1995 entry.version_number,
1996 crate::profile::modlist::SemVer {
1997 major: 1,
1998 minor: 2,
1999 patch: 3
2000 }
2001 );
2002 assert_eq!(entry.dependencies, vec!["Other-Dep-1.0.0".to_string()]);
2003 assert_eq!(entry.installed_at_time, 123);
2004 assert!(entry.enabled);
2005 }
2006
2007 #[test]
2008 fn install_extracted_places_files_and_records_mods_yml() {
2009 let eco = Ecosystem::bundled();
2010
2011 let dir = tempdir().unwrap();
2012 let base = dir.path();
2013
2014 let extracted = tempdir().unwrap();
2015 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2016 write_file(&extracted.path().join("manifest.json"), b"{}");
2017
2018 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2019
2020 install_extracted(
2021 base,
2022 &eco,
2023 "valheim",
2024 "Main",
2025 "Author-Mod",
2026 "Author",
2027 &version("Author-Mod"),
2028 extracted.path(),
2029 None,
2030 123,
2031 )
2032 .unwrap();
2033
2034 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2035
2036 assert!(
2037 profile_dir
2038 .join("BepInEx/plugins/Author-Mod/Mod.dll")
2039 .exists()
2040 );
2041
2042 let mods = crate::profile::modlist::read(&profile_dir).unwrap();
2043
2044 assert_eq!(mods.len(), 1);
2045 assert_eq!(mods[0].name, "Author-Mod");
2046 assert!(mods[0].enabled);
2047 }
2048
2049 #[test]
2050 fn uninstall_removes_files_and_mods_yml_entry() {
2051 let eco = Ecosystem::bundled();
2052
2053 let dir = tempdir().unwrap();
2054 let base = dir.path();
2055
2056 let extracted = tempdir().unwrap();
2057 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2058
2059 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2060
2061 install_extracted(
2062 base,
2063 &eco,
2064 "valheim",
2065 "Main",
2066 "Author-Mod",
2067 "Author",
2068 &version("Author-Mod"),
2069 extracted.path(),
2070 None,
2071 1,
2072 )
2073 .unwrap();
2074
2075 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2076
2077 assert!(
2078 profile_dir
2079 .join("BepInEx/plugins/Author-Mod/Mod.dll")
2080 .exists()
2081 );
2082
2083 uninstall_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap();
2084
2085 assert!(!profile_dir.join("BepInEx/plugins/Author-Mod").exists());
2086 assert_eq!(
2087 crate::profile::modlist::read(&profile_dir).unwrap().len(),
2088 0
2089 );
2090 }
2091
2092 #[test]
2093 fn uninstall_refuses_a_mod_whose_install_record_cannot_be_read() {
2094 let eco = Ecosystem::bundled();
2095
2096 let dir = tempdir().unwrap();
2097 let base = dir.path();
2098
2099 let extracted = tempdir().unwrap();
2100 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2101
2102 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2103 install_extracted(
2104 base,
2105 &eco,
2106 "valheim",
2107 "Main",
2108 "Author-Mod",
2109 "Author",
2110 &version("Author-Mod"),
2111 extracted.path(),
2112 None,
2113 1,
2114 )
2115 .unwrap();
2116
2117 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2118
2119 write_file(&state_file_path(&profile_dir, "Author-Mod"), b"not: [valid");
2123
2124 let error = uninstall_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap_err();
2125
2126 assert!(
2131 profile_dir
2132 .join("BepInEx/plugins/Author-Mod/Mod.dll")
2133 .exists(),
2134 "the mod's files must survive a refusal; got error: {error}"
2135 );
2136 assert_eq!(
2137 crate::profile::modlist::read(&profile_dir).unwrap().len(),
2138 1
2139 );
2140 }
2141
2142 #[test]
2143 fn disable_then_enable_updates_disk_and_mods_yml() {
2144 let eco = Ecosystem::bundled();
2145
2146 let dir = tempdir().unwrap();
2147 let base = dir.path();
2148
2149 let extracted = tempdir().unwrap();
2150 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2151
2152 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2153 install_extracted(
2154 base,
2155 &eco,
2156 "valheim",
2157 "Main",
2158 "Author-Mod",
2159 "Author",
2160 &version("Author-Mod"),
2161 extracted.path(),
2162 None,
2163 1,
2164 )
2165 .unwrap();
2166
2167 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2168
2169 disable_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap();
2170
2171 assert!(
2172 profile_dir
2173 .join("BepInEx/plugins/Author-Mod/Mod.dll.old")
2174 .exists()
2175 );
2176 assert!(!crate::profile::modlist::read(&profile_dir).unwrap()[0].enabled);
2177
2178 enable_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap();
2179
2180 assert!(
2181 profile_dir
2182 .join("BepInEx/plugins/Author-Mod/Mod.dll")
2183 .exists()
2184 );
2185 assert!(crate::profile::modlist::read(&profile_dir).unwrap()[0].enabled);
2186 }
2187
2188 #[test]
2189 fn disable_leaves_files_alone_when_the_install_record_cannot_be_read() {
2190 let eco = Ecosystem::bundled();
2191
2192 let dir = tempdir().unwrap();
2193 let base = dir.path();
2194
2195 let extracted = tempdir().unwrap();
2196 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2197
2198 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2199 install_extracted(
2200 base,
2201 &eco,
2202 "valheim",
2203 "Main",
2204 "Author-Mod",
2205 "Author",
2206 &version("Author-Mod"),
2207 extracted.path(),
2208 None,
2209 1,
2210 )
2211 .unwrap();
2212
2213 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2214
2215 write_file(&state_file_path(&profile_dir, "Author-Mod"), b"not: [valid");
2216
2217 let error = disable_mod(base, &eco, "valheim", "Main", "Author-Mod").unwrap_err();
2218
2219 assert!(
2224 profile_dir
2225 .join("BepInEx/plugins/Author-Mod/Mod.dll")
2226 .exists(),
2227 "the mod's files must be left as they were; got error: {error}"
2228 );
2229 assert!(
2230 !profile_dir
2231 .join("BepInEx/plugins/Author-Mod/Mod.dll.old")
2232 .exists()
2233 );
2234 assert!(crate::profile::modlist::read(&profile_dir).unwrap()[0].enabled);
2235 }
2236
2237 #[test]
2238 fn disable_mod_is_noop_for_modloader_pack() {
2239 let eco = Ecosystem::bundled();
2240
2241 let dir = tempdir().unwrap();
2242 let base = dir.path();
2243 let full_name = "denikson-BepInExPack_Valheim";
2244
2245 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2246
2247 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2248 let loader_file = profile_dir.join("winhttp.dll");
2249
2250 write_file(&loader_file, b"dll");
2251
2252 let mut mods = Vec::new();
2253
2254 modlist::upsert(
2255 &mut mods,
2256 mod_entry_from_version(full_name, "denikson", &version(full_name), 1),
2257 );
2258 modlist::write(&profile_dir, &mods).unwrap();
2259
2260 let tracker = crate::install::ModFileTracker {
2261 mod_name: full_name.to_string(),
2262 files: vec![("unused-cache-source".to_string(), "winhttp.dll".to_string())],
2263 };
2264
2265 write_state_file(&profile_dir, &tracker).unwrap();
2266
2267 disable_mod(base, &eco, "valheim", "Main", full_name).unwrap();
2268
2269 assert!(loader_file.exists());
2270 assert!(crate::profile::modlist::read(&profile_dir).unwrap()[0].enabled);
2271 }
2272
2273 #[test]
2274 fn install_mod_fails_on_unresolved_dependency() {
2275 let eco = Ecosystem::bundled();
2276
2277 let package = crate::models::Package {
2278 name: Some("Mod".to_string()),
2279 full_name: Some("Author-Mod".to_string()),
2280 owner: Some("Author".to_string()),
2281 package_url: Some("https://example.com/Author-Mod".to_string()),
2282 date_created: OffsetDateTime::UNIX_EPOCH,
2283 date_updated: OffsetDateTime::UNIX_EPOCH,
2284 uuid4: Some("u".to_string()),
2285 rating_score: Some(0),
2286 is_pinned: Some(false),
2287 is_deprecated: Some(false),
2288 has_nsfw_content: Some(false),
2289 categories: vec![],
2290 versions: vec![Version {
2291 dependencies: vec!["Missing-Dep-1.0.0".to_string()],
2292 ..version("Author-Mod")
2293 }],
2294 };
2295
2296 let index: PackageIndex = vec![package].into();
2297
2298 let dir = tempdir().unwrap();
2299 let base = dir.path();
2300 let cache_dir = tempdir().unwrap();
2301
2302 let client = ThunderstoreClient::builder()
2303 .package_index_url("http://localhost/pkg/")
2304 .cache_dir(cache_dir.path())
2305 .build()
2306 .unwrap();
2307
2308 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2309
2310 let rt = tokio::runtime::Runtime::new().unwrap();
2311 let result = rt.block_on(install_mod(
2312 base,
2313 &eco,
2314 &index,
2315 &client,
2316 "valheim",
2317 "Main",
2318 "Author-Mod",
2319 1,
2320 ));
2321
2322 let err = result.unwrap_err();
2323
2324 assert!(
2325 matches!(
2326 &err,
2327 Error::UnresolvedDependency { package, unresolved }
2328 if package == "Author-Mod" && unresolved == &["Missing-Dep".to_string()]
2329 ),
2330 "unexpected error: {err}"
2331 );
2332 assert_eq!(
2333 err.to_string(),
2334 "Profile error: cannot install Author-Mod: could not resolve Missing-Dep"
2335 );
2336 }
2337
2338 #[test]
2339 fn server_mode_lifecycle_against_bare_target_dir() {
2340 let eco = Ecosystem::bundled();
2341
2342 let dir = tempdir().unwrap();
2343 let target_dir = dir.path();
2344
2345 let extracted = tempdir().unwrap();
2346 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2347
2348 install_extracted_in(
2349 target_dir,
2350 &eco,
2351 "valheim",
2352 "Author-Mod",
2353 "Author",
2354 &version("Author-Mod"),
2355 extracted.path(),
2356 None,
2357 123,
2358 )
2359 .unwrap();
2360
2361 assert!(
2362 target_dir
2363 .join("BepInEx/plugins/Author-Mod/Mod.dll")
2364 .exists()
2365 );
2366 assert!(target_dir.join("mods.yml").exists());
2367
2368 let mods = modlist::read(target_dir).unwrap();
2369
2370 assert_eq!(mods.len(), 1);
2371 assert_eq!(mods[0].name, "Author-Mod");
2372 assert!(mods[0].enabled);
2373
2374 let state_source = extracted
2381 .path()
2382 .join("cache/Author-Mod/1.0.0/state-dest.txt");
2383
2384 write_file(&state_source, b"state-data");
2385 write_file(&target_dir.join("state-dest.txt"), b"state-data");
2386
2387 let tracker = crate::install::ModFileTracker {
2388 mod_name: "Author-Mod".to_string(),
2389 files: vec![(
2390 state_source.to_string_lossy().to_string(),
2391 "state-dest.txt".to_string(),
2392 )],
2393 };
2394
2395 write_state_file(target_dir, &tracker).unwrap();
2396
2397 assert!(state_file_path(target_dir, "Author-Mod").exists());
2398
2399 disable_mod_in(target_dir, &eco, "valheim", "Author-Mod").unwrap();
2400
2401 assert!(
2402 target_dir
2403 .join("BepInEx/plugins/Author-Mod/Mod.dll.old")
2404 .exists()
2405 );
2406 assert!(!target_dir.join("state-dest.txt").exists());
2407 assert!(!modlist::read(target_dir).unwrap()[0].enabled);
2408
2409 enable_mod_in(target_dir, &eco, "valheim", "Author-Mod").unwrap();
2410
2411 assert!(
2412 target_dir
2413 .join("BepInEx/plugins/Author-Mod/Mod.dll")
2414 .exists()
2415 );
2416 assert!(target_dir.join("state-dest.txt").exists());
2417 assert!(modlist::read(target_dir).unwrap()[0].enabled);
2418
2419 uninstall_mod_in(target_dir, &eco, "valheim", "Author-Mod").unwrap();
2420
2421 assert!(!target_dir.join("BepInEx/plugins/Author-Mod").exists());
2422 assert!(!target_dir.join("state-dest.txt").exists());
2427 assert!(!state_file_path(target_dir, "Author-Mod").exists());
2428 assert_eq!(modlist::read(target_dir).unwrap().len(), 0);
2429 }
2430
2431 fn build_mod_zip() -> Vec<u8> {
2432 let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
2433 let opts: FileOptions<'_, ()> =
2434 FileOptions::default().compression_method(zip::CompressionMethod::Stored);
2435
2436 for (name, body) in [
2437 ("manifest.json", &b"{\"version_number\":\"1.0.0\"}"[..]),
2438 ("plugins/CoolMod.dll", &b"dll-bytes"[..]),
2439 ] {
2440 zip.start_file(name, opts).unwrap();
2441 zip.write_all(body).unwrap();
2442 }
2443
2444 zip.finish().unwrap().into_inner()
2445 }
2446
2447 fn index_json(server_url: &str) -> String {
2448 format!(
2449 r#"[{{"name":"CoolMod","full_name":"Author-CoolMod","owner":"Author","package_url":"https://example.com/CoolMod","date_created":"2024-01-01T12:00:00Z","date_updated":"2024-01-02T12:00:00Z","uuid4":"pkg","rating_score":1,"is_pinned":false,"is_deprecated":false,"has_nsfw_content":false,"categories":[],"versions":[{{"name":"CoolMod","full_name":"Author-CoolMod","description":"A cool mod","icon":"icon.png","version_number":"1.0.0","dependencies":[],"download_url":"{server_url}/dl/mod.zip","downloads":1,"date_created":"2024-01-01T12:00:00Z","website_url":"","is_active":true,"uuid4":"ver","file_size":1024}}]}}]"#
2450 )
2451 }
2452
2453 #[test]
2454 fn install_mod_in_extracts_into_cache_base_not_target_dir() {
2455 let mut server = mockito::Server::new();
2456 let zip_bytes = build_mod_zip();
2457
2458 let dl = server
2459 .mock("GET", "/dl/mod.zip")
2460 .with_status(200)
2461 .with_header("Content-Type", "application/zip")
2462 .with_body(zip_bytes)
2463 .create();
2464 let idx = server
2465 .mock("GET", "/pkg/")
2466 .with_status(200)
2467 .with_header("Content-Type", "application/json")
2468 .with_header("Last-Modified", "Wed, 21 Feb 2024 15:30:45 GMT")
2469 .with_body(index_json(&server.url()))
2470 .create();
2471
2472 let http_cache = tempdir().unwrap();
2473 let cache_base = tempdir().unwrap();
2474 let target = tempdir().unwrap();
2475
2476 let client = ThunderstoreClient::builder()
2477 .package_index_url(format!("{}/pkg/", server.url()))
2478 .cache_dir(http_cache.path())
2479 .build()
2480 .unwrap();
2481
2482 let rt = tokio::runtime::Runtime::new().unwrap();
2483 let eco = Ecosystem::bundled();
2484 let index = rt.block_on(client.get_manifest()).unwrap();
2485
2486 let installed = rt
2487 .block_on(install_mod_in(
2488 target.path(),
2489 cache_base.path(),
2490 &eco,
2491 &index,
2492 &client,
2493 "valheim",
2494 "Author-CoolMod",
2495 123,
2496 ))
2497 .unwrap();
2498
2499 assert_eq!(installed, vec!["Author-CoolMod".to_string()]);
2500
2501 assert!(
2502 target
2503 .path()
2504 .join("BepInEx/plugins/Author-CoolMod/CoolMod.dll")
2505 .exists()
2506 );
2507
2508 let cached = cache::package_cache_dir(cache_base.path(), "valheim", "Author-CoolMod", "1.0.0");
2509
2510 assert!(cached.join("plugins/CoolMod.dll").exists());
2511 assert!(!target.path().join("cache").exists());
2512
2513 dl.assert();
2514 idx.assert();
2515 }
2516
2517 fn profile_mod(name: &str) -> ProfileMod {
2521 ProfileMod {
2522 manifest_version: 1,
2523 name: name.to_string(),
2524 author_name: String::new(),
2525 website_url: String::new(),
2526 display_name: name.to_string(),
2527 description: String::new(),
2528 game_version: "0".to_string(),
2529 network_mode: "both".to_string(),
2530 package_type: "other".to_string(),
2531 install_mode: "managed".to_string(),
2532 installed_at_time: 1,
2533 loaders: Vec::new(),
2534 dependencies: Vec::new(),
2535 incompatibilities: Vec::new(),
2536 optional_dependencies: Vec::new(),
2537 version_number: SemVer::parse("1.0.0"),
2538 enabled: true,
2539 icon: String::new(),
2540 online_source: false,
2541 trusted_package: false,
2542 }
2543 }
2544
2545 #[test]
2546 fn uninstalling_a_loader_pack_without_a_state_file_is_refused() {
2547 let dir = tempdir().unwrap();
2548 let target_dir = dir.path();
2549 let eco = crate::ecosystem::Ecosystem::bundled();
2550
2551 modlist::write(target_dir, &[profile_mod("denikson-BepInExPack_Valheim")]).unwrap();
2555
2556 let result = uninstall_mod_in(target_dir, &eco, "valheim", "denikson-BepInExPack_Valheim");
2557
2558 assert!(result.is_err());
2559
2560 let message = result.unwrap_err().to_string();
2561
2562 assert!(
2563 message.contains("denikson-BepInExPack_Valheim"),
2564 "the error must name the loader; got: {message}"
2565 );
2566 assert_eq!(modlist::read(target_dir).unwrap().len(), 1);
2569 }
2570
2571 #[test]
2572 fn uninstalling_a_regular_mod_without_a_state_file_still_works() {
2573 let dir = tempdir().unwrap();
2574 let target_dir = dir.path();
2575 let eco = crate::ecosystem::Ecosystem::bundled();
2576
2577 modlist::write(target_dir, &[profile_mod("Owner-Regular")]).unwrap();
2580
2581 uninstall_mod_in(target_dir, &eco, "valheim", "Owner-Regular").unwrap();
2582
2583 assert!(modlist::read(target_dir).unwrap().is_empty());
2584 }
2585
2586 #[test]
2587 fn check_removable_batch_reports_every_unremovable_name_with_its_reason() {
2588 let dir = tempdir().unwrap();
2589 let target_dir = dir.path();
2590 let eco = crate::ecosystem::Ecosystem::bundled();
2591
2592 modlist::write(
2593 target_dir,
2594 &[
2595 profile_mod("denikson-BepInExPack_Valheim"),
2596 profile_mod("Owner-Regular"),
2597 ],
2598 )
2599 .unwrap();
2600
2601 let state_path = crate::install::state_file_path(target_dir, "Owner-Regular");
2608
2609 std::fs::create_dir_all(state_path.parent().unwrap()).unwrap();
2610 std::fs::write(&state_path, "not: [valid").unwrap();
2611
2612 let names = vec![
2613 "denikson-BepInExPack_Valheim".to_string(),
2614 "Owner-Regular".to_string(),
2615 ];
2616
2617 let blocked = check_removable_batch(target_dir, &eco, &names);
2618
2619 assert_eq!(
2620 blocked.len(),
2621 2,
2622 "both un-removable names must be reported, not just the first; got {blocked:?}"
2623 );
2624
2625 let loader_refusal = blocked
2626 .iter()
2627 .find(|(name, _)| name == "denikson-BepInExPack_Valheim")
2628 .map(|(_, refusal)| refusal)
2629 .unwrap();
2630 let loader_path = state_file_path(target_dir, "denikson-BepInExPack_Valheim");
2631
2632 assert!(
2635 matches!(loader_refusal, NotRemovable::RecordAbsent { path, .. } if path == &loader_path),
2636 "expected an absent record carrying its expected path; got: {loader_refusal:?}"
2637 );
2638
2639 let regular_refusal = blocked
2640 .iter()
2641 .find(|(name, _)| name == "Owner-Regular")
2642 .map(|(_, refusal)| refusal)
2643 .unwrap();
2644
2645 assert!(
2646 matches!(regular_refusal, NotRemovable::RecordUnreadable { path, .. } if path == &state_path),
2647 "expected an unreadable record carrying the path it could not read; got: {regular_refusal:?}"
2648 );
2649 }
2650
2651 #[test]
2652 fn a_removability_refusal_keeps_todays_wording_when_it_becomes_an_error() {
2653 let dir = tempdir().unwrap();
2654 let target_dir = dir.path();
2655 let eco = crate::ecosystem::Ecosystem::bundled();
2656
2657 modlist::write(target_dir, &[profile_mod("denikson-BepInExPack_Valheim")]).unwrap();
2658
2659 let refusal = ensure_removable(target_dir, &eco, "denikson-BepInExPack_Valheim").unwrap_err();
2660 let path = state_file_path(target_dir, "denikson-BepInExPack_Valheim");
2661
2662 assert_eq!(
2665 Error::from(refusal).to_string(),
2666 format!(
2667 "Profile error: denikson-BepInExPack_Valheim is a mod loader with no \
2668 install record at {}, so its files cannot be removed exactly. Reinstall \
2669 it, then uninstall it again, or remove its files by hand.",
2670 path.display()
2671 )
2672 );
2673 }
2674
2675 #[test]
2676 fn a_reinstall_the_caller_did_not_name_keeps_its_disabled_state() {
2677 let eco = Ecosystem::bundled();
2678 let dir = tempdir().unwrap();
2679 let base = dir.path();
2680
2681 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2682
2683 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2684 let extracted = tempdir().unwrap();
2685
2686 write_file(&extracted.path().join("plugins/Base.dll"), b"dll");
2687
2688 install_extracted(
2689 base,
2690 &eco,
2691 "valheim",
2692 "Main",
2693 "Author-Base",
2694 "Author",
2695 &version("Author-Base"),
2696 extracted.path(),
2697 None,
2698 1,
2699 )
2700 .unwrap();
2701
2702 disable_mod(base, &eco, "valheim", "Main", "Author-Base").unwrap();
2703
2704 assert!(!modlist::read(&profile_dir).unwrap()[0].enabled);
2705 assert!(
2706 profile_dir
2707 .join("BepInEx/plugins/Author-Base/Base.dll.old")
2708 .exists(),
2709 "the disable must have suffixed the file, or this test proves nothing"
2710 );
2711
2712 let batch = plan_install_batch(&profile_dir, &["Author-Base".to_string()], &[]).unwrap();
2715
2716 assert_eq!(batch.protect_disabled, vec!["Author-Base".to_string()]);
2717
2718 install_extracted(
2719 base,
2720 &eco,
2721 "valheim",
2722 "Main",
2723 "Author-Base",
2724 "Author",
2725 &version("Author-Base"),
2726 extracted.path(),
2727 None,
2728 2,
2729 )
2730 .unwrap();
2731
2732 reapply_batch_disabled(&profile_dir, &eco, "valheim", &batch).unwrap();
2733
2734 let mods = modlist::read(&profile_dir).unwrap();
2735
2736 assert!(
2737 !mods[0].enabled,
2738 "a disabled dependency must not be re-enabled by an incidental reinstall"
2739 );
2740 assert!(
2741 profile_dir
2742 .join("BepInEx/plugins/Author-Base/Base.dll.old")
2743 .exists(),
2744 "the file must be left suffixed, not rewritten un-suffixed and orphaned"
2745 );
2746 }
2747
2748 #[test]
2749 fn planning_an_uninstall_batch_partitions_loaders_and_lists_untracked() {
2750 let eco = Ecosystem::bundled();
2751 let dir = tempdir().unwrap();
2752 let base = dir.path();
2753
2754 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2755
2756 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2757 let extracted = tempdir().unwrap();
2758
2759 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2760 install_extracted(
2761 base,
2762 &eco,
2763 "valheim",
2764 "Main",
2765 "Author-Mod",
2766 "Author",
2767 &version("Author-Mod"),
2768 extracted.path(),
2769 None,
2770 1,
2771 )
2772 .unwrap();
2773
2774 write_file(
2776 &profile_dir.join("BepInEx/plugins/Other-ByHand/x.dll"),
2777 b"dll",
2778 );
2779 write_file(&profile_dir.join("BepInEx/plugins/MMHOOK/h.dll"), b"dll");
2781
2782 let batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
2783
2784 assert_eq!(batch.mods, vec!["Author-Mod".to_string()]);
2785 assert!(batch.loaders.is_empty());
2786 assert_eq!(
2787 batch.untracked,
2788 vec![std::path::PathBuf::from("BepInEx/plugins/Other-ByHand")]
2789 );
2790
2791 let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
2792
2793 assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
2794 assert_eq!(outcome.succeeded, vec!["Author-Mod".to_string()]);
2795 assert!(modlist::read(&profile_dir).unwrap().is_empty());
2796 assert!(profile_dir.join("BepInEx/plugins/MMHOOK/h.dll").exists());
2797 }
2798
2799 #[test]
2800 fn an_uninstall_batch_keeps_untracked_folders_unless_confirmed() {
2801 let eco = Ecosystem::bundled();
2802 let dir = tempdir().unwrap();
2803 let base = dir.path();
2804
2805 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2806
2807 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2808 let plugins = profile_dir.join("BepInEx/plugins");
2809
2810 install_plugin(base, &eco, "Author-Gone");
2811 write_file(&plugins.join("Other-ByHand/x.dll"), b"dll");
2812
2813 let batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
2814
2815 assert_eq!(
2816 batch.untracked,
2817 vec![PathBuf::from("BepInEx/plugins/Other-ByHand")]
2818 );
2819
2820 let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
2821
2822 assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
2823 assert_eq!(outcome.succeeded, vec!["Author-Gone".to_string()]);
2824 assert!(!plugins.join("Author-Gone").exists());
2825 assert!(plugins.join("Other-ByHand/x.dll").exists());
2826 assert_eq!(
2827 outcome.kept_untracked,
2828 vec![PathBuf::from("BepInEx/plugins/Other-ByHand")]
2829 );
2830 }
2831
2832 fn install_plugin(base: &Path, eco: &Ecosystem, name: &str) {
2834 let extracted = tempdir().unwrap();
2835
2836 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2837 install_extracted(
2838 base,
2839 eco,
2840 "valheim",
2841 "Main",
2842 name,
2843 "Author",
2844 &version(name),
2845 extracted.path(),
2846 None,
2847 1,
2848 )
2849 .unwrap();
2850 }
2851
2852 #[test]
2853 fn an_uninstall_batch_removes_only_the_untracked_folders_it_names() {
2854 let eco = Ecosystem::bundled();
2855 let dir = tempdir().unwrap();
2856 let base = dir.path();
2857
2858 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2859
2860 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2861 let plugins = profile_dir.join("BepInEx/plugins");
2862
2863 install_plugin(base, &eco, "Author-Gone");
2864 install_plugin(base, &eco, "Author-Kept");
2865 write_file(&plugins.join("Other-Confirmed/x.dll"), b"dll");
2866 write_file(&plugins.join("Other-Declined/x.dll"), b"dll");
2867
2868 let mut batch = plan_uninstall_batch(
2869 &profile_dir,
2870 &eco,
2871 "valheim",
2872 Some(&["Author-Gone".to_string()]),
2873 )
2874 .unwrap();
2875
2876 assert_eq!(
2877 batch.untracked,
2878 vec![
2879 PathBuf::from("BepInEx/plugins/Other-Confirmed"),
2880 PathBuf::from("BepInEx/plugins/Other-Declined"),
2881 ]
2882 );
2883
2884 batch
2885 .untracked
2886 .retain(|path| path.ends_with("Other-Confirmed"));
2887
2888 batch.confirm_untracked();
2889
2890 write_file(&plugins.join("Other-Late/x.dll"), b"dll");
2892
2893 let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
2894
2895 assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
2896 assert!(outcome.kept_untracked.is_empty());
2897 assert!(!plugins.join("Author-Gone").exists());
2898 assert!(!plugins.join("Other-Confirmed").exists());
2899 assert!(plugins.join("Author-Kept/Mod.dll").exists());
2900 assert!(plugins.join("Other-Declined/x.dll").exists());
2901 assert!(plugins.join("Other-Late/x.dll").exists());
2902 }
2903
2904 #[test]
2905 fn a_sweep_that_cannot_reread_the_record_keeps_the_outcome_and_the_folders() {
2906 let eco = Ecosystem::bundled();
2907 let dir = tempdir().unwrap();
2908 let base = dir.path();
2909
2910 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2911
2912 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2913 let untracked = profile_dir.join("BepInEx/plugins/Other-Confirmed");
2914
2915 write_file(&untracked.join("x.dll"), b"dll");
2916
2917 let mut batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
2918
2919 batch.confirm_untracked();
2920 write_file(&profile_dir.join("mods.yml"), b"- [unclosed");
2921
2922 let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
2923 let failed: Vec<PathBuf> = outcome
2924 .failed
2925 .iter()
2926 .map(|(name, _)| PathBuf::from(name))
2927 .collect();
2928
2929 assert_eq!(failed, [PathBuf::from("BepInEx/plugins/Other-Confirmed")]);
2930 assert!(untracked.join("x.dll").exists());
2931 }
2932
2933 #[test]
2934 fn uninstalling_one_mod_leaves_folders_the_record_does_not_name() {
2935 let eco = Ecosystem::bundled();
2936 let dir = tempdir().unwrap();
2937 let base = dir.path();
2938
2939 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2940
2941 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2942 let plugins = profile_dir.join("BepInEx/plugins");
2943
2944 install_plugin(base, &eco, "Author-Gone");
2945 write_file(&plugins.join("Other-ByHand/x.dll"), b"dll");
2946
2947 uninstall_mod(base, &eco, "valheim", "Main", "Author-Gone").unwrap();
2948
2949 assert!(!plugins.join("Author-Gone").exists());
2950 assert!(plugins.join("Other-ByHand/x.dll").exists());
2951 assert!(modlist::read(&profile_dir).unwrap().is_empty());
2952 }
2953
2954 #[test]
2955 fn uninstalling_a_name_the_record_lacks_is_refused_before_anything_is_removed() {
2956 let eco = Ecosystem::bundled();
2957 let dir = tempdir().unwrap();
2958 let base = dir.path();
2959
2960 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2961
2962 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2963 let plugins = profile_dir.join("BepInEx/plugins");
2964
2965 install_plugin(base, &eco, "Author-Kept");
2966 write_file(&plugins.join("Other-ByHand/x.dll"), b"dll");
2967
2968 for name in ["Other-ByHand", "author-kept"] {
2969 let refused = uninstall_mod(base, &eco, "valheim", "Main", name).unwrap_err();
2970
2971 assert!(
2972 matches!(&refused, Error::NotInstalled { package } if package == name),
2973 "got: {refused:?}"
2974 );
2975 }
2976
2977 assert!(plugins.join("Other-ByHand/x.dll").exists());
2978 assert!(plugins.join("Author-Kept").exists());
2979 assert_eq!(modlist::read(&profile_dir).unwrap().len(), 1);
2980 }
2981
2982 #[test]
2983 fn uninstalling_a_batch_removes_the_loader_after_ordinary_mods_and_its_own_files() {
2984 let eco = Ecosystem::bundled();
2985 let dir = tempdir().unwrap();
2986 let base = dir.path();
2987 let loader = "denikson-BepInExPack_Valheim";
2988
2989 crate::profile::layout::create(base, "valheim", "Main").unwrap();
2990
2991 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
2992 let extracted = tempdir().unwrap();
2993
2994 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
2995 install_extracted(
2996 base,
2997 &eco,
2998 "valheim",
2999 "Main",
3000 "Author-Mod",
3001 "Author",
3002 &version("Author-Mod"),
3003 extracted.path(),
3004 None,
3005 1,
3006 )
3007 .unwrap();
3008
3009 let winhttp = profile_dir.join("winhttp.dll");
3015 let core_dll = profile_dir.join("BepInEx/core/BepInEx.dll");
3016
3017 write_file(&winhttp, b"proxy");
3018 write_file(&core_dll, b"core");
3019
3020 let mut mods = modlist::read(&profile_dir).unwrap();
3021
3022 modlist::upsert(
3023 &mut mods,
3024 mod_entry_from_version(loader, "denikson", &version(loader), 1),
3025 );
3026 modlist::write(&profile_dir, &mods).unwrap();
3027
3028 let tracker = crate::install::ModFileTracker {
3029 mod_name: loader.to_string(),
3030 files: vec![
3031 (
3032 "unused-cache-source-1".to_string(),
3033 "winhttp.dll".to_string(),
3034 ),
3035 (
3036 "unused-cache-source-2".to_string(),
3037 "BepInEx/core/BepInEx.dll".to_string(),
3038 ),
3039 ],
3040 };
3041
3042 write_state_file(&profile_dir, &tracker).unwrap();
3043
3044 let batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
3045
3046 assert_eq!(batch.mods, vec!["Author-Mod".to_string()]);
3047 assert_eq!(batch.loaders, vec![loader.to_string()]);
3048
3049 let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
3050
3051 assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
3052 assert_eq!(
3060 outcome.succeeded,
3061 vec!["Author-Mod".to_string(), loader.to_string()]
3062 );
3063 assert!(modlist::read(&profile_dir).unwrap().is_empty());
3064 assert!(!winhttp.exists());
3067 assert!(!core_dll.exists());
3068 }
3069
3070 #[test]
3071 fn planning_an_uninstall_batch_sorts_and_removes_two_recorded_loaders() {
3072 let eco = Ecosystem::bundled();
3073 let dir = tempdir().unwrap();
3074 let base = dir.path();
3075 let first_loader = "denikson-BepInExPack_Valheim";
3076 let second_loader = "1F31A-BepInEx_Valheim_Full";
3082
3083 crate::profile::layout::create(base, "valheim", "Main").unwrap();
3084
3085 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
3086
3087 let mut mods = Vec::new();
3088
3089 for loader in [first_loader, second_loader] {
3090 modlist::upsert(
3091 &mut mods,
3092 mod_entry_from_version(loader, "owner", &version(loader), 1),
3093 );
3094
3095 write_state_file(
3099 &profile_dir,
3100 &crate::install::ModFileTracker {
3101 mod_name: loader.to_string(),
3102 files: Vec::new(),
3103 },
3104 )
3105 .unwrap();
3106 }
3107
3108 modlist::write(&profile_dir, &mods).unwrap();
3109
3110 let batch = plan_uninstall_batch(&profile_dir, &eco, "valheim", None).unwrap();
3111
3112 assert!(batch.mods.is_empty());
3113 assert_eq!(
3115 batch.loaders,
3116 vec![second_loader.to_string(), first_loader.to_string()]
3117 );
3118
3119 let outcome = uninstall_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
3120
3121 assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
3122 assert!(modlist::read(&profile_dir).unwrap().is_empty());
3123 }
3124
3125 #[test]
3126 fn planning_a_toggle_batch_splits_changing_from_already_and_excludes_loaders() {
3127 let eco = Ecosystem::bundled();
3128 let dir = tempdir().unwrap();
3129 let base = dir.path();
3130 let loader = "denikson-BepInExPack_Valheim";
3131
3132 crate::profile::layout::create(base, "valheim", "Main").unwrap();
3133
3134 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
3135 let extracted = tempdir().unwrap();
3136
3137 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
3138
3139 for name in ["Author-One", "Author-Two"] {
3140 install_extracted(
3141 base,
3142 &eco,
3143 "valheim",
3144 "Main",
3145 name,
3146 "Author",
3147 &version(name),
3148 extracted.path(),
3149 None,
3150 1,
3151 )
3152 .unwrap();
3153 }
3154
3155 let mut mods = modlist::read(&profile_dir).unwrap();
3157
3158 mods.push(mod_entry_from_version(
3159 loader,
3160 "denikson",
3161 &version(loader),
3162 1,
3163 ));
3164 modlist::write(&profile_dir, &mods).unwrap();
3165
3166 disable_mod(base, &eco, "valheim", "Main", "Author-One").unwrap();
3167
3168 let batch = plan_set_enabled_batch(&profile_dir, &eco, None, false).unwrap();
3169
3170 assert_eq!(batch.changing, vec!["Author-Two".to_string()]);
3171 assert_eq!(batch.already, vec!["Author-One".to_string()]);
3172 assert_eq!(batch.loaders, vec![loader.to_string()]);
3173
3174 let outcome = set_enabled_batch(&profile_dir, &eco, "valheim", &batch).unwrap();
3175
3176 assert!(outcome.is_ok(), "failed: {:?}", outcome.failed);
3177 assert_eq!(outcome.succeeded, vec!["Author-Two".to_string()]);
3178
3179 let after = modlist::read(&profile_dir).unwrap();
3180
3181 assert!(
3182 !after
3183 .iter()
3184 .find(|m| m.name == "Author-Two")
3185 .unwrap()
3186 .enabled
3187 );
3188 assert!(after.iter().find(|m| m.name == loader).unwrap().enabled);
3190 }
3191
3192 #[test]
3193 fn plan_set_enabled_batch_refuses_an_unrecorded_name() {
3194 let eco = Ecosystem::bundled();
3195 let dir = tempdir().unwrap();
3196 let base = dir.path();
3197
3198 crate::profile::layout::create(base, "valheim", "Main").unwrap();
3199
3200 let profile_dir = crate::profile::layout::profile_dir(base, "valheim", "Main");
3201 let extracted = tempdir().unwrap();
3202
3203 write_file(&extracted.path().join("plugins/Mod.dll"), b"dll");
3204
3205 install_extracted(
3206 base,
3207 &eco,
3208 "valheim",
3209 "Main",
3210 "Author-One",
3211 "Author",
3212 &version("Author-One"),
3213 extracted.path(),
3214 None,
3215 1,
3216 )
3217 .unwrap();
3218
3219 let names = vec!["Author-Gone".to_string()];
3220 let error = plan_set_enabled_batch(&profile_dir, &eco, Some(&names), false).unwrap_err();
3221
3222 assert!(error.to_string().contains("Author-Gone"));
3223 assert!(error.to_string().contains("is not installed"));
3224 }
3225
3226 mod reinstall {
3230 use super::*;
3231 use crate::models::Package;
3232
3233 const MOD: &str = "Author-Mod";
3234 const DEP: &str = "Author-Dep";
3235 const LOADER: &str = "denikson-BepInExPack_Valheim";
3236
3237 struct Pkg<'a> {
3239 full_name: &'a str,
3240 version: &'a str,
3241 deps: &'a [&'a str],
3242 files: &'a [(&'a str, &'a [u8])],
3243 }
3244
3245 struct Repo {
3246 server: mockito::ServerGuard,
3247 mocks: Vec<mockito::Mock>,
3248 client: ThunderstoreClient,
3249 _http_cache: tempfile::TempDir,
3250 cache_base: tempfile::TempDir,
3251 target: tempfile::TempDir,
3252 eco: Ecosystem,
3253 rt: tokio::runtime::Runtime,
3254 clock: u64,
3255 }
3256
3257 impl Repo {
3258 fn new() -> Self {
3259 let server = mockito::Server::new();
3260 let http_cache = tempdir().unwrap();
3261 let client = ThunderstoreClient::builder()
3262 .package_index_url(format!("{}/pkg/", server.url()))
3263 .cache_dir(http_cache.path())
3264 .build()
3265 .unwrap();
3266
3267 Self {
3268 server,
3269 mocks: Vec::new(),
3270 client,
3271 _http_cache: http_cache,
3272 cache_base: tempdir().unwrap(),
3273 target: tempdir().unwrap(),
3274 eco: Ecosystem::bundled(),
3275 rt: tokio::runtime::Runtime::new().unwrap(),
3276 clock: 0,
3277 }
3278 }
3279
3280 fn publish(&mut self, pkgs: &[Pkg<'_>]) -> PackageIndex {
3283 let mut packages: Vec<serde_json::Value> = Vec::new();
3284
3285 for (day, pkg) in pkgs.iter().enumerate() {
3286 let path = format!("/dl/{}-{}.zip", pkg.full_name, pkg.version);
3287 let mock = self
3288 .server
3289 .mock("GET", path.as_str())
3290 .with_status(200)
3291 .with_header("Content-Type", "application/zip")
3292 .with_body(zip_of(pkg.files))
3293 .create();
3294
3295 self.mocks.push(mock);
3296
3297 let (owner, name) = pkg.full_name.split_once('-').unwrap();
3298 let created = format!("2024-01-{:02}T12:00:00Z", day + 1);
3299 let version = serde_json::json!({
3300 "name": name, "full_name": pkg.full_name, "description": "d", "icon": "i",
3301 "version_number": pkg.version, "dependencies": pkg.deps,
3302 "download_url": format!("{}{path}", self.server.url()), "downloads": 1,
3303 "date_created": created, "website_url": "", "is_active": true,
3304 "uuid4": "ver", "file_size": 1
3305 });
3306
3307 match packages
3308 .iter_mut()
3309 .find(|p| p["full_name"] == pkg.full_name)
3310 {
3311 Some(package) => package["versions"].as_array_mut().unwrap().push(version),
3312 None => packages.push(serde_json::json!({
3313 "name": name, "full_name": pkg.full_name, "owner": owner,
3314 "package_url": "https://example.com", "date_created": "2024-01-01T12:00:00Z",
3315 "date_updated": "2024-01-02T12:00:00Z", "uuid4": "pkg", "rating_score": 1,
3316 "is_pinned": false, "is_deprecated": false, "has_nsfw_content": false,
3317 "categories": [], "versions": [version]
3318 })),
3319 }
3320 }
3321
3322 let packages = packages
3323 .into_iter()
3324 .map(|json| serde_json::from_value::<Package>(json).unwrap())
3325 .collect::<Vec<_>>();
3326
3327 PackageIndex::from(packages)
3328 }
3329
3330 fn install(
3332 &mut self,
3333 index: &PackageIndex,
3334 desired: &[&str],
3335 explicit: &[&str],
3336 force: bool,
3337 ) -> BatchOutcome {
3338 let outcome = self.try_install(index, desired, explicit, force);
3339
3340 assert!(outcome.is_ok(), "batch failed: {:?}", outcome.failed);
3341
3342 outcome
3343 }
3344
3345 fn try_install(
3348 &mut self,
3349 index: &PackageIndex,
3350 desired: &[&str],
3351 explicit: &[&str],
3352 force: bool,
3353 ) -> BatchOutcome {
3354 let desired: Vec<String> = desired.iter().map(|s| s.to_string()).collect();
3355 let explicit: Vec<String> = explicit.iter().map(|s| s.to_string()).collect();
3356 let mut batch = plan_install_batch(self.target.path(), &desired, &explicit).unwrap();
3357
3358 batch.force = force;
3359 self.clock += 1;
3360
3361 self
3362 .rt
3363 .block_on(install_batch(
3364 self.target.path(),
3365 self.cache_base.path(),
3366 &self.eco,
3367 index,
3368 &self.client,
3369 "valheim",
3370 &batch,
3371 self.clock,
3372 ))
3373 .unwrap()
3374 }
3375
3376 fn path(&self, rel: &str) -> PathBuf {
3377 self.target.path().join(rel)
3378 }
3379
3380 fn entry(&self, name: &str) -> ProfileMod {
3381 modlist::read(self.target.path())
3382 .unwrap()
3383 .into_iter()
3384 .find(|m| m.name == name)
3385 .unwrap()
3386 }
3387 }
3388
3389 fn zip_of(files: &[(&str, &[u8])]) -> Vec<u8> {
3390 let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
3391 let opts: FileOptions<'_, ()> =
3392 FileOptions::default().compression_method(zip::CompressionMethod::Stored);
3393
3394 for (name, body) in files {
3395 zip.start_file(*name, opts).unwrap();
3396 zip.write_all(body).unwrap();
3397 }
3398
3399 zip.finish().unwrap().into_inner()
3400 }
3401
3402 fn names(list: &[&str]) -> Vec<String> {
3403 list.iter().map(|s| s.to_string()).collect()
3404 }
3405
3406 #[test]
3407 fn an_install_at_the_recorded_version_is_skipped() {
3408 let mut repo = Repo::new();
3409 let index = repo.publish(&[Pkg {
3410 full_name: MOD,
3411 version: "1.0.0",
3412 deps: &[],
3413 files: &[("plugins/Mod.dll", b"v1")],
3414 }]);
3415
3416 repo.install(&index, &[MOD], &[MOD], false);
3417
3418 let user_file = repo.path("BepInEx/plugins/Author-Mod/user.txt");
3419
3420 write_file(&user_file, b"mine");
3421
3422 let installed_at = repo.entry(MOD).installed_at_time;
3423 let outcome = repo.install(&index, &[MOD], &[MOD], false);
3424
3425 assert!(outcome.succeeded.is_empty());
3426 assert_eq!(outcome.unchanged, names(&[MOD]));
3427 assert!(user_file.exists(), "a skipped install must not touch files");
3428 assert_eq!(repo.entry(MOD).installed_at_time, installed_at);
3429 }
3430
3431 #[test]
3432 fn a_version_change_removes_files_only_the_old_version_had() {
3433 let mut repo = Repo::new();
3434 let v1 = repo.publish(&[Pkg {
3435 full_name: MOD,
3436 version: "1.0.0",
3437 deps: &[],
3438 files: &[
3439 ("plugins/Old.dll", b"old"),
3440 ("plugins/german.json", b"flat"),
3441 ],
3442 }]);
3443
3444 repo.install(&v1, &[MOD], &[MOD], false);
3445
3446 assert!(repo.path("BepInEx/plugins/Author-Mod/german.json").exists());
3447
3448 let v2 = repo.publish(&[Pkg {
3449 full_name: MOD,
3450 version: "2.0.0",
3451 deps: &[],
3452 files: &[
3453 ("plugins/Mod.dll", b"new"),
3454 ("plugins/Translations/German/german.json", b"nested"),
3455 ],
3456 }]);
3457 let outcome = repo.install(&v2, &[MOD], &[MOD], false);
3458
3459 assert_eq!(outcome.succeeded, names(&[MOD]));
3460 assert!(!repo.path("BepInEx/plugins/Author-Mod/Old.dll").exists());
3461 assert!(!repo.path("BepInEx/plugins/Author-Mod/german.json").exists());
3462 assert!(
3463 repo
3464 .path("BepInEx/plugins/Author-Mod/Translations/German/german.json")
3465 .exists()
3466 );
3467 assert_eq!(repo.entry(MOD).version_number.to_string(), "2.0.0");
3468 }
3469
3470 #[test]
3471 fn force_reinstalls_the_recorded_version_from_a_clean_folder() {
3472 let mut repo = Repo::new();
3473 let index = repo.publish(&[Pkg {
3474 full_name: MOD,
3475 version: "1.0.0",
3476 deps: &[],
3477 files: &[("plugins/Translations/German/german.json", b"nested")],
3478 }]);
3479
3480 repo.install(&index, &[MOD], &[MOD], false);
3481
3482 let stale = repo.path("BepInEx/plugins/Author-Mod/german.json");
3484
3485 write_file(&stale, b"flat");
3486
3487 let outcome = repo.install(&index, &[MOD], &[MOD], true);
3488
3489 assert_eq!(outcome.succeeded, names(&[MOD]));
3490 assert!(outcome.unchanged.is_empty());
3491 assert!(!stale.exists());
3492 assert!(
3493 repo
3494 .path("BepInEx/plugins/Author-Mod/Translations/German/german.json")
3495 .exists()
3496 );
3497 }
3498
3499 #[test]
3500 fn force_reinstalls_only_the_named_mod_not_its_dependencies() {
3501 let mut repo = Repo::new();
3502 let index = repo.publish(&[
3503 Pkg {
3504 full_name: MOD,
3505 version: "1.0.0",
3506 deps: &["Author-Dep-1.0.0"],
3507 files: &[("plugins/Mod.dll", b"mod")],
3508 },
3509 Pkg {
3510 full_name: DEP,
3511 version: "1.0.0",
3512 deps: &[],
3513 files: &[("plugins/Dep.dll", b"dep")],
3514 },
3515 ]);
3516
3517 repo.install(&index, &[MOD], &[MOD], false);
3518
3519 let dep_marker = repo.path("BepInEx/plugins/Author-Dep/user.txt");
3520
3521 write_file(&dep_marker, b"mine");
3522
3523 let outcome = repo.install(&index, &[MOD], &[MOD], true);
3524
3525 assert_eq!(outcome.succeeded, names(&[MOD]));
3526 assert_eq!(outcome.unchanged, names(&[DEP]));
3527 assert!(
3528 dep_marker.exists(),
3529 "the dependency must not be reinstalled"
3530 );
3531 }
3532
3533 #[test]
3534 fn a_disabled_mod_stays_disabled_through_force_and_an_update() {
3535 let mut repo = Repo::new();
3536 let v1 = repo.publish(&[Pkg {
3537 full_name: MOD,
3538 version: "1.0.0",
3539 deps: &[],
3540 files: &[("plugins/Mod.dll", b"v1"), ("plugins/Old.dll", b"v1")],
3541 }]);
3542
3543 repo.install(&v1, &[MOD], &[MOD], false);
3544
3545 set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3546
3547 repo.install(&v1, &[MOD], &[], true);
3549
3550 assert!(!repo.entry(MOD).enabled);
3551 assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll.old").exists());
3552 assert!(!repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3553
3554 let v2 = repo.publish(&[Pkg {
3555 full_name: MOD,
3556 version: "2.0.0",
3557 deps: &[],
3558 files: &[("plugins/Mod.dll", b"v2")],
3559 }]);
3560
3561 repo.install(&v2, &[MOD], &[], false);
3562
3563 assert!(!repo.entry(MOD).enabled);
3564 assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll.old").exists());
3565 assert!(!repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3566 assert!(!repo.path("BepInEx/plugins/Author-Mod/Old.dll.old").exists());
3567 }
3568
3569 #[test]
3570 fn naming_a_disabled_mod_at_its_recorded_version_enables_it() {
3571 let mut repo = Repo::new();
3572 let index = repo.publish(&[Pkg {
3573 full_name: MOD,
3574 version: "1.0.0",
3575 deps: &[],
3576 files: &[("plugins/Mod.dll", b"v1")],
3577 }]);
3578
3579 repo.install(&index, &[MOD], &[MOD], false);
3580
3581 set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3582
3583 let outcome = repo.install(&index, &[MOD], &[MOD], false);
3584
3585 assert_eq!(outcome.unchanged, names(&[MOD]));
3586 assert!(repo.entry(MOD).enabled);
3587 assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3588 assert!(!repo.path("BepInEx/plugins/Author-Mod/Mod.dll.old").exists());
3589 }
3590
3591 #[test]
3592 fn shared_config_survives_force_and_an_update() {
3593 let mut repo = Repo::new();
3594 let v1 = repo.publish(&[Pkg {
3595 full_name: MOD,
3596 version: "1.0.0",
3597 deps: &[],
3598 files: &[("plugins/Mod.dll", b"v1"), ("config/Mod.cfg", b"default")],
3599 }]);
3600
3601 repo.install(&v1, &[MOD], &[MOD], false);
3602
3603 let cfg = repo.path("BepInEx/config/Mod.cfg");
3604
3605 write_file(&cfg, b"edited");
3606 repo.install(&v1, &[MOD], &[MOD], true);
3607
3608 assert_eq!(std::fs::read(&cfg).unwrap(), b"edited");
3609
3610 let v2 = repo.publish(&[Pkg {
3611 full_name: MOD,
3612 version: "2.0.0",
3613 deps: &[],
3614 files: &[("plugins/Mod.dll", b"v2"), ("config/Mod.cfg", b"default")],
3615 }]);
3616
3617 repo.install(&v2, &[MOD], &[MOD], false);
3618
3619 assert_eq!(std::fs::read(&cfg).unwrap(), b"edited");
3620 }
3621
3622 #[test]
3623 fn force_reinstalls_a_loader_pack_and_keeps_its_config() {
3624 let mut repo = Repo::new();
3625 let index = repo.publish(&[Pkg {
3626 full_name: LOADER,
3627 version: "5.4.2333",
3628 deps: &[],
3629 files: &[
3630 ("BepInExPack_Valheim/winhttp.dll", b"proxy"),
3631 ("BepInExPack_Valheim/BepInEx/core/BepInEx.dll", b"core"),
3632 ("BepInExPack_Valheim/BepInEx/config/BepInEx.cfg", b"default"),
3633 ],
3634 }]);
3635
3636 repo.install(&index, &[LOADER], &[LOADER], false);
3637
3638 let cfg = repo.path("BepInEx/config/BepInEx.cfg");
3639 let core = repo.path("BepInEx/core/BepInEx.dll");
3640
3641 write_file(&cfg, b"edited");
3642 write_file(&core, b"tampered");
3643
3644 let outcome = repo.install(&index, &[LOADER], &[LOADER], true);
3645
3646 assert_eq!(outcome.succeeded, names(&[LOADER]));
3647 assert_eq!(std::fs::read(&core).unwrap(), b"core");
3648 assert!(repo.path("winhttp.dll").exists());
3649 assert_eq!(std::fs::read(&cfg).unwrap(), b"edited");
3650 assert!(state_file_path(repo.target.path(), LOADER).exists());
3651 }
3652
3653 #[test]
3654 fn a_recorded_mod_whose_folder_is_gone_is_reinstalled() {
3655 let mut repo = Repo::new();
3656 let index = repo.publish(&[Pkg {
3657 full_name: MOD,
3658 version: "1.0.0",
3659 deps: &[],
3660 files: &[("plugins/Mod.dll", b"v1")],
3661 }]);
3662
3663 repo.install(&index, &[MOD], &[MOD], false);
3664
3665 std::fs::remove_dir_all(repo.path("BepInEx/plugins/Author-Mod")).unwrap();
3666
3667 let outcome = repo.install(&index, &[MOD], &[MOD], false);
3668
3669 assert_eq!(outcome.succeeded, names(&[MOD]));
3670 assert!(outcome.unchanged.is_empty());
3671 assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3672 }
3673
3674 #[test]
3675 fn a_loader_pack_missing_a_tracked_file_is_reinstalled() {
3676 let mut repo = Repo::new();
3677 let index = repo.publish(&[Pkg {
3678 full_name: LOADER,
3679 version: "5.4.2333",
3680 deps: &[],
3681 files: &[
3682 ("BepInExPack_Valheim/winhttp.dll", b"proxy"),
3683 ("BepInExPack_Valheim/BepInEx/core/BepInEx.dll", b"core"),
3684 ],
3685 }]);
3686
3687 repo.install(&index, &[LOADER], &[LOADER], false);
3688
3689 std::fs::remove_file(repo.path("winhttp.dll")).unwrap();
3690
3691 let outcome = repo.install(&index, &[LOADER], &[LOADER], false);
3692
3693 assert_eq!(outcome.succeeded, names(&[LOADER]));
3694 assert!(repo.path("winhttp.dll").exists());
3695 }
3696
3697 #[test]
3698 fn a_recorded_mod_with_no_files_to_place_is_skipped() {
3699 let mut repo = Repo::new();
3700 let index = repo.publish(&[Pkg {
3701 full_name: MOD,
3702 version: "1.0.0",
3703 deps: &[],
3704 files: &[("manifest.json", b"{}"), ("README.md", b"modpack")],
3705 }]);
3706
3707 repo.install(&index, &[MOD], &[MOD], false);
3708
3709 let outcome = repo.install(&index, &[MOD], &[MOD], false);
3710
3711 assert!(outcome.succeeded.is_empty());
3712 assert_eq!(outcome.unchanged, names(&[MOD]));
3713 }
3714
3715 #[cfg(unix)]
3716 #[test]
3717 fn a_failed_enable_is_reported_per_item_without_losing_the_batch() {
3718 use std::os::unix::fs::PermissionsExt;
3719
3720 let mut repo = Repo::new();
3721 let index = repo.publish(&[
3722 Pkg {
3723 full_name: MOD,
3724 version: "1.0.0",
3725 deps: &[],
3726 files: &[("plugins/Mod.dll", b"v1")],
3727 },
3728 Pkg {
3729 full_name: DEP,
3730 version: "1.0.0",
3731 deps: &[],
3732 files: &[("plugins/Dep.dll", b"dep")],
3733 },
3734 ]);
3735
3736 repo.install(&index, &[MOD], &[MOD], false);
3737
3738 set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3739
3740 let folder = repo.path("BepInEx/plugins/Author-Mod");
3742
3743 std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o555)).unwrap();
3744
3745 if std::fs::write(folder.join("probe"), b"").is_ok() {
3746 return;
3748 }
3749
3750 let desired = names(&[MOD, DEP]);
3751 let batch = plan_install_batch(repo.target.path(), &desired, &desired).unwrap();
3752 let result = repo.rt.block_on(install_batch(
3753 repo.target.path(),
3754 repo.cache_base.path(),
3755 &repo.eco,
3756 &index,
3757 &repo.client,
3758 "valheim",
3759 &batch,
3760 1,
3761 ));
3762
3763 std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap();
3764
3765 let outcome = result.expect("a failed enable must not discard the batch");
3766 let failed: Vec<&str> = outcome.failed.iter().map(|(n, _)| n.as_str()).collect();
3767
3768 assert_eq!(failed, vec![MOD]);
3769 assert_eq!(outcome.succeeded, names(&[DEP]));
3770 assert!(outcome.unchanged.is_empty());
3771 }
3772
3773 #[test]
3774 fn a_disabled_mod_not_named_is_still_skipped() {
3775 let mut repo = Repo::new();
3776 let index = repo.publish(&[Pkg {
3777 full_name: MOD,
3778 version: "1.0.0",
3779 deps: &[],
3780 files: &[("plugins/Mod.dll", b"v1")],
3781 }]);
3782
3783 repo.install(&index, &[MOD], &[MOD], false);
3784
3785 set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3786
3787 let outcome = repo.install(&index, &[MOD], &[], false);
3788
3789 assert_eq!(outcome.unchanged, names(&[MOD]));
3790 assert!(!repo.entry(MOD).enabled);
3791 assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll.old").exists());
3792 }
3793
3794 #[test]
3795 fn a_mod_left_half_disabled_is_reinstalled() {
3796 let mut repo = Repo::new();
3797 let index = repo.publish(&[Pkg {
3798 full_name: MOD,
3799 version: "1.0.0",
3800 deps: &[],
3801 files: &[("plugins/Mod.dll", b"v1"), ("plugins/Extra.dll", b"v1")],
3802 }]);
3803
3804 repo.install(&index, &[MOD], &[MOD], false);
3805
3806 let extra = repo.path("BepInEx/plugins/Author-Mod/Extra.dll");
3809
3810 std::fs::rename(
3811 &extra,
3812 repo.path("BepInEx/plugins/Author-Mod/Extra.dll.old"),
3813 )
3814 .unwrap();
3815
3816 let outcome = repo.install(&index, &[MOD], &[MOD], false);
3817
3818 assert_eq!(outcome.succeeded, names(&[MOD]));
3819 assert!(outcome.unchanged.is_empty());
3820 assert!(extra.exists());
3821 assert!(
3822 !repo
3823 .path("BepInEx/plugins/Author-Mod/Extra.dll.old")
3824 .exists()
3825 );
3826 assert!(repo.path("BepInEx/plugins/Author-Mod/Mod.dll").exists());
3827 }
3828
3829 #[cfg(unix)]
3830 #[test]
3831 fn a_failed_loader_reinstall_keeps_it_uninstallable() {
3832 let mut repo = Repo::new();
3833 let v1 = repo.publish(&[Pkg {
3834 full_name: LOADER,
3835 version: "5.4.2333",
3836 deps: &[],
3837 files: &[
3838 ("BepInExPack_Valheim/winhttp.dll", b"proxy"),
3839 ("BepInExPack_Valheim/BepInEx/core/BepInEx.dll", b"core"),
3840 ],
3841 }]);
3842
3843 repo.install(&v1, &[LOADER], &[LOADER], false);
3844
3845 let v2 = repo.publish(&[Pkg {
3846 full_name: LOADER,
3847 version: "5.4.2334",
3848 deps: &[],
3849 files: &[
3850 ("BepInExPack_Valheim/winhttp.dll", b"proxy"),
3851 ("BepInExPack_Valheim/BepInEx/core/BepInEx.dll", b"core"),
3852 ("BepInExPack_Valheim/BepInEx/core/Extra.dll", b"extra"),
3853 ],
3854 }]);
3855
3856 std::os::unix::fs::symlink(
3859 repo.path("elsewhere.dll"),
3860 repo.path("BepInEx/core/Extra.dll"),
3861 )
3862 .unwrap();
3863
3864 let desired = names(&[LOADER]);
3865 let batch = plan_install_batch(repo.target.path(), &desired, &desired).unwrap();
3866 let outcome = repo
3867 .rt
3868 .block_on(install_batch(
3869 repo.target.path(),
3870 repo.cache_base.path(),
3871 &repo.eco,
3872 &v2,
3873 &repo.client,
3874 "valheim",
3875 &batch,
3876 2,
3877 ))
3878 .unwrap();
3879 let failed: Vec<&str> = outcome.failed.iter().map(|(n, _)| n.as_str()).collect();
3880
3881 assert_eq!(failed, vec![LOADER]);
3882 assert!(state_file_path(repo.target.path(), LOADER).exists());
3883
3884 uninstall_mod_in(repo.target.path(), &repo.eco, "valheim", LOADER).unwrap();
3885
3886 assert!(modlist::read(repo.target.path()).unwrap().is_empty());
3887 assert!(!state_file_path(repo.target.path(), LOADER).exists());
3888 }
3889
3890 fn mod_history<'a>() -> [Pkg<'a>; 2] {
3891 [
3892 Pkg {
3893 full_name: MOD,
3894 version: "1.0.0",
3895 deps: &[],
3896 files: &[("plugins/Mod.dll", b"v1")],
3897 },
3898 Pkg {
3899 full_name: MOD,
3900 version: "2.0.0",
3901 deps: &[],
3902 files: &[("plugins/Mod.dll", b"v2")],
3903 },
3904 ]
3905 }
3906
3907 #[test]
3908 fn a_pinned_install_lands_the_requested_version_not_the_latest() {
3909 let mut repo = Repo::new();
3910 let index = repo.publish(&mod_history());
3911 let dll = repo.path("BepInEx/plugins/Author-Mod/Mod.dll");
3912
3913 let outcome = repo.install(&index, &["Author-Mod-1.0.0"], &["Author-Mod-1.0.0"], false);
3914
3915 assert_eq!(outcome.succeeded, names(&[MOD]));
3916 assert_eq!(repo.entry(MOD).version_number.to_string(), "1.0.0");
3917 assert_eq!(std::fs::read(&dll).unwrap(), b"v1");
3918
3919 repo.install(&index, &[MOD], &[MOD], false);
3920
3921 assert_eq!(repo.entry(MOD).version_number.to_string(), "2.0.0");
3922 assert_eq!(std::fs::read(&dll).unwrap(), b"v2");
3923
3924 repo.install(&index, &["Author-Mod-1.0.0"], &["Author-Mod-1.0.0"], false);
3925
3926 assert_eq!(repo.entry(MOD).version_number.to_string(), "1.0.0");
3927 assert_eq!(std::fs::read(&dll).unwrap(), b"v1");
3928 }
3929
3930 #[test]
3931 fn a_pin_holds_for_another_item_in_the_batch_that_depends_on_it() {
3932 let mut repo = Repo::new();
3933 let index = repo.publish(&[
3934 Pkg {
3935 full_name: DEP,
3936 version: "1.0.0",
3937 deps: &[],
3938 files: &[("plugins/Dep.dll", b"dep1")],
3939 },
3940 Pkg {
3941 full_name: DEP,
3942 version: "2.0.0",
3943 deps: &[],
3944 files: &[("plugins/Dep.dll", b"dep2")],
3945 },
3946 Pkg {
3947 full_name: MOD,
3948 version: "1.0.0",
3949 deps: &["Author-Dep-2.0.0"],
3950 files: &[("plugins/Mod.dll", b"v1")],
3951 },
3952 ]);
3953
3954 let desired = ["Author-Dep-1.0.0", MOD];
3955
3956 repo.install(&index, &desired, &desired, false);
3957
3958 assert_eq!(repo.entry(DEP).version_number.to_string(), "1.0.0");
3959 assert_eq!(repo.entry(MOD).version_number.to_string(), "1.0.0");
3960 }
3961
3962 #[test]
3963 fn a_missing_pinned_version_fails_rather_than_installing_the_latest() {
3964 let mut repo = Repo::new();
3965 let index = repo.publish(&mod_history());
3966 let outcome = repo.try_install(&index, &["Author-Mod-9.9.9"], &["Author-Mod-9.9.9"], false);
3967
3968 assert!(outcome.succeeded.is_empty());
3969 assert_eq!(outcome.failed.len(), 1);
3970 assert_eq!(outcome.failed[0].0, "Author-Mod-9.9.9");
3971 assert!(
3972 matches!(
3973 &outcome.failed[0].1,
3974 Error::MissingVersion { package, version }
3975 if package == "Author-Mod" && version == "9.9.9"
3976 ),
3977 "{}",
3978 outcome.failed[0].1
3979 );
3980 assert_eq!(
3981 outcome.failed[0].1.to_string(),
3982 "Profile error: cannot install Author-Mod-9.9.9: Author-Mod has no version 9.9.9"
3983 );
3984 assert!(
3985 modlist::read(repo.target.path())
3986 .unwrap_or_default()
3987 .is_empty()
3988 );
3989 }
3990
3991 #[test]
3992 fn naming_a_disabled_mod_with_a_version_enables_it() {
3993 let mut repo = Repo::new();
3994 let index = repo.publish(&mod_history());
3995
3996 repo.install(&index, &["Author-Mod-1.0.0"], &["Author-Mod-1.0.0"], false);
3997 set_enabled_in(repo.target.path(), &repo.eco, "valheim", MOD, false).unwrap();
3998
3999 assert!(!repo.entry(MOD).enabled);
4000
4001 let outcome = repo.install(&index, &["Author-Mod-1.0.0"], &["Author-Mod-1.0.0"], false);
4002
4003 assert_eq!(outcome.unchanged, names(&[MOD]));
4004 assert!(repo.entry(MOD).enabled);
4005 }
4006 }
4007}
4008
4009#[cfg(test)]
4010mod planning_tests {
4011 use super::*;
4012 use time::OffsetDateTime;
4013
4014 const LOADER: &str = "denikson-BepInExPack_Valheim";
4015
4016 fn recorded(name: &str, enabled: bool) -> ProfileMod {
4017 let version = Version {
4018 name: None,
4019 full_name: Some(name.to_string()),
4020 description: None,
4021 icon: None,
4022 version_number: Some("1.0.0".to_string()),
4023 dependencies: Vec::new(),
4024 download_url: None,
4025 downloads: None,
4026 date_created: OffsetDateTime::UNIX_EPOCH,
4027 website_url: None,
4028 is_active: None,
4029 uuid4: None,
4030 file_size: None,
4031 };
4032 let mut entry = mod_entry_from_version(name, "Owner", &version, 0);
4033
4034 entry.enabled = enabled;
4035
4036 entry
4037 }
4038
4039 fn names(list: &[&str]) -> Vec<String> {
4040 list.iter().map(|name| name.to_string()).collect()
4041 }
4042
4043 #[test]
4044 fn install_batch_from_restores_disabled_mods_unless_named() {
4045 let record = [
4046 recorded("Owner-Named", false),
4047 recorded("Owner-Other", false),
4048 recorded("Owner-On", true),
4049 ];
4050
4051 let batch = plan_install_batch_from(
4052 &record,
4053 &names(&["Owner-Named-1.0.0", "Owner-New"]),
4054 &names(&["Owner-Named-1.0.0"]),
4055 );
4056
4057 assert_eq!(batch.desired, names(&["Owner-Named-1.0.0", "Owner-New"]));
4058 assert_eq!(batch.enable_requested, names(&["Owner-Named"]));
4059 assert_eq!(batch.protect_disabled, names(&["Owner-Other"]));
4060 assert!(!batch.force);
4061 }
4062
4063 #[test]
4064 fn set_enabled_batch_from_sorts_mods_and_sets_loaders_aside() {
4065 let eco = Ecosystem::bundled();
4066 let record = [
4067 recorded("Owner-B", true),
4068 recorded("Owner-A", true),
4069 recorded("Owner-Off", false),
4070 recorded(LOADER, true),
4071 ];
4072
4073 let batch = plan_set_enabled_batch_from(&record, &eco, None, false).unwrap();
4074
4075 assert_eq!(batch.changing, names(&["Owner-A", "Owner-B"]));
4076 assert_eq!(batch.already, names(&["Owner-Off"]));
4077 assert_eq!(batch.loaders, names(&[LOADER]));
4078 assert!(!batch.enabled);
4079 }
4080
4081 #[test]
4082 fn set_enabled_batch_from_refuses_an_unrecorded_name() {
4083 let eco = Ecosystem::bundled();
4084 let record = [recorded("Owner-A", true)];
4085
4086 let result = plan_set_enabled_batch_from(&record, &eco, Some(&names(&["Owner-Missing"])), true);
4087
4088 let error = result.unwrap_err();
4089
4090 assert!(matches!(&error, Error::NotInstalled { package } if package == "Owner-Missing"));
4091 assert_eq!(
4092 error.to_string(),
4093 "Profile error: Owner-Missing is not installed"
4094 );
4095 }
4096
4097 #[test]
4098 fn check_removable_from_refuses_only_unknowable_records() {
4099 let eco = Ecosystem::bundled();
4100 let dir = Path::new("/profiles/main");
4101
4102 assert!(check_removable_from(dir, &eco, LOADER, RecordState::Present).is_ok());
4103 assert!(check_removable_from(dir, &eco, "Owner-Mod", RecordState::Absent).is_ok());
4104 assert!(matches!(
4105 check_removable_from(dir, &eco, LOADER, RecordState::Absent),
4106 Err(NotRemovable::RecordAbsent { path, .. })
4107 if path == crate::install::state_file_path(dir, LOADER)
4108 ));
4109 assert!(matches!(
4110 check_removable_from(
4111 dir,
4112 &eco,
4113 "Owner-Mod",
4114 RecordState::Unreadable(Error::Install("bad yaml".to_string()))
4115 ),
4116 Err(NotRemovable::RecordUnreadable { .. })
4117 ));
4118 }
4119
4120 #[test]
4121 fn uninstall_batch_from_splits_loaders_and_keeps_untracked() {
4122 let eco = Ecosystem::bundled();
4123 let record = [
4124 recorded("Owner-B", true),
4125 recorded("Owner-A", true),
4126 recorded(LOADER, true),
4127 ];
4128 let untracked = vec![PathBuf::from("BepInEx/plugins/Stray-Mod")];
4129
4130 let batch = plan_uninstall_batch_from(
4131 Path::new("/profiles/main"),
4132 &eco,
4133 "valheim",
4134 None,
4135 &record,
4136 |_| RecordState::Present,
4137 untracked.clone(),
4138 )
4139 .unwrap();
4140
4141 assert_eq!(batch.mods, names(&["Owner-A", "Owner-B"]));
4142 assert_eq!(batch.loaders, names(&[LOADER]));
4143 assert_eq!(batch.untracked, untracked);
4144 }
4145
4146 #[test]
4147 fn uninstall_batch_from_stops_at_the_first_refusal() {
4148 let eco = Ecosystem::bundled();
4149 let record = [recorded(LOADER, true), recorded("Owner-A", true)];
4150 let mut asked = Vec::new();
4151
4152 let result = plan_uninstall_batch_from(
4153 Path::new("/profiles/main"),
4154 &eco,
4155 "valheim",
4156 Some(&names(&[LOADER, "Owner-A"])),
4157 &record,
4158 |name| {
4159 asked.push(name.to_string());
4160
4161 RecordState::Absent
4162 },
4163 Vec::new(),
4164 );
4165
4166 assert!(
4167 matches!(result, Err(Error::Profile(message)) if message.contains("cannot be removed"))
4168 );
4169 assert_eq!(asked, names(&[LOADER]));
4170 }
4171
4172 #[test]
4173 fn uninstall_batch_from_refuses_unrecorded_names_and_unknown_games() {
4174 let eco = Ecosystem::bundled();
4175 let record = [recorded("Owner-A", true)];
4176
4177 let unrecorded = plan_uninstall_batch_from(
4178 Path::new("/profiles/main"),
4179 &eco,
4180 "valheim",
4181 Some(&names(&["Owner-Missing"])),
4182 &record,
4183 |_| RecordState::Present,
4184 Vec::new(),
4185 );
4186 let unknown_game = plan_uninstall_batch_from(
4187 Path::new("/profiles/main"),
4188 &eco,
4189 "no-such-game",
4190 None,
4191 &record,
4192 |_| RecordState::Present,
4193 Vec::new(),
4194 );
4195
4196 assert!(
4197 matches!(unrecorded, Err(Error::NotInstalled { package }) if package == "Owner-Missing")
4198 );
4199 assert!(matches!(unknown_game, Err(Error::UnknownGame { game }) if game == "no-such-game"));
4200 }
4201}