diff --git a/src/instance/config_sync.rs b/src/instance/config_sync.rs index 996accc..e8755e3 100644 --- a/src/instance/config_sync.rs +++ b/src/instance/config_sync.rs @@ -436,7 +436,7 @@ fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { && (file_type.is_file() || file_type.is_symlink()) { if file_type.is_symlink() { - copy_link(&entry.path(), &staging.join(&name))?; + crate::storage::copy_symlink(&entry.path(), &staging.join(&name))?; } else { std::fs::copy(entry.path(), staging.join(&name))?; } @@ -446,7 +446,7 @@ fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { } for entry in std::fs::read_dir(&staging)? { let entry = entry?; - crate::storage::replace_file(&entry.path(), &dst.join(entry.file_name()))?; + std::fs::rename(entry.path(), dst.join(entry.file_name()))?; } remove_options(dst, &copied)?; Ok(()) @@ -506,29 +506,13 @@ fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { } else if file_type.is_file() { std::fs::copy(&source, &target)?; } else if file_type.is_symlink() { - copy_link(&source, &target)?; + crate::storage::copy_symlink(&source, &target)?; } } Ok(()) } -#[cfg(unix)] -fn copy_link(source: &Path, target: &Path) -> std::io::Result<()> { - std::os::unix::fs::symlink(std::fs::read_link(source)?, target) -} - -#[cfg(not(unix))] -fn copy_link(source: &Path, _target: &Path) -> std::io::Result<()> { - Err(std::io::Error::new( - std::io::ErrorKind::Unsupported, - format!( - "Cannot copy config symlink '{}' on this platform", - source.display() - ), - )) -} - #[cfg(test)] #[path = "tests/config_sync.rs"] mod tests; diff --git a/src/instance/import/archive.rs b/src/instance/import/archive.rs new file mode 100644 index 0000000..4f421bf --- /dev/null +++ b/src/instance/import/archive.rs @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use std::io::Read; +use std::path::{Path, PathBuf}; + +const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024; + +pub(super) fn read_pack_manifest(reader: impl Read) -> Result, String> { + let mut bytes = Vec::new(); + reader + .take(MAX_PACK_MANIFEST_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES { + return Err("Pack manifest exceeds 8 MiB".to_owned()); + } + Ok(bytes) +} + +fn relative_path( + entry: &zip::read::ZipFile<'_, std::fs::File>, + root: &str, +) -> Result, String> { + let root = root.trim_matches('/'); + if root.is_empty() || !entry.name().starts_with(&format!("{root}/")) { + return Ok(None); + } + let enclosed = entry + .enclosed_name() + .ok_or_else(|| format!("Unsafe override path: {}", entry.name()))?; + let relative = enclosed + .strip_prefix(root) + .map_err(|_| format!("Invalid override path: {}", entry.name()))?; + Ok(Some(relative.to_owned())) +} + +pub(super) fn override_files(path: &Path, roots: &[&str]) -> Result, String> { + let file = std::fs::File::open(path).map_err(|error| error.to_string())?; + let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?; + let mut files = Vec::new(); + for index in 0..archive.len() { + let entry = archive.by_index(index).map_err(|error| error.to_string())?; + if entry.is_dir() { + continue; + } + for root in roots { + if let Some(relative) = relative_path(&entry, root)? + && !relative.as_os_str().is_empty() + { + files.push(relative); + break; + } + } + } + Ok(files) +} + +pub(super) fn extract_overrides( + path: &Path, + destination: &Path, + roots: &[&str], +) -> Result<(), Box> { + let file = std::fs::File::open(path)?; + let mut archive = zip::ZipArchive::new(file)?; + // Later roots override earlier ones, independently of ZIP entry order. + for root in roots { + for index in 0..archive.len() { + let mut entry = archive.by_index(index)?; + let Some(relative) = relative_path(&entry, root)? else { + continue; + }; + let target = destination.join(relative); + if entry.is_dir() { + std::fs::create_dir_all(&target)?; + continue; + } + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent)?; + } + let mut file = std::fs::File::create(&target)?; + let size = std::io::copy(&mut entry, &mut file)?; + tracing::trace!( + "Extracted {} to {} ({} bytes)", + entry.name(), + target.display(), + size + ); + } + } + Ok(()) +} diff --git a/src/instance/import/curseforge.rs b/src/instance/import/curseforge.rs index 542dc88..29d1c50 100644 --- a/src/instance/import/curseforge.rs +++ b/src/instance/import/curseforge.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// curseforge modpack archives: manifest.json references provider file ids, -// while the overrides directory contains configs and other bundled files. - use std::path::Path; use serde::Deserialize; @@ -97,7 +94,7 @@ fn loader(manifest: &Manifest) -> (ModLoader, Option) { pub fn build_summary(path: &Path) -> Result { let manifest = parse(path)?; let (loader, loader_version) = loader(&manifest); - let override_count = count_overrides(path, &manifest.overrides)?; + let override_count = super::override_files(path, &[&manifest.overrides])?.len(); Ok(ImportSummary { name: manifest.name, pack_version: manifest.version, @@ -131,15 +128,18 @@ async fn download_files( manifest: &Manifest, minecraft_dir: &Path, ) -> Result<(), Box> { - let api_key = - crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?; - let client = crate::net::HttpClient::new(); let ids = manifest .files .iter() .filter(|file| file.required) .map(|file| file.file_id) .collect::>(); + if ids.is_empty() { + return Ok(()); + } + let api_key = + crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?; + let client = crate::net::HttpClient::new(); let versions = crate::net::curseforge::fetch_file_versions(&client, api_key, &ids).await?; if versions.len() != ids.len() { return Err(format!( @@ -218,53 +218,13 @@ pub(super) async fn owned_files(path: &Path) -> Result, Ok(files) } -fn count_overrides(path: &Path, root: &str) -> Result { - let root = root.trim_matches('/'); - if root.is_empty() { - return Ok(0); - } - let file = std::fs::File::open(path).map_err(|error| error.to_string())?; - let archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?; - let prefix = format!("{root}/"); - Ok(archive - .file_names() - .filter(|name| name.starts_with(&prefix) && !name.ends_with('/')) - .count()) -} - fn extract_overrides( path: &Path, minecraft_dir: &Path, root: &str, ) -> Result<(), Box> { progress::set_action("Extracting overrides..."); - let file = std::fs::File::open(path)?; - let mut archive = zip::ZipArchive::new(file)?; - let root = root.trim_matches('/'); - if root.is_empty() { - return Ok(()); - } - for index in 0..archive.len() { - let mut entry = archive.by_index(index)?; - let enclosed = entry.enclosed_name().ok_or("Unsafe override path")?; - let Ok(relative) = enclosed.strip_prefix(root) else { - continue; - }; - if relative.as_os_str().is_empty() { - continue; - } - let destination = minecraft_dir.join(relative); - if entry.is_dir() { - std::fs::create_dir_all(destination)?; - continue; - } - if let Some(parent) = destination.parent() { - std::fs::create_dir_all(parent)?; - } - let mut destination = std::fs::File::create(destination)?; - std::io::copy(&mut entry, &mut destination)?; - } - Ok(()) + super::archive::extract_overrides(path, minecraft_dir, &[root]) } #[cfg(test)] diff --git a/src/instance/import/mmc.rs b/src/instance/import/mmc.rs index b531a20..02a5253 100644 --- a/src/instance/import/mmc.rs +++ b/src/instance/import/mmc.rs @@ -233,12 +233,9 @@ fn instance_name_from_cfg(path: &Path) -> Option { } fn find_archive_prefix(archive: &zip::ZipArchive) -> String { - for name in archive.file_names() { - if name.ends_with("mmc-pack.json") { - return name.strip_suffix("mmc-pack.json").unwrap_or("").to_string(); - } - } - String::new() + find_entry(archive, "mmc-pack.json") + .and_then(|name| name.strip_suffix("mmc-pack.json").map(str::to_owned)) + .unwrap_or_default() } // looks for a file at root or one level deep (some archives nest everything diff --git a/src/instance/import/mod.rs b/src/instance/import/mod.rs index 830b5c8..0fa02a3 100644 --- a/src/instance/import/mod.rs +++ b/src/instance/import/mod.rs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only +mod archive; pub mod curseforge; pub mod mmc; pub mod mrpack; @@ -8,21 +9,7 @@ pub mod refresh; use std::path::{Path, PathBuf}; -const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024; - -fn read_pack_manifest(reader: impl std::io::Read) -> Result, String> { - use std::io::Read; - - let mut bytes = Vec::new(); - reader - .take(MAX_PACK_MANIFEST_BYTES + 1) - .read_to_end(&mut bytes) - .map_err(|error| error.to_string())?; - if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES { - return Err("Pack manifest exceeds 8 MiB".to_owned()); - } - Ok(bytes) -} +use archive::{override_files, read_pack_manifest}; use crate::instance::manager::InstanceManager; use crate::instance::models::ModLoader; @@ -152,7 +139,8 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String { tracing::trace!("Import instance name '{}' is available", candidate); return candidate; } - for n in 2..100 { + let mut n = 2; + loop { let candidate = format!("{base} ({n})"); if !instances_dir.join(&candidate).exists() { tracing::debug!( @@ -162,12 +150,8 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String { ); return candidate; } + n += 1; } - tracing::warn!( - "Import instance name '{}' had many collisions; using fallback suffix", - base - ); - format!("{base} (import)") } pub async fn execute_import( @@ -286,34 +270,6 @@ async fn owned_files(summary: &ImportSummary) -> Result, String> { } } -fn override_files(path: &Path, roots: &[&str]) -> Result, String> { - let file = std::fs::File::open(path).map_err(|error| error.to_string())?; - let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?; - let mut files = Vec::new(); - for index in 0..archive.len() { - let entry = archive.by_index(index).map_err(|error| error.to_string())?; - if entry.is_dir() { - continue; - } - let Some(root) = roots - .iter() - .find(|root| entry.name().starts_with(&format!("{root}/"))) - else { - continue; - }; - let relative = entry - .enclosed_name() - .ok_or_else(|| format!("Unsafe override path: {}", entry.name()))? - .strip_prefix(root) - .map_err(|error| error.to_string())? - .to_owned(); - if !relative.as_os_str().is_empty() { - files.push(relative); - } - } - Ok(files) -} - fn cleanup_failed_import(manager: &InstanceManager, name: &str) { let instance_dir = manager.instances_dir.join(name); if let Err(error) = std::fs::remove_dir_all(&instance_dir) diff --git a/src/instance/import/mrpack.rs b/src/instance/import/mrpack.rs index f0c0c85..e2e39f1 100644 --- a/src/instance/import/mrpack.rs +++ b/src/instance/import/mrpack.rs @@ -35,11 +35,23 @@ pub struct MrpackFile { pub path: String, #[serde(default)] pub hashes: HashMap, + #[serde(default)] + pub env: HashMap, pub downloads: Vec, #[serde(rename = "fileSize")] pub file_size: u64, } +impl MrpackIndex { + fn client_files(&self) -> impl Iterator { + self.files.iter().filter(|file| { + file.env + .get("client") + .is_none_or(|support| support != "unsupported") + }) + } +} + pub fn parse_mrpack(path: &Path) -> Result { tracing::debug!("Parsing .mrpack manifest from {}", path.display()); let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?; @@ -50,6 +62,12 @@ pub fn parse_mrpack(path: &Path) -> Result { let raw = super::read_pack_manifest(entry)?; let index: MrpackIndex = serde_json::from_slice(&raw).map_err(|e| format!("Invalid manifest JSON: {e}"))?; + if index.format_version != 1 || index.game != "minecraft" { + return Err(format!( + "Unsupported .mrpack format {} for game '{}'", + index.format_version, index.game + )); + } tracing::debug!( "Parsed .mrpack '{}' version_id={} files={} deps={}", index.name, @@ -104,7 +122,7 @@ pub fn build_summary(path: &Path) -> Result { let (loader_opt, loader_version) = loader_from_dependencies(&index.dependencies); let loader = loader_opt.unwrap_or(ModLoader::Vanilla); - let override_count = count_overrides(path).unwrap_or(0); + let override_count = super::override_files(path, &["overrides", "client-overrides"])?.len(); tracing::trace!( ".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}", game_version, @@ -119,7 +137,7 @@ pub fn build_summary(path: &Path) -> Result { game_version, loader, loader_version, - mod_count: index.files.len(), + mod_count: index.client_files().count(), override_count, format: PackFormat::Mrpack, archive_path: path.to_path_buf(), @@ -127,19 +145,6 @@ pub fn build_summary(path: &Path) -> Result { }) } -fn count_overrides(mrpack_path: &Path) -> Result { - let file = std::fs::File::open(mrpack_path).map_err(|e| e.to_string())?; - let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; - let count = archive - .file_names() - .filter(|name| { - (name.starts_with("overrides/") || name.starts_with("client-overrides/")) - && !name.ends_with('/') - }) - .count(); - Ok(count) -} - pub async fn execute_import( summary: &ImportSummary, manager: &InstanceManager, @@ -173,8 +178,6 @@ pub async fn execute_import( Ok(()) } -// downloads all mod files listed in the mrpack index, capped at 10 concurrent -// downloads to avoid getting rate-limited into oblivion async fn download_mod_files( index: &MrpackIndex, minecraft_dir: &Path, @@ -183,7 +186,7 @@ async fn download_mod_files( use std::sync::atomic::{AtomicUsize, Ordering}; let client = crate::net::HttpClient::new(); - let total = index.files.len(); + let total = index.client_files().count(); let completed = Arc::new(AtomicUsize::new(0)); tracing::debug!( "Downloading {} file(s) from .mrpack '{}' into {}", @@ -194,60 +197,14 @@ async fn download_mod_files( progress::set_action(format!("Downloading mods... 0/{total}")); - // bounded concurrency via manual JoinSet draining: seed with max_concurrent - // tasks, then spawn a new one each time one finishes let mut tasks = tokio::task::JoinSet::new(); - let max_concurrent = 10; - let mut file_iter = index.files.iter(); - for _ in 0..max_concurrent { - if let Some(file) = file_iter.next() { - let client = client.clone(); - let relative = safe_mrpack_path(&file.path)?; - let dest = minecraft_dir.join(relative); - let url = file.downloads.first().cloned().ok_or_else(|| { - crate::net::NetError::Parse(format!( - ".mrpack file '{}' has no download URL", - file.path - )) - })?; - let filename = file - .path - .rsplit('/') - .next() - .unwrap_or(&file.path) - .to_string(); - let hashes = file.hashes.clone(); - let file_size = file.file_size; - let completed = completed.clone(); - tasks.spawn(async move { - if let Some(parent) = dest.parent() - && let Err(error) = tokio::fs::create_dir_all(parent).await - { - return Err(crate::net::NetError::from(error)); - } - progress::set_sub_action(filename); - tracing::trace!("Downloading .mrpack file to {}", dest.display()); - crate::net::download_file(&client, &url, &dest, |_, _| {}).await?; - if !verify_mrpack_file(&dest, file_size, &hashes)? { - let _ = tokio::fs::remove_file(&dest).await; - return Err(crate::net::NetError::Parse(format!( - "Downloaded .mrpack file '{}' failed its size or hash verification", - dest.display() - ))); - } - let done = completed.fetch_add(1, Ordering::Relaxed) + 1; - progress::set_action(format!("Downloading mods... {done}/{total}")); - Ok::<(), crate::net::NetError>(()) - }); - } - } - - for file in file_iter { - if let Some(result) = tasks.join_next().await { - result - .map_err(|e| -> Box { Box::new(e) })? - .map_err(|e| -> Box { Box::new(e) })?; + for file in index.client_files() { + // Keep at most ten downloads in flight to avoid provider rate limits. + if tasks.len() == 10 + && let Some(result) = tasks.join_next().await + { + result??; } let client = client.clone(); let relative = safe_mrpack_path(&file.path)?; @@ -287,9 +244,7 @@ async fn download_mod_files( } while let Some(result) = tasks.join_next().await { - result - .map_err(|e| -> Box { Box::new(e) })? - .map_err(|e| -> Box { Box::new(e) })?; + result??; } Ok(()) @@ -297,11 +252,7 @@ async fn download_mod_files( fn safe_mrpack_path(path: &str) -> Result { let path = Path::new(path); - if path.as_os_str().is_empty() - || path - .components() - .any(|component| !matches!(component, std::path::Component::Normal(_))) - { + if !crate::storage::safe_relative_path(path) { return Err(crate::net::NetError::Parse(format!( "Unsafe .mrpack file path '{}'", path.display() @@ -311,9 +262,9 @@ fn safe_mrpack_path(path: &str) -> Result { } pub(super) fn owned_files(path: &Path) -> Result, String> { - let mut files: Vec<_> = parse_mrpack(path)? - .files - .into_iter() + let index = parse_mrpack(path)?; + let mut files: Vec<_> = index + .client_files() .map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string())) .collect::>()?; files.extend(super::override_files( @@ -346,7 +297,7 @@ fn seed_content_manifest( paths: &InstancePaths, ) -> Result<(), Box> { let mut manifest = ContentManifest::default(); - for file in &index.files { + for file in index.client_files() { let relative_path = Path::new(&file.path); let Some(kind) = mrpack_content_kind(relative_path) else { continue; @@ -429,65 +380,11 @@ fn extract_overrides( progress::set_action("Extracting overrides...".to_string()); progress::set_sub_action(String::new()); - let file = std::fs::File::open(mrpack_path)?; - let mut archive = zip::ZipArchive::new(file)?; - let mut extracted = 0usize; - let mut dirs = 0usize; - - for i in 0..archive.len() { - let mut entry = archive.by_index(i)?; - let entry_name = entry.name().to_string(); - - let root = if entry_name.starts_with("overrides/") { - "overrides" - } else if entry_name.starts_with("client-overrides/") { - "client-overrides" - } else { - continue; - }; - let enclosed = entry.enclosed_name().ok_or_else(|| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("Unsafe override path: {entry_name}"), - ) - })?; - let relative = enclosed.strip_prefix(root).map_err(|_| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("Invalid override path: {entry_name}"), - ) - })?; - - if relative.as_os_str().is_empty() || entry_name.ends_with('/') { - let dir = minecraft_dir.join(relative); - std::fs::create_dir_all(dir)?; - dirs += 1; - continue; - } - - let dest = minecraft_dir.join(relative); - if let Some(parent) = dest.parent() { - std::fs::create_dir_all(parent)?; - } - - let mut destination = std::fs::File::create(&dest)?; - let size = std::io::copy(&mut entry, &mut destination)?; - tracing::trace!( - "Extracting .mrpack override {} to {} ({} bytes)", - entry_name, - dest.display(), - size - ); - extracted += 1; - } - - tracing::debug!( - "Extracted {} override files and {} directories from {}", - extracted, - dirs, - mrpack_path.display() - ); - Ok(()) + super::archive::extract_overrides( + mrpack_path, + minecraft_dir, + &["overrides", "client-overrides"], + ) } #[cfg(test)] diff --git a/src/instance/import/refresh.rs b/src/instance/import/refresh.rs index 12aa6ba..7eaa110 100644 --- a/src/instance/import/refresh.rs +++ b/src/instance/import/refresh.rs @@ -75,7 +75,12 @@ pub async fn prepare( .map_err(|error| error.to_string())?; let live = manager.instances_dir.join(&instance.name); let needed = directory_size(&live) - .saturating_add(target.files.iter().map(|file| file.size).sum::()) + .saturating_add( + target + .files + .iter() + .fold(0u64, |size, file| size.saturating_add(file.size)), + ) .saturating_add(64 * 1024 * 1024); let available = fs2::available_space(&manager.instances_dir).map_err(|e| e.to_string())?; if available < needed { @@ -156,6 +161,9 @@ pub fn apply( plan: RefreshPlan, replace_conflicts: &HashSet, ) -> Result { + if crate::instance::runtime::is_active(&plan.instance.name) { + return Err("Stop the instance before changing its modpack".to_owned()); + } let live = plan .stage_root .parent() @@ -188,7 +196,13 @@ pub fn apply( } std::fs::rename(&live, &backup).map_err(|error| error.to_string())?; if let Err(error) = std::fs::rename(&plan.staged_instance, &live) { - let _ = std::fs::rename(&backup, &live); + if let Err(rollback) = std::fs::rename(&backup, &live) { + return Err(format!( + "Could not activate the staged update: {error}; could not restore '{}' from '{}': {rollback}", + live.display(), + backup.display() + )); + } return Err(format!("Could not activate the staged update: {error}")); } if let Err(error) = std::fs::remove_dir_all(&backup) { @@ -284,7 +298,7 @@ fn preserve_refresh_state( let path = &record.relative_path; if !old_owned.contains(path) && !(new_owned.contains(path) && replace_conflicts.contains(path)) - && old.minecraft().join(path).exists() + && std::fs::symlink_metadata(old.minecraft().join(path)).is_ok() { new_manifest.upsert(record.clone()); } @@ -292,7 +306,7 @@ fn preserve_refresh_state( for path in new_owned { if !replace_conflicts.contains(path) && !old_owned.contains(path) - && old.minecraft().join(path).exists() + && std::fs::symlink_metadata(old.minecraft().join(path)).is_ok() && old_manifest.record(path).is_none() { new_manifest.remove(path); @@ -300,7 +314,15 @@ fn preserve_refresh_state( } new_manifest .save(&new.content_manifest()) - .map_err(|e| e.to_string()) + .map_err(|e| e.to_string())?; + let mut state = PackState::load(&new) + .ok_or_else(|| "The staged pack did not record its owned files".to_owned())?; + state.files.retain(|path| { + old_owned.contains(path) + || replace_conflicts.contains(path) + || std::fs::symlink_metadata(old.minecraft().join(path)).is_err() + }); + state.save(&new) } fn preserve_user_files( @@ -332,17 +354,7 @@ fn preserve_user_files( } std::fs::remove_file(&target).map_err(|error| error.to_string())?; } - #[cfg(unix)] - std::os::unix::fs::symlink( - std::fs::read_link(&path).map_err(|error| error.to_string())?, - &target, - ) - .map_err(|error| error.to_string())?; - #[cfg(not(unix))] - return Err(format!( - "Cannot preserve symbolic link '{}' on this platform", - path.display() - )); + crate::storage::copy_symlink(&path, &target).map_err(|error| error.to_string())?; } else if metadata.is_dir() { let target = destination.join(entry.file_name()); std::fs::create_dir_all(&target).map_err(|error| error.to_string())?; @@ -387,9 +399,13 @@ fn collect_files( } fn directory_size(path: &Path) -> u64 { - let mut size = 0; + let mut size = 0u64; let _ = collect_files(path, path, &mut |_, file| { - size += file.metadata().map(|metadata| metadata.len()).unwrap_or(0); + size = size.saturating_add( + std::fs::symlink_metadata(file) + .map(|metadata| metadata.len()) + .unwrap_or(0), + ); Ok(()) }); size @@ -409,6 +425,50 @@ mod tests { use crate::instance::content::manifest::{ContentFileRecord, ContentKind, FileFingerprint}; + #[test] + fn refresh_rechecks_whether_the_instance_started_after_preparation() { + let temp = tempfile::tempdir().unwrap(); + let name = "refresh-became-active"; + let stage_root = temp.path().join(".rmcl-refresh-test"); + let live = temp.path().join(name); + let staged_instance = stage_root.join(name); + std::fs::create_dir_all(live.join("minecraft")).unwrap(); + std::fs::create_dir_all(staged_instance.join("minecraft")).unwrap(); + let instance = serde_json::from_value(serde_json::json!({ + "name": name, "game_version": "1.21", "loader": "vanilla", + "loader_version": null, "created": "2026-01-01T00:00:00Z" + })) + .unwrap(); + let plan = RefreshPlan { + instance, + summary: ImportSummary { + name: name.to_owned(), + pack_version: "2".to_owned(), + game_version: "1.21".to_owned(), + loader: crate::instance::ModLoader::Vanilla, + loader_version: None, + mod_count: 0, + override_count: 0, + format: super::super::PackFormat::Mrpack, + archive_path: stage_root.join("pack.mrpack"), + source: None, + }, + current_version: "1".to_owned(), + target_version: "2".to_owned(), + conflicts: Vec::new(), + stage_root, + staged_instance, + old_owned: HashSet::new(), + new_owned: HashSet::new(), + }; + crate::instance::runtime::set_state(name, crate::instance::runtime::RunState::Running); + let result = apply(plan, &HashSet::new()); + crate::instance::runtime::remove(name); + + assert!(result.unwrap_err().contains("Stop the instance")); + assert!(live.join("minecraft").is_dir()); + } + fn record(path: &str) -> ContentFileRecord { ContentFileRecord { relative_path: path.into(), @@ -446,6 +506,20 @@ mod tests { let mut staged = ContentManifest::default(); staged.upsert(record("mods/pack.jar")); staged.save(&new.content_manifest()).unwrap(); + PackState { + source: ProviderProject { + provider: "modrinth".to_owned(), + project_id: "pack".to_owned(), + version_id: "2".to_owned(), + }, + files: vec![ + "mods/pack.jar".into(), + "mods/user.jar".into(), + "mods/replace.jar".into(), + ], + } + .save(&new) + .unwrap(); preserve_refresh_state( old.root(), @@ -453,6 +527,7 @@ mod tests { &HashSet::new(), &HashSet::from([ PathBuf::from("mods/pack.jar"), + PathBuf::from("mods/user.jar"), PathBuf::from("mods/replace.jar"), ]), &HashSet::from([PathBuf::from("mods/replace.jar")]), @@ -467,6 +542,13 @@ mod tests { assert!(manifest.record(Path::new("mods/user.jar")).is_some()); assert!(manifest.record(Path::new("mods/pack.jar")).is_some()); assert!(manifest.record(Path::new("mods/replace.jar")).is_none()); + assert_eq!( + PackState::load(&new).unwrap().files, + vec![ + PathBuf::from("mods/pack.jar"), + PathBuf::from("mods/replace.jar") + ] + ); } #[cfg(unix)] diff --git a/src/instance/tests/import/curseforge.rs b/src/instance/tests/import/curseforge.rs index 6804df6..3845496 100644 --- a/src/instance/tests/import/curseforge.rs +++ b/src/instance/tests/import/curseforge.rs @@ -87,4 +87,7 @@ async fn override_only_pack_tracks_files_under_its_configured_root() { owned_files(&path).await.unwrap(), vec![std::path::PathBuf::from("config/pack.toml")] ); + download_files(&parse(&path).unwrap(), &temp.path().join("minecraft")) + .await + .unwrap(); } diff --git a/src/instance/tests/import/format_detection.rs b/src/instance/tests/import/format_detection.rs index c2d7ad3..6354be3 100644 --- a/src/instance/tests/import/format_detection.rs +++ b/src/instance/tests/import/format_detection.rs @@ -36,8 +36,6 @@ fn detect_format_recognises_mrpack() { #[test] fn detect_format_recognises_mmc_flat() { - // mmc-pack.json at the zip root - the flat layout that some mmc - // archives use. let tmp = tempfile::tempdir().unwrap(); let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]); assert_eq!(detect_format(&path), Ok(PackFormat::Mmc)); @@ -45,8 +43,6 @@ fn detect_format_recognises_mmc_flat() { #[test] fn detect_format_recognises_mmc_nested() { - // mmc-pack.json one directory deep - the more common layout where - // the archive wraps everything in a named directory. let tmp = tempfile::tempdir().unwrap(); let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]); assert_eq!(detect_format(&path), Ok(PackFormat::Mmc)); @@ -54,8 +50,6 @@ fn detect_format_recognises_mmc_nested() { #[test] fn detect_format_prefers_mrpack_when_both_markers_present() { - // a zip with both markers should resolve to Mrpack since the - // detector checks modrinth.index.json first. let tmp = tempfile::tempdir().unwrap(); let path = make_pack_zip( tmp.path(), @@ -121,6 +115,17 @@ fn unique_name_multiple_collisions() { assert_eq!(name, "TestPack (4)"); } +#[test] +fn unique_name_keeps_searching_after_ninety_nine_collisions() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::create_dir(tmp.path().join("Pack")).unwrap(); + for suffix in 2..=100 { + std::fs::create_dir(tmp.path().join(format!("Pack ({suffix})"))).unwrap(); + } + std::fs::create_dir(tmp.path().join("Pack (import)")).unwrap(); + assert_eq!(unique_instance_name("Pack", tmp.path()), "Pack (101)"); +} + #[test] fn parse_project_url() { assert_eq!( diff --git a/src/instance/tests/import/mmc.rs b/src/instance/tests/import/mmc.rs index ebe206a..6460c62 100644 --- a/src/instance/tests/import/mmc.rs +++ b/src/instance/tests/import/mmc.rs @@ -3,6 +3,32 @@ use super::*; +#[test] +fn minecraft_prefix_comes_from_the_manifest_used_for_import() { + use std::io::Write; + + let tmp = tempfile::tempdir().unwrap(); + let archive_path = tmp.path().join("pack.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&archive_path).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + zip.start_file("Decoy/mmc-pack.json", options).unwrap(); + zip.write_all(b"{}").unwrap(); + zip.start_file("mmc-pack.json", options).unwrap(); + zip.write_all(br#"{"components":[{"uid":"net.minecraft","version":"1.21"}]}"#) + .unwrap(); + zip.start_file(".minecraft/options.txt", options).unwrap(); + zip.write_all(b"correct").unwrap(); + zip.finish().unwrap(); + + let destination = tmp.path().join("minecraft"); + assert_eq!(build_summary(&archive_path).unwrap().override_count, 1); + extract_mmc_archive(&archive_path, &destination).unwrap(); + assert_eq!( + std::fs::read(destination.join("options.txt")).unwrap(), + b"correct" + ); +} + #[test] fn parse_mmc_pack_json() { let json = r#"{ diff --git a/src/instance/tests/import/mrpack.rs b/src/instance/tests/import/mrpack.rs index 9932ce2..e0553ff 100644 --- a/src/instance/tests/import/mrpack.rs +++ b/src/instance/tests/import/mrpack.rs @@ -108,6 +108,7 @@ fn extraction_merges_both_override_roots() { &[ ("overrides/config/test.toml", b"config"), ("client-overrides/options.txt", b"options"), + ("overrides/options.txt", b"generic"), ], ); let minecraft = tmp.path().join("minecraft"); @@ -124,6 +125,63 @@ fn extraction_merges_both_override_roots() { ); } +#[test] +fn server_only_files_are_excluded_from_client_imports() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("server-only.mrpack"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap()); + zip.start_file( + "modrinth.index.json", + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + zip.write_all(br#"{ + "formatVersion": 1, "game": "minecraft", "versionId": "1", "name": "Pack", + "dependencies": {"minecraft": "1.21"}, + "files": [ + {"path": "mods/server.jar", "env": {"client": "unsupported"}, "downloads": [], "fileSize": 0}, + {"path": "mods/client.jar", "downloads": [], "fileSize": 0} + ] + }"#).unwrap(); + zip.finish().unwrap(); + + assert_eq!(build_summary(&path).unwrap().mod_count, 1); + assert_eq!( + owned_files(&path).unwrap(), + vec![PathBuf::from("mods/client.jar")] + ); +} + +#[test] +fn unsupported_pack_format_or_game_is_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("unsupported.mrpack"); + for (from, to) in [ + ("\"formatVersion\": 1", "\"formatVersion\": 2"), + ("\"game\": \"minecraft\"", "\"game\": \"other\""), + ] { + let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap()); + zip.start_file( + "modrinth.index.json", + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + zip.write_all( + std::str::from_utf8(INDEX) + .unwrap() + .replace(from, to) + .as_bytes(), + ) + .unwrap(); + zip.finish().unwrap(); + assert!( + parse_mrpack(&path) + .unwrap_err() + .contains("Unsupported .mrpack") + ); + } +} + #[test] fn extraction_rejects_path_traversal() { let tmp = tempfile::tempdir().unwrap(); @@ -150,7 +208,7 @@ fn mod_files_download_to_their_manifest_paths() { Mock::given(method("GET")) .and(path("/first.jar")) .respond_with(ResponseTemplate::new(200).set_body_bytes(b"first".to_vec())) - .expect(1) + .expect(11) .mount(&server) .await; Mock::given(method("GET")) @@ -159,7 +217,7 @@ fn mod_files_download_to_their_manifest_paths() { .expect(1) .mount(&server) .await; - let index = MrpackIndex { + let mut index = MrpackIndex { format_version: 1, game: "minecraft".to_owned(), version_id: "1".to_owned(), @@ -168,18 +226,27 @@ fn mod_files_download_to_their_manifest_paths() { files: vec![ MrpackFile { path: "mods/first.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: vec![format!("{}/first.jar", server.uri())], file_size: 5, }, MrpackFile { path: "resourcepacks/second.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: vec![format!("{}/second.jar", server.uri())], file_size: 6, }, ], }; + index.files.extend((2..12).map(|number| MrpackFile { + path: format!("mods/extra-{number}.jar"), + env: Default::default(), + hashes: Default::default(), + downloads: vec![format!("{}/first.jar", server.uri())], + file_size: 5, + })); let tmp = tempfile::tempdir().unwrap(); download_mod_files(&index, tmp.path()).await.unwrap(); @@ -192,6 +259,12 @@ fn mod_files_download_to_their_manifest_paths() { std::fs::read(tmp.path().join("resourcepacks/second.jar")).unwrap(), b"second" ); + for number in 2..12 { + assert_eq!( + std::fs::read(tmp.path().join(format!("mods/extra-{number}.jar"))).unwrap(), + b"first" + ); + } crate::feedback::progress::clear(); }); } @@ -206,7 +279,7 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() { .build() .unwrap(); runtime.block_on(async { - let index = MrpackIndex { + let mut index = MrpackIndex { format_version: 1, game: "minecraft".to_owned(), version_id: "1".to_owned(), @@ -214,6 +287,7 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() { dependencies: Default::default(), files: vec![MrpackFile { path: "mods/missing.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: Vec::new(), file_size: 0, @@ -223,6 +297,11 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() { assert!(download_mod_files(&index, tmp.path()).await.is_err()); assert!(!tmp.path().join("mods/missing.jar").exists()); + index.files[0] + .env + .insert("client".to_owned(), "unsupported".to_owned()); + download_mod_files(&index, tmp.path()).await.unwrap(); + assert!(!tmp.path().join("mods/missing.jar").exists()); crate::feedback::progress::clear(); }); } @@ -247,6 +326,7 @@ fn mod_file_rejects_paths_outside_the_instance() { dependencies: Default::default(), files: vec![MrpackFile { path: "../escape.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: vec!["https://example.invalid/escape.jar".to_owned()], file_size: 1, @@ -286,6 +366,7 @@ fn mod_file_removes_downloads_with_invalid_metadata() { dependencies: Default::default(), files: vec![MrpackFile { path: "mods/corrupt.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: vec![format!("{}/corrupt.jar", server.uri())], file_size: 1, @@ -320,6 +401,7 @@ fn import_seeds_exact_modrinth_content_identity() { dependencies: Default::default(), files: vec![MrpackFile { path: relative_path.to_string_lossy().into_owned(), + env: Default::default(), hashes: HashMap::from([("sha512".to_owned(), sha512)]), downloads: vec![ "https://cdn.modrinth.com/data/project/versions/version/example.zip".to_owned(), diff --git a/src/layout_migration.rs b/src/layout_migration.rs index 05b9e1a..2027de7 100644 --- a/src/layout_migration.rs +++ b/src/layout_migration.rs @@ -136,6 +136,7 @@ pub fn run( let metadata = MetadataPaths::new(meta_dir); if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION) && metadata.cache_rebuild_pending().exists() + && !metadata.migration_journal().exists() && !has_legacy_instances(instances_dir) && !has_legacy_shared_data(meta_dir) { @@ -150,7 +151,7 @@ pub fn run( fs::create_dir_all(metadata.state())?; fs::write(metadata.cache_rebuild_pending(), LAYOUT_VERSION.to_string())?; - let mut journal = load_or_create_journal(instances_dir, &metadata)?; + let mut journal = load_or_create_journal(&metadata)?; let instances = instance_directories(instances_dir)?; let total = instances.len() as u64 + 8; let mut current = journal.completed.len() as u64; @@ -554,7 +555,7 @@ fn copy_dir_recursive_with_progress( let file_type = entry.file_type()?; let target = destination.join(entry.file_name()); if file_type.is_symlink() { - copy_symlink(&entry.path(), &target)?; + crate::storage::copy_symlink(&entry.path(), &target)?; } else if file_type.is_dir() { copy_dir_recursive_with_progress(&entry.path(), &target, report)?; } else { @@ -566,25 +567,7 @@ fn copy_dir_recursive_with_progress( Ok(()) } -#[cfg(unix)] -fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> { - std::os::unix::fs::symlink(fs::read_link(source)?, destination) -} - -#[cfg(windows)] -fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> { - let target = fs::read_link(source)?; - if source.is_dir() { - std::os::windows::fs::symlink_dir(target, destination) - } else { - std::os::windows::fs::symlink_file(target, destination) - } -} - -fn load_or_create_journal( - _instances_dir: &Path, - metadata: &MetadataPaths, -) -> Result { +fn load_or_create_journal(metadata: &MetadataPaths) -> Result { let legacy_journal = metadata.state().join("migration-v2.json"); if metadata.migration_journal().exists() { return Ok(serde_json::from_slice(&fs::read( @@ -597,7 +580,7 @@ fn load_or_create_journal( fs::remove_file(legacy_journal)?; return Ok(journal); } - let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string(); + let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S-%f").to_string(); let journal = MigrationJournal { version: LAYOUT_VERSION, backup_dir: metadata.backups().join(format!("backup-{timestamp}")), diff --git a/src/migrate.rs b/src/migrate.rs index 8098e5d..fc85b77 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -93,7 +93,9 @@ fn copy_dir_recursive(src: &Path, dst: &Path) -> io::Result<()> { let entry = entry?; let ty = entry.file_type()?; let dst_path = dst.join(entry.file_name()); - if ty.is_dir() { + if ty.is_symlink() { + crate::storage::copy_symlink(&entry.path(), &dst_path)?; + } else if ty.is_dir() { copy_dir_recursive(&entry.path(), &dst_path)?; } else { fs::copy(entry.path(), &dst_path)?; diff --git a/src/net/mod.rs b/src/net/mod.rs index 67ba14b..4f4546b 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -333,7 +333,7 @@ async fn download_file_once( } file.flush().await?; drop(file); - crate::storage::replace_file(&temporary, dest)?; + tokio::fs::rename(&temporary, dest).await?; Ok(()) } .await; diff --git a/src/storage.rs b/src/storage.rs index a9e7b64..83c67f2 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -3,9 +3,10 @@ use std::io; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -static TEMP_FILE_ID: AtomicU64 = AtomicU64::new(1); +mod filesystem; +pub(crate) use filesystem::copy_symlink; +pub use filesystem::{write_atomic, write_atomic_private}; pub const MINECRAFT_DIR_NAME: &str = "minecraft"; pub const INSTANCE_STATE_DIR_NAME: &str = "rmcl"; @@ -161,68 +162,6 @@ pub fn safe_relative_path(path: &Path) -> bool { && components.all(|part| matches!(part, std::path::Component::Normal(_))) } -pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { - write_atomic_with_mode(path, bytes, false) -} - -pub fn write_atomic_private(path: &Path, bytes: &[u8]) -> io::Result<()> { - write_atomic_with_mode(path, bytes, true) -} - -fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> { - let parent = path - .parent() - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; - std::fs::create_dir_all(parent)?; - let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed); - let name = path - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or("data"); - let temporary = parent.join(format!(".{name}.{}.{}.tmp", std::process::id(), id)); - let result = (|| { - use std::io::Write; - - let mut options = std::fs::OpenOptions::new(); - options.create_new(true).write(true); - #[cfg(unix)] - if private { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - #[cfg(not(unix))] - let _ = private; - let mut file = options.open(&temporary)?; - file.write_all(bytes)?; - file.sync_all()?; - replace_file(&temporary, path) - })(); - if result.is_err() { - let _ = std::fs::remove_file(&temporary); - } - result -} - -#[cfg(not(windows))] -pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { - std::fs::rename(source, destination) -} - -#[cfg(windows)] -pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { - if !destination.exists() { - return std::fs::rename(source, destination); - } - let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed); - let backup = destination.with_extension(format!("rmcl-replaced-{id}")); - std::fs::rename(destination, &backup)?; - if let Err(error) = std::fs::rename(source, destination) { - let _ = std::fs::rename(&backup, destination); - return Err(error); - } - std::fs::remove_file(backup) -} - #[cfg(test)] #[path = "tests/storage.rs"] mod tests; diff --git a/src/storage/filesystem.rs b/src/storage/filesystem.rs new file mode 100644 index 0000000..80ad07d --- /dev/null +++ b/src/storage/filesystem.rs @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use std::io; +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; + +static TEMP_FILE_ID: AtomicU64 = AtomicU64::new(1); + +pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + write_atomic_with_mode(path, bytes, false) +} + +pub fn write_atomic_private(path: &Path, bytes: &[u8]) -> io::Result<()> { + write_atomic_with_mode(path, bytes, true) +} + +fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> { + let parent = path + .parent() + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + std::fs::create_dir_all(parent)?; + let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed); + let name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("data"); + let temporary = parent.join(format!(".{name}.{}.{}.tmp", std::process::id(), id)); + let result = (|| { + use std::io::Write; + + let mut options = std::fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(unix)] + if private { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + #[cfg(not(unix))] + let _ = private; + let mut file = options.open(&temporary)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + std::fs::rename(&temporary, path) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&temporary); + } + result +} + +#[cfg(unix)] +pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> { + std::os::unix::fs::symlink(std::fs::read_link(source)?, destination) +} + +#[cfg(windows)] +pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> { + let target = std::fs::read_link(source)?; + if source.is_dir() { + std::os::windows::fs::symlink_dir(target, destination) + } else { + std::os::windows::fs::symlink_file(target, destination) + } +} diff --git a/src/tests/layout_migration.rs b/src/tests/layout_migration.rs index 44e0a96..1de38cc 100644 --- a/src/tests/layout_migration.rs +++ b/src/tests/layout_migration.rs @@ -49,6 +49,44 @@ fn migrated_layout_detects_newly_copied_shared_data() { ); } +#[test] +fn incomplete_migration_is_not_skipped_after_legacy_directories_were_renamed() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + let config = temp.path().join("config.toml"); + let state = instances.join("Copied/.rmcl"); + fs::create_dir_all(state.join("config-sync/local-config")).unwrap(); + fs::create_dir_all(state.join("content/config")).unwrap(); + fs::write(state.join("config-sync/local-config/options.txt"), b"old").unwrap(); + fs::write(state.join("content/config/options.txt"), b"current").unwrap(); + initialize_new_layout(&meta).unwrap(); + + assert!(run(&instances, &meta, &config, |_| {}).is_err()); + assert!(!state.exists()); + assert!(MetadataPaths::new(&meta).migration_journal().exists()); + assert!(run(&instances, &meta, &config, |_| {}).is_err()); + assert_eq!( + fs::read(instances.join("Copied/rmcl/content/config/options.txt")).unwrap(), + b"current" + ); +} + +#[test] +fn repeated_migrations_create_separate_backups() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + let config = temp.path().join("config.toml"); + fs::create_dir_all(instances.join("First/.minecraft")).unwrap(); + let first = run(&instances, &meta, &config, |_| {}).unwrap(); + fs::create_dir_all(instances.join("Second/.minecraft")).unwrap(); + let second = run(&instances, &meta, &config, |_| {}).unwrap(); + + assert_ne!(first, second); + assert!(second.join("instances/Second/.minecraft").is_dir()); +} + #[test] fn migration_backs_up_and_renames_instance_directories() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/tests/migrate.rs b/src/tests/migrate.rs index a09c481..1294a38 100644 --- a/src/tests/migrate.rs +++ b/src/tests/migrate.rs @@ -123,3 +123,25 @@ fn copy_dir_recursive_copies_nested_tree() { b"inner" ); } + +#[cfg(unix)] +#[test] +fn cross_device_copy_preserves_links_without_following_directory_cycles() { + let tmp = tempfile::tempdir().unwrap(); + let source = tmp.path().join("old"); + let destination = tmp.path().join("new"); + fs::create_dir(&source).unwrap(); + fs::write(source.join("data.txt"), b"data").unwrap(); + std::os::unix::fs::symlink("data.txt", source.join("linked.txt")).unwrap(); + std::os::unix::fs::symlink(".", source.join("cycle")).unwrap(); + + copy_dir_recursive(&source, &destination).unwrap(); + assert_eq!( + fs::read_link(destination.join("linked.txt")).unwrap(), + Path::new("data.txt") + ); + assert_eq!( + fs::read_link(destination.join("cycle")).unwrap(), + Path::new(".") + ); +} diff --git a/src/tests/storage.rs b/src/tests/storage.rs index 9d06657..f8f751e 100644 --- a/src/tests/storage.rs +++ b/src/tests/storage.rs @@ -68,3 +68,15 @@ fn atomic_write_replaces_existing_file() { write_atomic(&path, b"new").unwrap(); assert_eq!(std::fs::read(path).unwrap(), b"new"); } + +#[test] +fn failed_atomic_replacement_keeps_the_destination_and_removes_staging() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("state.json"); + std::fs::create_dir(&path).unwrap(); + std::fs::write(path.join("keep"), b"old").unwrap(); + + assert!(write_atomic(&path, b"new").is_err()); + assert_eq!(std::fs::read(path.join("keep")).unwrap(), b"old"); + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1); +}