1#![deny(missing_docs)]
16
17#[cfg(feature = "io")]
18use crate::client::ThunderstoreClient;
19use crate::error::{Error, Result};
20use crate::profile::modlist::{ProfileMod, SemVer};
21#[cfg(feature = "io")]
22use crate::util::{canonicalize_missing, same_file};
23#[cfg(feature = "io")]
24use base64::Engine as _;
25#[cfg(feature = "io")]
26use base64::engine::general_purpose::STANDARD;
27use serde::{Deserialize, Serialize};
28#[cfg(feature = "io")]
29use std::fs;
30#[cfg(feature = "io")]
31use std::io::{Cursor, Read, Write};
32use std::path::PathBuf;
33#[cfg(feature = "io")]
34use std::path::{Component, Path};
35#[cfg(feature = "io")]
36use zip::write::{FileOptions, ZipWriter};
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[non_exhaustive]
43pub struct ExportMod {
44 pub name: String,
46 pub version: SemVer,
48 #[serde(default = "default_true")]
50 pub enabled: bool,
51}
52
53fn default_true() -> bool {
56 true
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "camelCase")]
64#[non_exhaustive]
65pub struct ExportFormat {
66 pub profile_name: String,
68 pub mods: Vec<ExportMod>,
70}
71
72pub fn export_format_from_mods(profile_name: &str, mods: &[ProfileMod]) -> ExportFormat {
74 let mods = mods
75 .iter()
76 .map(|entry| ExportMod {
77 name: entry.name.clone(),
78 version: entry.version_number,
79 enabled: entry.enabled,
80 })
81 .collect();
82
83 ExportFormat {
84 profile_name: profile_name.to_string(),
85 mods,
86 }
87}
88
89pub fn export_r2x_to_string(export: &ExportFormat) -> Result<String> {
91 serde_yaml_ng::to_string(export)
92 .map_err(|e| Error::Profile(format!("serializing export.r2x: {e}")))
93}
94
95pub fn parse_export_r2x(yaml: &str) -> Result<ExportFormat> {
97 serde_yaml_ng::from_str(yaml).map_err(|e| Error::Profile(format!("parsing export.r2x: {e}")))
98}
99
100#[cfg(feature = "io")]
102const CONFIG_EXTENSIONS: [&str; 6] = [".cfg", ".txt", ".json", ".yml", ".yaml", ".ini"];
103
104#[cfg(feature = "io")]
111fn is_pruned(rel: &Path) -> bool {
112 let normalized = rel.to_string_lossy().replace('\\', "/");
113
114 let prefixes = [
115 "dotnet/",
116 "_state/",
117 "MelonLoader/",
118 "BepInEx/config/",
119 "GDWeave/core/",
120 "GDWeave/mods/",
121 ];
122
123 if prefixes.iter().any(|p| normalized.starts_with(p)) {
124 return true;
125 }
126
127 if normalized == "mods.yml" || normalized == "GDWeave/GDWeave.log" {
128 return true;
129 }
130
131 is_plugin_manifest(&normalized)
132}
133
134#[cfg(feature = "io")]
137fn is_plugin_manifest(normalized: &str) -> bool {
138 let parts: Vec<&str> = normalized.split('/').collect();
139
140 parts.len() == 4
141 && parts[0] == "BepInEx"
142 && parts[1] == "plugins"
143 && parts[3].eq_ignore_ascii_case("manifest.json")
144}
145
146#[cfg(feature = "io")]
149fn is_config_file(rel: &Path) -> bool {
150 let name = match rel.file_name().and_then(|n| n.to_str()) {
151 Some(name) => name.to_ascii_lowercase(),
152 None => return false,
153 };
154
155 CONFIG_EXTENSIONS.iter().any(|ext| name.ends_with(ext))
156}
157
158#[cfg(feature = "io")]
161fn collect_export_paths(target_dir: &Path) -> Result<Vec<PathBuf>> {
162 let mut found = Vec::new();
163
164 collect_files(target_dir, target_dir, &mut found)?;
165
166 let mut kept: Vec<PathBuf> = found
167 .into_iter()
168 .filter(|rel| is_config_file(rel) && !is_pruned(rel))
169 .collect();
170
171 kept.sort();
172
173 Ok(kept)
174}
175
176#[cfg(feature = "io")]
179fn collect_files(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
180 if !dir.is_dir() {
181 return Ok(());
182 }
183
184 for entry in
185 fs::read_dir(dir).map_err(|e| Error::Profile(format!("reading {}: {}", dir.display(), e)))?
186 {
187 let entry = entry.map_err(|e| Error::Profile(format!("reading an entry: {e}")))?;
188 let path = entry.path();
189 let metadata = fs::symlink_metadata(&path)
190 .map_err(|e| Error::Profile(format!("inspecting {}: {}", path.display(), e)))?;
191
192 if metadata.file_type().is_symlink() {
193 continue;
194 }
195
196 if metadata.is_dir() {
197 collect_files(root, &path, out)?;
198 } else if let Ok(rel) = path.strip_prefix(root) {
199 out.push(rel.to_path_buf());
200 }
201 }
202
203 Ok(())
204}
205
206#[cfg(feature = "io")]
208const EXPORT_MANIFEST: &str = "export.r2x";
209
210#[cfg(feature = "io")]
212const ARCHIVE_CONFIG_DIR: &str = "config";
213
214#[cfg(feature = "io")]
216const BEPINEX_CONFIG_DIR: &str = "BepInEx/config";
217
218#[cfg(feature = "io")]
247pub fn build_r2z_in(target_dir: &Path, profile_name: &str) -> Result<Vec<u8>> {
248 let mods = crate::profile::modlist::read(target_dir)?;
249 let manifest = export_r2x_to_string(&export_format_from_mods(profile_name, &mods))?;
250
251 let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
252 let options: FileOptions<'_, ()> =
253 FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
254
255 zip
256 .start_file(EXPORT_MANIFEST, options)
257 .map_err(|e| Error::Profile(format!("writing {EXPORT_MANIFEST}: {e}")))?;
258 zip
259 .write_all(manifest.as_bytes())
260 .map_err(|e| Error::Profile(format!("writing {EXPORT_MANIFEST}: {e}")))?;
261
262 let config_root = target_dir.join(BEPINEX_CONFIG_DIR);
263 let mut shared = Vec::new();
264
265 collect_files(&config_root, &config_root, &mut shared)?;
266 shared.sort();
267
268 for rel in shared {
269 let archive_path = format!(
270 "{ARCHIVE_CONFIG_DIR}/{}",
271 rel.to_string_lossy().replace('\\', "/")
272 );
273
274 add_zip_file(&mut zip, options, &archive_path, &config_root.join(&rel))?;
275 }
276
277 for rel in collect_export_paths(target_dir)? {
278 let archive_path = rel.to_string_lossy().replace('\\', "/");
279
280 add_zip_file(&mut zip, options, &archive_path, &target_dir.join(&rel))?;
281 }
282
283 let cursor = zip
284 .finish()
285 .map_err(|e| Error::Profile(format!("finishing export archive: {e}")))?;
286
287 Ok(cursor.into_inner())
288}
289
290#[cfg(feature = "io")]
292fn add_zip_file(
293 zip: &mut ZipWriter<Cursor<Vec<u8>>>,
294 options: FileOptions<'_, ()>,
295 archive_path: &str,
296 source: &Path,
297) -> Result<()> {
298 let bytes =
299 fs::read(source).map_err(|e| Error::Profile(format!("reading {}: {}", source.display(), e)))?;
300
301 zip
302 .start_file(archive_path, options)
303 .map_err(|e| Error::Profile(format!("writing {archive_path}: {e}")))?;
304 zip
305 .write_all(&bytes)
306 .map_err(|e| Error::Profile(format!("writing {archive_path}: {e}")))?;
307
308 Ok(())
309}
310
311#[cfg(feature = "io")]
320pub fn export_to_file_in(
321 target_dir: &Path,
322 profile_name: &str,
323 out_dir: &Path,
324 timestamp_millis: u64,
325) -> Result<PathBuf> {
326 crate::profile::layout::validate_existing_name(profile_name)?;
327
328 let bytes = build_r2z_in(target_dir, profile_name)?;
329
330 fs::create_dir_all(out_dir)
331 .map_err(|e| Error::Profile(format!("creating {}: {}", out_dir.display(), e)))?;
332
333 let path = out_dir.join(format!("{profile_name}_{timestamp_millis}.r2z"));
334
335 fs::write(&path, bytes)
336 .map_err(|e| Error::Profile(format!("writing {}: {}", path.display(), e)))?;
337
338 Ok(path)
339}
340
341#[cfg(feature = "io")]
344pub fn export_to_file(
345 base: &Path,
346 game: &str,
347 profile_name: &str,
348 timestamp_millis: u64,
349) -> Result<PathBuf> {
350 export_to_file_in(
351 &crate::profile::layout::profile_dir(base, game, profile_name),
352 profile_name,
353 &base.join(game).join("exports"),
354 timestamp_millis,
355 )
356}
357
358#[cfg(feature = "io")]
360const MAX_EXPORT_CODE_BYTES: usize = 20_000_000;
361
362#[cfg(feature = "io")]
364const PROFILE_DATA_PREFIX: &str = "#r2modman";
365
366#[cfg(feature = "io")]
370fn encode_profile_payload(zip_bytes: &[u8]) -> Result<Vec<u8>> {
371 if zip_bytes.len() > MAX_EXPORT_CODE_BYTES {
372 return Err(Error::SizeLimitExceeded {
373 context: "profile export".to_string(),
374 limit: MAX_EXPORT_CODE_BYTES as u64,
375 actual: Some(zip_bytes.len() as u64),
376 });
377 }
378
379 let mut payload = format!("{PROFILE_DATA_PREFIX}\n").into_bytes();
380
381 payload.extend_from_slice(STANDARD.encode(zip_bytes).as_bytes());
382
383 Ok(payload)
384}
385
386#[cfg(feature = "io")]
392pub async fn export_code_in(
393 target_dir: &Path,
394 profile_name: &str,
395 client: &ThunderstoreClient,
396) -> Result<String> {
397 let payload = encode_profile_payload(&build_r2z_in(target_dir, profile_name)?)?;
398
399 client.create_profile_code(&payload).await
400}
401
402#[cfg(feature = "io")]
404pub async fn export_code(
405 base: &Path,
406 game: &str,
407 profile_name: &str,
408 client: &ThunderstoreClient,
409) -> Result<String> {
410 export_code_in(
411 &crate::profile::layout::profile_dir(base, game, profile_name),
412 profile_name,
413 client,
414 )
415 .await
416}
417
418#[cfg(feature = "io")]
421const BLOCKED_IMPORT_EXTENSIONS: [&str; 12] = [
422 ".dll", ".exe", ".bat", ".cmd", ".com", ".ps1", ".sh", ".js", ".vbs", ".msi", ".scr", ".jar",
423];
424
425#[cfg(feature = "io")]
428fn decode_profile_payload(body: &[u8]) -> Result<Vec<u8>> {
429 let text = std::str::from_utf8(body)
430 .map_err(|e| Error::Profile(format!("profile code is not valid UTF-8: {e}")))?;
431
432 let encoded = text
433 .strip_prefix(PROFILE_DATA_PREFIX)
434 .ok_or_else(|| Error::Profile("profile code is missing its #r2modman prefix".to_string()))?;
435
436 STANDARD
437 .decode(encoded.trim())
438 .map_err(|e| Error::Profile(format!("decoding profile code: {e}")))
439}
440
441#[cfg(feature = "io")]
446const MAX_IMPORT_ENTRY_BYTES: u64 = 16 * 1024 * 1024;
447
448#[cfg(feature = "io")]
450const MAX_IMPORT_TOTAL_BYTES: u64 = 64 * 1024 * 1024;
451
452#[cfg(feature = "io")]
459fn read_capped_entry(entry: &mut impl Read, label: &str) -> Result<Vec<u8>> {
460 let mut bytes = Vec::new();
461
462 entry
463 .take(MAX_IMPORT_ENTRY_BYTES + 1)
464 .read_to_end(&mut bytes)
465 .map_err(|e| Error::Profile(format!("reading {label}: {e}")))?;
466
467 if bytes.len() as u64 > MAX_IMPORT_ENTRY_BYTES {
468 return Err(Error::ExtractLimitExceeded(format!(
469 "{label} exceeds the {MAX_IMPORT_ENTRY_BYTES}-byte per-entry import cap"
470 )));
471 }
472
473 Ok(bytes)
474}
475
476#[cfg(feature = "io")]
478pub fn read_export(bytes: &[u8]) -> Result<ExportFormat> {
479 match zip::ZipArchive::new(Cursor::new(bytes.to_vec())) {
480 Ok(mut archive) => {
481 let mut entry = archive
482 .by_name(EXPORT_MANIFEST)
483 .map_err(|e| Error::Profile(format!("archive has no {EXPORT_MANIFEST}: {e}")))?;
484
485 let manifest_bytes = read_capped_entry(&mut entry, EXPORT_MANIFEST)?;
486 let manifest = std::str::from_utf8(&manifest_bytes)
487 .map_err(|e| Error::Profile(format!("{EXPORT_MANIFEST} is not valid UTF-8: {e}")))?;
488
489 parse_export_r2x(manifest)
490 }
491 Err(_) => {
492 let text = std::str::from_utf8(bytes)
493 .map_err(|e| Error::Profile(format!("export is neither a zip nor UTF-8 YAML: {e}")))?;
494
495 parse_export_r2x(text)
496 }
497 }
498}
499
500#[cfg(feature = "io")]
513fn import_config_key(name: &str) -> Option<PathBuf> {
514 let normalized = name.replace('\\', "/");
515
516 if normalized.is_empty() || normalized.ends_with('/') {
517 return None;
518 }
519
520 if normalized == EXPORT_MANIFEST || normalized == "mods.yml" {
521 return None;
522 }
523
524 let lower = normalized.to_ascii_lowercase();
525 let probe = lower.trim_end_matches(['.', ' ']);
526
527 if BLOCKED_IMPORT_EXTENSIONS
528 .iter()
529 .any(|ext| probe.ends_with(ext))
530 {
531 return None;
532 }
533
534 let remapped = match normalized.strip_prefix("config/") {
535 Some(rest) => format!("{BEPINEX_CONFIG_DIR}/{rest}"),
536 None => normalized,
537 };
538
539 let path = PathBuf::from(remapped);
540
541 for component in path.components() {
542 match component {
543 Component::Normal(_) | Component::CurDir => {}
544 Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
545 }
546 }
547
548 let first = path.components().find_map(|component| match component {
549 Component::Normal(name) => Some(name.to_string_lossy().to_ascii_lowercase()),
550 _ => None,
551 });
552
553 if first.is_some_and(|first| first.trim_end_matches(['.', ' ']) == "_state") {
554 return None;
555 }
556
557 Some(path)
558}
559
560#[cfg(feature = "io")]
569fn looks_like_zip(bytes: &[u8]) -> bool {
570 bytes.len() >= 2 && &bytes[0..2] == b"PK"
571}
572
573#[cfg(feature = "io")]
582fn refuse_symlink_dest(dest: &Path) -> Result<()> {
583 let is_symlink = fs::symlink_metadata(dest)
584 .map(|metadata| metadata.file_type().is_symlink())
585 .unwrap_or(false);
586
587 if is_symlink {
588 return Err(Error::Profile(format!(
589 "refusing to write through a symlink at {}",
590 dest.display()
591 )));
592 }
593
594 Ok(())
595}
596
597#[cfg(feature = "io")]
615pub fn extract_configs_in(target_dir: &Path, zip_bytes: &[u8]) -> Result<Vec<PathBuf>> {
616 if !looks_like_zip(zip_bytes) {
617 return Ok(Vec::new());
618 }
619
620 let mut archive = zip::ZipArchive::new(Cursor::new(zip_bytes.to_vec()))
621 .map_err(|e| Error::Profile(format!("reading export archive: {e}")))?;
622
623 let mut written = Vec::new();
624 let mut total_written: u64 = 0;
625
626 for index in 0..archive.len() {
627 let mut entry = archive
628 .by_index(index)
629 .map_err(|e| Error::Profile(format!("reading archive entry {index}: {e}")))?;
630
631 let rel = match import_config_key(entry.name()) {
632 Some(rel) => rel,
633 None => continue,
634 };
635
636 let bytes = read_capped_entry(&mut entry, &rel.display().to_string())?;
637
638 total_written += bytes.len() as u64;
639
640 if total_written > MAX_IMPORT_TOTAL_BYTES {
641 return Err(Error::ExtractLimitExceeded(format!(
642 "import exceeds the {MAX_IMPORT_TOTAL_BYTES}-byte cumulative import cap"
643 )));
644 }
645
646 let dest = target_dir.join(&rel);
647
648 if let Some(parent) = dest.parent() {
649 fs::create_dir_all(parent)
650 .map_err(|e| Error::Profile(format!("creating {}: {}", parent.display(), e)))?;
651 }
652
653 refuse_symlink_dest(&dest)?;
654 fs::write(&dest, &bytes)
655 .map_err(|e| Error::Profile(format!("writing {}: {}", dest.display(), e)))?;
656
657 written.push(rel);
658 }
659
660 Ok(written)
661}
662
663#[allow(clippy::too_many_arguments)]
696#[cfg(feature = "io")]
697pub async fn import_r2z_in(
698 target_dir: &Path,
699 cache_base: &Path,
700 eco: &crate::ecosystem::Ecosystem,
701 index: &crate::models::PackageIndex,
702 client: &ThunderstoreClient,
703 game: &str,
704 zip_bytes: &[u8],
705 installed_at_time: u64,
706) -> Result<ImportedMods> {
707 let export = read_export(zip_bytes)?;
708
709 let desired: Vec<String> = export
710 .mods
711 .iter()
712 .map(|entry| format!("{}-{}", entry.name, entry.version))
713 .collect();
714 let protect: Vec<String> = export
715 .mods
716 .iter()
717 .filter(|entry| !entry.enabled)
718 .map(|entry| entry.name.clone())
719 .collect();
720 let mut batch = crate::profile::InstallBatch::new(desired, protect);
721
722 batch.enable_requested = export
726 .mods
727 .iter()
728 .filter(|entry| entry.enabled)
729 .map(|entry| entry.name.clone())
730 .collect();
731
732 let outcome = crate::profile::install_batch(
733 target_dir,
734 cache_base,
735 eco,
736 index,
737 client,
738 game,
739 &batch,
740 installed_at_time,
741 )
742 .await?;
743
744 if !outcome.failed.is_empty() {
749 return Err(Error::ImportUnfinished {
750 failures: outcome.failed,
751 });
752 }
753
754 let config_dir = target_dir.to_path_buf();
757 let config_zip = zip_bytes.to_vec();
758
759 tokio::task::spawn_blocking(move || extract_configs_in(&config_dir, &config_zip))
760 .await
761 .map_err(|e| Error::Install(format!("config extraction task failed: {e}")))??;
762
763 Ok(ImportedMods {
765 installed: outcome.succeeded,
766 unchanged: outcome.unchanged,
767 })
768}
769
770#[derive(Debug, Clone, Default, PartialEq, Eq)]
776#[non_exhaustive]
777pub struct ImportedMods {
778 pub installed: Vec<String>,
780 pub unchanged: Vec<String>,
787}
788
789#[allow(clippy::too_many_arguments)]
791#[cfg(feature = "io")]
792pub async fn import_code_in(
793 target_dir: &Path,
794 cache_base: &Path,
795 eco: &crate::ecosystem::Ecosystem,
796 index: &crate::models::PackageIndex,
797 client: &ThunderstoreClient,
798 game: &str,
799 code: &str,
800 installed_at_time: u64,
801) -> Result<ImportedMods> {
802 let body = client.fetch_profile_code(code).await?;
803 let zip_bytes = decode_profile_payload(&body)?;
804
805 import_r2z_in(
806 target_dir,
807 cache_base,
808 eco,
809 index,
810 client,
811 game,
812 &zip_bytes,
813 installed_at_time,
814 )
815 .await
816}
817
818#[cfg(feature = "io")]
845pub fn import_r2modman_dir(source_profile_dir: &Path, target_dir: &Path) -> Result<()> {
846 if !source_profile_dir.is_dir() {
847 return Err(Error::Profile(format!(
848 "{} is not a profile directory",
849 source_profile_dir.display()
850 )));
851 }
852
853 ensure_disjoint_trees(source_profile_dir, target_dir)?;
854
855 copy_tree(source_profile_dir, target_dir)
856}
857
858#[derive(Debug, Clone, Default)]
861#[non_exhaustive]
862pub struct AdoptedProfile {
863 pub adopted: Vec<String>,
865 pub reinstalled: Vec<String>,
872}
873
874#[allow(clippy::too_many_arguments)]
907#[cfg(feature = "io")]
908pub async fn adopt_r2modman_dir_in(
909 source_profile_dir: &Path,
910 target_dir: &Path,
911 cache_base: &Path,
912 eco: &crate::ecosystem::Ecosystem,
913 client: &ThunderstoreClient,
914 game: &str,
915 installed_at_time: u64,
916) -> Result<AdoptedProfile> {
917 import_r2modman_dir(source_profile_dir, target_dir)?;
918
919 let adopted: Vec<String> = crate::profile::modlist::read(target_dir)?
920 .iter()
921 .map(|entry| entry.name.clone())
922 .collect();
923
924 let unrecorded: Vec<String> = adopted
932 .iter()
933 .filter(|name| eco.modloader_package(name).is_some())
934 .filter(|name| !crate::install::state_file_path(target_dir, name).exists())
935 .cloned()
936 .collect();
937
938 if unrecorded.is_empty() {
939 return Ok(AdoptedProfile {
940 adopted,
941 reinstalled: unrecorded,
942 });
943 }
944
945 let index = client.get_manifest().await?;
946
947 for full_name in &unrecorded {
951 crate::profile::install_named_in(
952 target_dir,
953 cache_base,
954 eco,
955 &index,
956 client,
957 game,
958 full_name,
959 true,
960 installed_at_time,
961 )
962 .await?;
963 }
964
965 Ok(AdoptedProfile {
966 adopted,
967 reinstalled: unrecorded,
968 })
969}
970
971#[derive(Debug, Default)]
977#[non_exhaustive]
978pub struct AdoptOutcome {
979 pub adopted: Vec<String>,
981 pub unchanged: Vec<String>,
985 pub remaining: Vec<String>,
993 pub swept: Vec<PathBuf>,
996 pub failed: Vec<(String, Error)>,
1004}
1005
1006#[cfg(feature = "io")]
1014pub fn needs_adoption(target_dir: &Path, desired: &[String]) -> Result<bool> {
1015 if desired.is_empty() {
1016 return Ok(false);
1017 }
1018
1019 let recorded = crate::profile::modlist::read(target_dir).unwrap_or_default();
1020
1021 Ok(
1022 desired
1023 .iter()
1024 .any(|name| crate::profile::modlist::find(&recorded, name).is_none()),
1025 )
1026}
1027
1028#[allow(clippy::too_many_arguments)]
1044#[cfg(feature = "io")]
1045pub async fn adopt_names_in(
1046 target_dir: &Path,
1047 cache_base: &Path,
1048 eco: &crate::ecosystem::Ecosystem,
1049 index: &crate::models::PackageIndex,
1050 client: &ThunderstoreClient,
1051 game: &str,
1052 desired: &[String],
1053 installed_at_time: u64,
1054) -> Result<AdoptOutcome> {
1055 let batch = crate::profile::plan_install_batch(target_dir, desired, &[])?;
1056
1057 let batch_outcome = crate::profile::install_batch(
1058 target_dir,
1059 cache_base,
1060 eco,
1061 index,
1062 client,
1063 game,
1064 &batch,
1065 installed_at_time,
1066 )
1067 .await?;
1068
1069 let failed = batch_outcome.failed;
1070 let failed_names: std::collections::BTreeSet<&str> =
1071 failed.iter().map(|(name, _)| name.as_str()).collect();
1072
1073 let recorded = crate::profile::modlist::read(target_dir).unwrap_or_default();
1080
1081 let mut adopted: Vec<String> = Vec::new();
1082 let mut unchanged: Vec<String> = Vec::new();
1083 let mut remaining: Vec<String> = Vec::new();
1084
1085 for name in desired {
1086 let Some(entry) = crate::profile::modlist::find(&recorded, name) else {
1087 remaining.push(name.clone());
1088
1089 continue;
1090 };
1091
1092 if failed_names.contains(name.as_str()) {
1093 continue;
1096 }
1097
1098 if entry.installed_at_time == installed_at_time {
1099 adopted.push(name.clone());
1100 } else {
1101 unchanged.push(name.clone());
1102 }
1103 }
1104
1105 adopted.sort();
1106 adopted.dedup();
1107 unchanged.sort();
1108 unchanged.dedup();
1109 remaining.sort();
1110 remaining.dedup();
1111
1112 if !remaining.is_empty() {
1113 return Ok(AdoptOutcome {
1114 adopted,
1115 unchanged,
1116 remaining,
1117 swept: Vec::new(),
1118 failed,
1119 });
1120 }
1121
1122 let game_profile = eco.require_profile(game)?;
1123 let keep: std::collections::BTreeSet<String> =
1124 recorded.iter().map(|entry| entry.name.clone()).collect();
1125 let swept = crate::install::remove_delisted(game_profile, target_dir, &keep)?;
1126
1127 Ok(AdoptOutcome {
1128 adopted,
1129 unchanged,
1130 remaining,
1131 swept,
1132 failed,
1133 })
1134}
1135
1136#[cfg(feature = "io")]
1155pub fn ensure_disjoint_trees(source: &Path, target: &Path) -> Result<()> {
1156 let source_at = resolve_as_far_as_it_exists(source);
1157 let target_at = resolve_as_far_as_it_exists(target);
1158
1159 if source_at == target_at {
1160 return Err(Error::Profile(format!(
1161 "refusing to copy {} onto itself: every file would be truncated to zero \
1162 bytes",
1163 source.display()
1164 )));
1165 }
1166
1167 if source_at.starts_with(&target_at) {
1168 return Err(Error::Profile(format!(
1169 "refusing to copy {} into {}: the source lives inside the destination, so \
1170 the copy would overwrite the tree it is reading",
1171 source.display(),
1172 target.display()
1173 )));
1174 }
1175
1176 if target_at.starts_with(&source_at) {
1177 return Err(Error::Profile(format!(
1178 "refusing to copy {} into {}: the destination lives inside the source, so \
1179 the copy would recurse into itself",
1180 source.display(),
1181 target.display()
1182 )));
1183 }
1184
1185 Ok(())
1186}
1187
1188#[cfg(feature = "io")]
1210fn resolve_as_far_as_it_exists(path: &Path) -> PathBuf {
1211 if let Ok(canonical) = path.canonicalize() {
1212 return canonical;
1213 }
1214
1215 if let Ok(canonical) = canonicalize_missing(path) {
1216 return canonical;
1217 }
1218
1219 for ancestor in path.ancestors().skip(1) {
1220 let Ok(canonical_ancestor) = ancestor.canonicalize() else {
1221 continue;
1222 };
1223 let Ok(remainder) = path.strip_prefix(ancestor) else {
1224 continue;
1225 };
1226
1227 return canonical_ancestor.join(remainder);
1228 }
1229
1230 path.to_path_buf()
1231}
1232
1233#[cfg(feature = "io")]
1239fn copy_tree(src: &Path, dst: &Path) -> Result<()> {
1240 fs::create_dir_all(dst)
1241 .map_err(|e| Error::Profile(format!("creating {}: {}", dst.display(), e)))?;
1242
1243 for entry in
1244 fs::read_dir(src).map_err(|e| Error::Profile(format!("reading {}: {}", src.display(), e)))?
1245 {
1246 let entry = entry.map_err(|e| Error::Profile(format!("reading an entry: {e}")))?;
1247 let path = entry.path();
1248 let metadata = fs::symlink_metadata(&path)
1249 .map_err(|e| Error::Profile(format!("inspecting {}: {}", path.display(), e)))?;
1250
1251 if metadata.file_type().is_symlink() {
1252 continue;
1253 }
1254
1255 let target = dst.join(entry.file_name());
1256
1257 if metadata.is_dir() {
1258 copy_tree(&path, &target)?;
1259 } else {
1260 refuse_symlink_dest(&target)?;
1261
1262 if same_file(&path, &target) {
1269 continue;
1270 }
1271
1272 fs::copy(&path, &target)
1273 .map_err(|e| Error::Profile(format!("copying to {}: {}", target.display(), e)))?;
1274 }
1275 }
1276
1277 Ok(())
1278}
1279
1280#[derive(Debug, Clone, PartialEq, Eq)]
1293pub enum ImportSource {
1294 R2modmanDir(PathBuf),
1296 Archive(PathBuf),
1298 Code(String),
1300}
1301
1302#[cfg(feature = "io")]
1303impl ImportSource {
1304 pub fn classify(source: &str) -> Self {
1311 let path = Path::new(source);
1312
1313 if path.is_dir() {
1314 return Self::R2modmanDir(path.to_path_buf());
1315 }
1316
1317 if path.is_file() {
1318 return Self::Archive(path.to_path_buf());
1319 }
1320
1321 Self::Code(source.to_string())
1322 }
1323}
1324
1325#[derive(Debug)]
1332#[non_exhaustive]
1333pub struct ImportOutcome {
1334 pub source: ImportSource,
1336 pub installed: Vec<String>,
1341 pub unchanged: Vec<String>,
1346 pub reinstalled: Vec<String>,
1350}
1351
1352#[cfg(feature = "io")]
1369pub async fn import_in(
1370 target_dir: &Path,
1371 cache_base: &Path,
1372 eco: &crate::ecosystem::Ecosystem,
1373 client: &ThunderstoreClient,
1374 game: &str,
1375 source: &str,
1376 installed_at_time: u64,
1377) -> Result<ImportOutcome> {
1378 let source = ImportSource::classify(source);
1379
1380 if let ImportSource::R2modmanDir(dir) = &source {
1381 let adopted = adopt_r2modman_dir_in(
1382 dir,
1383 target_dir,
1384 cache_base,
1385 eco,
1386 client,
1387 game,
1388 installed_at_time,
1389 )
1390 .await?;
1391 let mut installed = adopted.adopted;
1392
1393 installed.sort();
1394 installed.dedup();
1395
1396 return Ok(ImportOutcome {
1397 source,
1398 installed,
1399 unchanged: Vec::new(),
1400 reinstalled: adopted.reinstalled,
1401 });
1402 }
1403
1404 let index = client.get_manifest().await?;
1405
1406 let imported = match &source {
1407 ImportSource::Archive(path) => {
1408 let bytes =
1409 fs::read(path).map_err(|e| Error::Profile(format!("reading {}: {}", path.display(), e)))?;
1410
1411 import_r2z_in(
1412 target_dir,
1413 cache_base,
1414 eco,
1415 &index,
1416 client,
1417 game,
1418 &bytes,
1419 installed_at_time,
1420 )
1421 .await?
1422 }
1423 ImportSource::Code(code) => {
1424 import_code_in(
1425 target_dir,
1426 cache_base,
1427 eco,
1428 &index,
1429 client,
1430 game,
1431 code,
1432 installed_at_time,
1433 )
1434 .await?
1435 }
1436 ImportSource::R2modmanDir(_) => {
1441 unreachable!("R2modmanDir returns from the early branch above this match")
1442 }
1443 };
1444
1445 Ok(ImportOutcome {
1446 source,
1447 installed: imported.installed,
1448 unchanged: imported.unchanged,
1449 reinstalled: Vec::new(),
1450 })
1451}
1452
1453#[allow(clippy::too_many_arguments)]
1455#[cfg(feature = "io")]
1456pub async fn import_r2z(
1457 base: &Path,
1458 game: &str,
1459 profile_name: &str,
1460 eco: &crate::ecosystem::Ecosystem,
1461 index: &crate::models::PackageIndex,
1462 client: &ThunderstoreClient,
1463 zip_bytes: &[u8],
1464 installed_at_time: u64,
1465) -> Result<ImportedMods> {
1466 import_r2z_in(
1467 &crate::profile::layout::profile_dir(base, game, profile_name),
1468 base,
1469 eco,
1470 index,
1471 client,
1472 game,
1473 zip_bytes,
1474 installed_at_time,
1475 )
1476 .await
1477}
1478
1479#[allow(clippy::too_many_arguments)]
1482#[cfg(feature = "io")]
1483pub async fn import_code(
1484 base: &Path,
1485 game: &str,
1486 profile_name: &str,
1487 eco: &crate::ecosystem::Ecosystem,
1488 index: &crate::models::PackageIndex,
1489 client: &ThunderstoreClient,
1490 code: &str,
1491 installed_at_time: u64,
1492) -> Result<ImportedMods> {
1493 import_code_in(
1494 &crate::profile::layout::profile_dir(base, game, profile_name),
1495 base,
1496 eco,
1497 index,
1498 client,
1499 game,
1500 code,
1501 installed_at_time,
1502 )
1503 .await
1504}
1505
1506#[cfg(all(test, feature = "io"))]
1507mod tests {
1508 use super::*;
1509
1510 fn profile_mod(name: &str, enabled: bool) -> ProfileMod {
1511 let mut entry = crate::profile::mod_entry_from_version(name, "Author", &sample_version(), 1);
1512 entry.enabled = enabled;
1513
1514 entry
1515 }
1516
1517 fn sample_version() -> crate::models::Version {
1518 let json = r#"{"name":"Mod","full_name":"Author-Mod","description":"d","icon":"i",
1520 "version_number":"1.2.3","dependencies":[],"download_url":"u","downloads":1,
1521 "date_created":"2024-01-01T12:00:00Z","website_url":"w","is_active":true,
1522 "uuid4":"u","file_size":1}"#;
1523
1524 serde_json::from_str(json).unwrap()
1525 }
1526
1527 #[test]
1528 fn import_source_classifies_a_directory_a_file_and_a_code() {
1529 let dir = tempfile::tempdir().unwrap();
1530 let profile = dir.path().join("SomeProfile");
1531 let archive = dir.path().join("export.r2z");
1532
1533 std::fs::create_dir_all(&profile).unwrap();
1534 write_test_file(&archive, b"not really a zip");
1535
1536 assert!(matches!(
1537 ImportSource::classify(profile.to_str().unwrap()),
1538 ImportSource::R2modmanDir(path) if path == profile
1539 ));
1540 assert!(matches!(
1541 ImportSource::classify(archive.to_str().unwrap()),
1542 ImportSource::Archive(path) if path == archive
1543 ));
1544
1545 assert!(matches!(
1549 ImportSource::classify("abc123-def456"),
1550 ImportSource::Code(code) if code == "abc123-def456"
1551 ));
1552 assert!(matches!(
1553 ImportSource::classify("/no/such/path.r2z"),
1554 ImportSource::Code(_)
1555 ));
1556 }
1557
1558 #[test]
1559 fn export_format_maps_mods_and_preserves_enabled() {
1560 let mods = vec![
1561 profile_mod("Author-A", true),
1562 profile_mod("Author-B", false),
1563 ];
1564
1565 let export = export_format_from_mods("MyProfile", &mods);
1566
1567 assert_eq!(export.profile_name, "MyProfile");
1568 assert_eq!(export.mods.len(), 2);
1569 assert_eq!(export.mods[0].name, "Author-A");
1570 assert_eq!(
1571 export.mods[0].version,
1572 SemVer {
1573 major: 1,
1574 minor: 2,
1575 patch: 3
1576 }
1577 );
1578 assert!(export.mods[0].enabled);
1579 assert!(!export.mods[1].enabled);
1580 }
1581
1582 #[test]
1583 fn serialized_r2x_uses_version_not_version_number() {
1584 let mods = vec![profile_mod("Author-A", true)];
1585 let yaml = export_r2x_to_string(&export_format_from_mods("MyProfile", &mods)).unwrap();
1586
1587 assert!(yaml.contains("profileName: MyProfile"));
1588 assert!(yaml.contains("name: Author-A"));
1589 assert!(yaml.contains("version:"));
1590 assert!(yaml.contains("major: 1"));
1591 assert!(!yaml.contains("versionNumber"));
1593 }
1594
1595 #[test]
1596 fn parses_real_r2x_and_defaults_missing_enabled_to_true() {
1597 let yaml = r#"profileName: Shared
1598mods:
1599 - name: Author-A
1600 version:
1601 major: 2
1602 minor: 0
1603 patch: 1
1604 enabled: false
1605 - name: Author-B
1606 version:
1607 major: 1
1608 minor: 0
1609 patch: 0
1610"#;
1611
1612 let export = parse_export_r2x(yaml).unwrap();
1613
1614 assert_eq!(export.profile_name, "Shared");
1615 assert_eq!(export.mods.len(), 2);
1616 assert!(!export.mods[0].enabled);
1617 assert!(export.mods[1].enabled);
1619 }
1620
1621 #[test]
1622 fn parse_export_r2x_rejects_malformed() {
1623 assert!(parse_export_r2x("not: a valid export").is_err());
1624 }
1625
1626 fn write_test_file(path: &Path, bytes: &[u8]) {
1627 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1628 std::fs::write(path, bytes).unwrap();
1629 }
1630
1631 #[test]
1632 fn is_pruned_matches_r2modman_rules() {
1633 assert!(is_pruned(Path::new("dotnet/x.json")));
1635 assert!(is_pruned(Path::new("_state/Author-Mod-state.yml")));
1636 assert!(is_pruned(Path::new("BepInEx/config/BepInEx.cfg")));
1637 assert!(is_pruned(Path::new(
1638 "BepInEx/plugins/Author-Mod/manifest.json"
1639 )));
1640 assert!(is_pruned(Path::new("MelonLoader/x.cfg")));
1641 assert!(is_pruned(Path::new("GDWeave/core/a.json")));
1642 assert!(is_pruned(Path::new("GDWeave/mods/b.json")));
1643 assert!(is_pruned(Path::new("GDWeave/GDWeave.log")));
1644 assert!(is_pruned(Path::new("mods.yml")));
1645
1646 assert!(!is_pruned(Path::new(
1648 "BepInEx/plugins/Author-Mod/settings.cfg"
1649 )));
1650 assert!(!is_pruned(Path::new("GDWeave/other.json")));
1651 assert!(!is_pruned(Path::new("notes.txt")));
1652 }
1653
1654 #[test]
1655 fn is_config_file_matches_supported_extensions() {
1656 assert!(is_config_file(Path::new("a/b.cfg")));
1657 assert!(is_config_file(Path::new("a/b.YAML")));
1658 assert!(is_config_file(Path::new("b.ini")));
1659 assert!(!is_config_file(Path::new("a/b.dll")));
1660 assert!(!is_config_file(Path::new("a/b")));
1661 }
1662
1663 #[test]
1664 fn collect_export_paths_selects_configs_and_skips_pruned() {
1665 let dir = tempfile::tempdir().unwrap();
1666 let root = dir.path();
1667
1668 write_test_file(&root.join("mods.yml"), b"[]");
1669 write_test_file(&root.join("BepInEx/config/BepInEx.cfg"), b"cfg");
1670 write_test_file(&root.join("BepInEx/plugins/Author-Mod/settings.cfg"), b"s");
1671 write_test_file(
1672 &root.join("BepInEx/plugins/Author-Mod/manifest.json"),
1673 b"{}",
1674 );
1675 write_test_file(&root.join("BepInEx/plugins/Author-Mod/Mod.dll"), b"dll");
1676 write_test_file(&root.join("_state/Author-Mod-state.yml"), b"x");
1677
1678 let paths = collect_export_paths(root).unwrap();
1679 let as_str: Vec<String> = paths
1680 .iter()
1681 .map(|p| p.to_string_lossy().replace('\\', "/"))
1682 .collect();
1683
1684 assert_eq!(
1685 as_str,
1686 vec!["BepInEx/plugins/Author-Mod/settings.cfg".to_string()]
1687 );
1688 }
1689
1690 #[test]
1691 fn build_r2z_contains_manifest_and_configs() {
1692 let dir = tempfile::tempdir().unwrap();
1693 let root = dir.path();
1694
1695 crate::profile::modlist::write(root, &[profile_mod("Author-A", true)]).unwrap();
1696 write_test_file(&root.join("BepInEx/config/BepInEx.cfg"), b"shared");
1697 write_test_file(&root.join("BepInEx/plugins/Author-A/settings.cfg"), b"mine");
1698 write_test_file(&root.join("BepInEx/plugins/Author-A/Mod.dll"), b"dll");
1699
1700 let bytes = build_r2z_in(root, "MyProfile").unwrap();
1701
1702 let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
1703 let names: Vec<String> = (0..zip.len())
1704 .map(|i| zip.by_index(i).unwrap().name().replace('\\', "/"))
1705 .collect();
1706
1707 assert!(names.contains(&"export.r2x".to_string()));
1708 assert!(names.contains(&"config/BepInEx.cfg".to_string()));
1710 assert!(names.contains(&"BepInEx/plugins/Author-A/settings.cfg".to_string()));
1712 assert!(!names.iter().any(|n| n.ends_with("Mod.dll")));
1714 assert!(!names.contains(&"mods.yml".to_string()));
1715
1716 let mut manifest = String::new();
1717 std::io::Read::read_to_string(&mut zip.by_name("export.r2x").unwrap(), &mut manifest).unwrap();
1718
1719 let export = parse_export_r2x(&manifest).unwrap();
1720
1721 assert_eq!(export.profile_name, "MyProfile");
1722 assert_eq!(export.mods[0].name, "Author-A");
1723 }
1724
1725 #[test]
1726 fn export_to_file_uses_name_and_timestamp() {
1727 let dir = tempfile::tempdir().unwrap();
1728 let root = dir.path().join("profile");
1729 let out = dir.path().join("exports");
1730
1731 crate::profile::modlist::write(&root, &[profile_mod("Author-A", true)]).unwrap();
1732
1733 let path = export_to_file_in(&root, "MyProfile", &out, 1_700_000_000_000).unwrap();
1734
1735 assert_eq!(
1736 path.file_name().unwrap().to_string_lossy(),
1737 "MyProfile_1700000000000.r2z"
1738 );
1739 assert!(path.exists());
1740 }
1741
1742 #[test]
1743 fn export_to_file_rejects_unsafe_profile_name() {
1744 let dir = tempfile::tempdir().unwrap();
1745 let root = dir.path().join("profile");
1746 let out = dir.path().join("exports");
1747
1748 crate::profile::modlist::write(&root, &[profile_mod("Author-A", true)]).unwrap();
1749
1750 assert!(export_to_file_in(&root, "../evil", &out, 1).is_err());
1751 assert!(!dir.path().join("evil_1.r2z").exists());
1752 }
1753
1754 #[test]
1755 #[cfg(unix)]
1756 fn export_to_file_accepts_a_profile_named_under_the_old_rules() {
1757 let dir = tempfile::tempdir().unwrap();
1758 let root = dir.path().join("profile");
1759 let out = dir.path().join("exports");
1760
1761 crate::profile::modlist::write(&root, &[profile_mod("Author-A", true)]).unwrap();
1762
1763 let path = export_to_file_in(&root, "v2: test", &out, 1).unwrap();
1764
1765 assert_eq!(path, out.join("v2: test_1.r2z"));
1766 }
1767
1768 #[test]
1769 fn encode_profile_payload_prefixes_and_base64s() {
1770 let payload = encode_profile_payload(b"ABC").unwrap();
1771
1772 assert_eq!(payload, b"#r2modman\nQUJD");
1773 }
1774
1775 #[test]
1776 fn encode_profile_payload_rejects_oversize() {
1777 let big = vec![0u8; MAX_EXPORT_CODE_BYTES + 1];
1778
1779 assert!(matches!(
1780 encode_profile_payload(&big),
1781 Err(Error::SizeLimitExceeded { .. })
1782 ));
1783 }
1784
1785 #[test]
1786 fn decode_profile_payload_round_trips_and_rejects_bad_prefix() {
1787 let payload = encode_profile_payload(b"ABC").unwrap();
1788
1789 assert_eq!(decode_profile_payload(&payload).unwrap(), b"ABC");
1790 assert!(decode_profile_payload(b"nope\nQUJD").is_err());
1791 }
1792
1793 #[test]
1794 fn import_config_key_remaps_config_and_blocks_unsafe() {
1795 assert_eq!(
1797 import_config_key("config/BepInEx.cfg"),
1798 Some(PathBuf::from("BepInEx/config/BepInEx.cfg"))
1799 );
1800 assert_eq!(
1802 import_config_key("BepInEx/plugins/Author-A/settings.cfg"),
1803 Some(PathBuf::from("BepInEx/plugins/Author-A/settings.cfg"))
1804 );
1805 assert_eq!(import_config_key("export.r2x"), None);
1807 assert_eq!(import_config_key("mods.yml"), None);
1808 assert_eq!(import_config_key("_state/Author-Mod-state.yml"), None);
1809 assert_eq!(import_config_key("./_STATE /Author-Mod-state.yml"), None);
1810 assert_eq!(import_config_key("BepInEx/plugins/evil.dll"), None);
1812 assert_eq!(import_config_key("../escape.cfg"), None);
1814 }
1815
1816 #[test]
1817 fn import_config_key_blocks_trailing_dot_and_space_bypass() {
1818 let blocked = [
1822 "evil.dll.",
1823 "evil.dll ",
1824 "evil.dll. . ",
1825 "evil.DLL",
1826 "evil.cfg.dll",
1827 ];
1828
1829 for name in blocked {
1830 assert_eq!(
1831 import_config_key(name),
1832 None,
1833 "{name} should have been blocked"
1834 );
1835 }
1836
1837 assert_eq!(import_config_key("a.cfg"), Some(PathBuf::from("a.cfg")));
1839 }
1840
1841 #[test]
1844 #[cfg(windows)]
1845 fn import_config_key_refuses_a_drive_prefix() {
1846 assert_eq!(import_config_key(r"C:\Windows\evil.cfg"), None);
1847 assert_eq!(import_config_key("C:evil.cfg"), None);
1848 assert_eq!(import_config_key(r"\\server\share\evil.cfg"), None);
1849 }
1850
1851 #[test]
1852 fn read_export_accepts_r2z_and_bare_r2x() {
1853 let dir = tempfile::tempdir().unwrap();
1854 let root = dir.path();
1855
1856 crate::profile::modlist::write(root, &[profile_mod("Author-A", true)]).unwrap();
1857
1858 let zip_bytes = build_r2z_in(root, "MyProfile").unwrap();
1859
1860 assert_eq!(read_export(&zip_bytes).unwrap().profile_name, "MyProfile");
1861
1862 let yaml = export_r2x_to_string(&export_format_from_mods("Bare", &[])).unwrap();
1863
1864 assert_eq!(read_export(yaml.as_bytes()).unwrap().profile_name, "Bare");
1865 }
1866
1867 #[test]
1868 fn extract_configs_writes_remapped_files_only() {
1869 let dir = tempfile::tempdir().unwrap();
1870 let source = dir.path().join("source");
1871 let target = dir.path().join("target");
1872
1873 crate::profile::modlist::write(&source, &[profile_mod("Author-A", true)]).unwrap();
1874 write_test_file(&source.join("BepInEx/config/BepInEx.cfg"), b"shared");
1875 write_test_file(
1876 &source.join("BepInEx/plugins/Author-A/settings.cfg"),
1877 b"mine",
1878 );
1879
1880 let zip_bytes = build_r2z_in(&source, "MyProfile").unwrap();
1881 let written = extract_configs_in(&target, &zip_bytes).unwrap();
1882
1883 assert!(target.join("BepInEx/config/BepInEx.cfg").exists());
1884 assert!(
1885 target
1886 .join("BepInEx/plugins/Author-A/settings.cfg")
1887 .exists()
1888 );
1889 assert!(!target.join("export.r2x").exists());
1891 assert_eq!(written.len(), 2);
1892 }
1893
1894 #[test]
1895 fn extract_configs_treats_non_zip_input_as_no_configs() {
1896 let dir = tempfile::tempdir().unwrap();
1897 let target = dir.path().join("target");
1898
1899 let yaml = export_r2x_to_string(&export_format_from_mods("Bare", &[])).unwrap();
1901
1902 let written = extract_configs_in(&target, yaml.as_bytes()).unwrap();
1903
1904 assert!(written.is_empty());
1905 }
1906
1907 #[test]
1908 fn extract_configs_still_rejects_a_genuinely_corrupt_zip() {
1909 let dir = tempfile::tempdir().unwrap();
1910 let target = dir.path().join("target");
1911
1912 let corrupt = b"PK\x03\x04not a real zip".to_vec();
1914
1915 assert!(extract_configs_in(&target, &corrupt).is_err());
1916 }
1917
1918 #[test]
1919 #[cfg(unix)]
1920 fn extract_configs_refuses_to_write_through_a_symlink() {
1921 use std::os::unix::fs::symlink;
1922
1923 let outside = tempfile::tempdir().unwrap();
1924 let secret = outside.path().join("secret.cfg");
1925 std::fs::write(&secret, b"original").unwrap();
1926
1927 let source = tempfile::tempdir().unwrap();
1928
1929 crate::profile::modlist::write(source.path(), &[profile_mod("Author-A", true)]).unwrap();
1930 write_test_file(
1931 &source.path().join("BepInEx/config/BepInEx.cfg"),
1932 b"new-content",
1933 );
1934
1935 let zip_bytes = build_r2z_in(source.path(), "MyProfile").unwrap();
1936
1937 let target = tempfile::tempdir().unwrap();
1940 let dest = target.path().join("BepInEx/config/BepInEx.cfg");
1941
1942 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
1943 symlink(&secret, &dest).unwrap();
1944
1945 let err = extract_configs_in(target.path(), &zip_bytes).unwrap_err();
1946
1947 assert!(matches!(err, Error::Profile(_)));
1948 assert_eq!(std::fs::read_to_string(&secret).unwrap(), "original");
1950 }
1951
1952 fn zip_with_one_zero_filled_entry(name: &str, inflated_len: usize) -> Vec<u8> {
1955 let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
1956 let options: FileOptions<'_, ()> =
1957 FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
1958
1959 zip.start_file(name, options).unwrap();
1960 zip.write_all(&vec![0u8; inflated_len]).unwrap();
1961
1962 zip.finish().unwrap().into_inner()
1963 }
1964
1965 #[test]
1966 fn extract_configs_rejects_entry_exceeding_the_per_entry_cap() {
1967 let bytes = zip_with_one_zero_filled_entry(
1968 "BepInEx/config/Big.cfg",
1969 (MAX_IMPORT_ENTRY_BYTES + 1) as usize,
1970 );
1971
1972 let dir = tempfile::tempdir().unwrap();
1973 let err = extract_configs_in(dir.path(), &bytes).unwrap_err();
1974
1975 assert!(matches!(err, Error::ExtractLimitExceeded(_)));
1976 }
1977
1978 #[test]
1979 fn extract_configs_rejects_import_exceeding_the_cumulative_cap() {
1980 let per_entry_len = (MAX_IMPORT_ENTRY_BYTES - 1024) as usize;
1983 let entries_needed = (MAX_IMPORT_TOTAL_BYTES / per_entry_len as u64) + 1;
1984
1985 let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
1986 let options: FileOptions<'_, ()> =
1987 FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
1988 let chunk = vec![0u8; per_entry_len];
1989
1990 for i in 0..entries_needed {
1991 zip
1992 .start_file(format!("BepInEx/config/{i}.cfg"), options)
1993 .unwrap();
1994 zip.write_all(&chunk).unwrap();
1995 }
1996
1997 let bytes = zip.finish().unwrap().into_inner();
1998
1999 let dir = tempfile::tempdir().unwrap();
2000 let err = extract_configs_in(dir.path(), &bytes).unwrap_err();
2001
2002 assert!(matches!(err, Error::ExtractLimitExceeded(_)));
2003 }
2004
2005 #[test]
2006 fn import_r2modman_dir_adopts_an_existing_profile() {
2007 let dir = tempfile::tempdir().unwrap();
2008 let source = dir.path().join("source");
2009 let target = dir.path().join("target");
2010
2011 crate::profile::modlist::write(&source, &[profile_mod("Author-A", true)]).unwrap();
2012 write_test_file(&source.join("BepInEx/plugins/Author-A/Mod.dll"), b"dll");
2013
2014 import_r2modman_dir(&source, &target).unwrap();
2015
2016 assert!(target.join("BepInEx/plugins/Author-A/Mod.dll").exists());
2017 assert_eq!(crate::profile::modlist::read(&target).unwrap().len(), 1);
2018 assert!(import_r2modman_dir(&dir.path().join("missing"), &target).is_err());
2019 }
2020
2021 #[test]
2022 #[cfg(unix)]
2023 fn import_r2modman_dir_refuses_to_copy_through_a_symlink() {
2024 use std::os::unix::fs::symlink;
2025
2026 let outside = tempfile::tempdir().unwrap();
2027 let secret = outside.path().join("secret.cfg");
2028 std::fs::write(&secret, b"original").unwrap();
2029
2030 let dir = tempfile::tempdir().unwrap();
2031 let source = dir.path().join("source");
2032 let target = dir.path().join("target");
2033
2034 crate::profile::modlist::write(&source, &[profile_mod("Author-A", true)]).unwrap();
2035 write_test_file(
2036 &source.join("BepInEx/plugins/Author-A/settings.cfg"),
2037 b"new-content",
2038 );
2039
2040 let dest = target.join("BepInEx/plugins/Author-A/settings.cfg");
2042
2043 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
2044 symlink(&secret, &dest).unwrap();
2045
2046 let err = import_r2modman_dir(&source, &target).unwrap_err();
2047
2048 assert!(matches!(err, Error::Profile(_)));
2049 assert_eq!(std::fs::read_to_string(&secret).unwrap(), "original");
2051 }
2052
2053 #[test]
2054 fn copy_tree_skips_a_same_file_copy_instead_of_truncating_it() {
2055 let dir = tempfile::tempdir().unwrap();
2056 let root = dir.path();
2057
2058 write_test_file(&root.join("sub/file.txt"), b"original bytes");
2059
2060 copy_tree(root, root).unwrap();
2067
2068 let bytes = std::fs::read(root.join("sub/file.txt")).unwrap();
2069
2070 assert_eq!(
2071 bytes, b"original bytes",
2072 "a same-file copy must be skipped, not truncate the file to zero bytes"
2073 );
2074 }
2075}