From 0d1cafcb1096daa015be0249d1179878ec3f3934 Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 17:44:34 +0200 Subject: [PATCH] fix: preserve instance state through launches and updates --- src/instance/config_sync.rs | 158 +++++++++++++++--- src/instance/content/dependencies.rs | 4 +- src/instance/content/reconcile.rs | 20 ++- src/instance/desktop.rs | 66 +++++++- src/instance/import/refresh.rs | 184 ++++++++++++++++++++- src/instance/launch/mod.rs | 39 +---- src/instance/manager.rs | 26 ++- src/instance/tests/config_sync.rs | 135 +++++++++++++++ src/instance/tests/content/dependencies.rs | 50 ++++++ src/instance/tests/content/reconcile.rs | 15 ++ src/instance/tests/desktop.rs | 17 ++ src/instance/tests/manager.rs | 39 +++++ src/layout_migration.rs | 33 ++-- src/tests/layout_migration.rs | 49 ++++++ 14 files changed, 741 insertions(+), 94 deletions(-) diff --git a/src/instance/config_sync.rs b/src/instance/config_sync.rs index a563eb7..996accc 100644 --- a/src/instance/config_sync.rs +++ b/src/instance/config_sync.rs @@ -11,6 +11,8 @@ pub enum ConfigSyncError { InvalidProfile(String), #[error("Cannot switch config profiles while '{instance}' is running")] InstanceRunning { instance: String }, + #[error("Config profile '{0}' is in use by another instance")] + ProfileInUse(String), #[error("IO error: {0}")] Io(#[from] std::io::Error), #[error("Failed to save config profile: {0}")] @@ -22,6 +24,7 @@ pub enum ConfigSyncError { #[derive(Debug)] pub struct ConfigSyncLock { file: std::fs::File, + profile_dir: PathBuf, } impl Drop for ConfigSyncLock { @@ -37,16 +40,24 @@ pub fn prepare( meta_dir: &Path, minecraft_dir: &Path, ) -> Result { + Ok(prepare_for_launch(profile, meta_dir, minecraft_dir)?.is_some()) +} + +pub fn prepare_for_launch( + profile: Option<&str>, + meta_dir: &Path, + minecraft_dir: &Path, +) -> Result, ConfigSyncError> { let Some(profile) = profile.and_then(normalize_profile) else { - return Ok(false); + return Ok(None); }; validate_profile(profile)?; let profile_dir = profile_dir(meta_dir, profile); if !profile_dir.exists() { - return Ok(false); + return Ok(None); } - let _lock = acquire_lock(&profile_dir)?; + let lock = acquire_lock(&profile_dir)?; if !profile_payload_exists(&profile_dir)? { sync_to_profile(minecraft_dir, &profile_dir)?; @@ -54,7 +65,11 @@ pub fn prepare( sync_from_profile(&profile_dir, minecraft_dir)?; } - Ok(true) + Ok(Some(lock)) +} + +pub fn finish_launch(lock: ConfigSyncLock, minecraft_dir: &Path) -> Result<(), ConfigSyncError> { + sync_to_profile(minecraft_dir, &lock.profile_dir) } pub fn finish( @@ -105,6 +120,7 @@ pub fn delete_profile(meta_dir: &Path, profile: &str) -> Result<(), ConfigSyncEr validate_profile(profile)?; let dir = profile_dir(meta_dir, profile); if dir.exists() { + let _lock = acquire_lock(&dir)?; remove_path(&dir)?; } Ok(()) @@ -291,14 +307,26 @@ fn acquire_lock(profile_dir: &Path) -> Result { .create(true) .truncate(false) .open(path)?; - file.lock()?; - Ok(ConfigSyncLock { file }) + match file.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => { + return Err(ConfigSyncError::ProfileInUse( + profile_dir + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(), + )); + } + Err(std::fs::TryLockError::Error(error)) => return Err(error.into()), + } + Ok(ConfigSyncLock { + file, + profile_dir: profile_dir.to_owned(), + }) } fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { - // stage the copy in a sibling temp dir and swap it in only when complete. - // deleting dst up-front (the old behaviour) meant a failure mid-copy - // destroyed the current config tree with nothing to fall back to. let parent = dst.parent().filter(|p| !p.as_os_str().is_empty()); let Some(parent) = parent else { return Err(std::io::Error::new( @@ -310,6 +338,21 @@ fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { std::fs::create_dir_all(parent)?; let name = dst.file_name().and_then(|s| s.to_str()).unwrap_or("mirror"); let staging = parent.join(format!(".{name}.mirror-tmp")); + let backup = parent.join(format!(".{name}.mirror-backup")); + if std::fs::symlink_metadata(dst).is_ok_and(|meta| meta.file_type().is_symlink()) { + return Err(std::io::Error::other(format!( + "Cannot replace symlinked config directory '{}'", + dst.display() + )) + .into()); + } + if backup.exists() { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + format!("Previous config backup remains at {}", backup.display()), + ) + .into()); + } if staging.exists() { remove_path(&staging)?; } @@ -319,10 +362,25 @@ fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { if src.exists() { copy_dir_contents(src, &staging)?; } - if dst.exists() { - remove_path(dst)?; + let had_dst = dst.exists(); + if had_dst { + std::fs::rename(dst, &backup)?; + } + if let Err(error) = std::fs::rename(&staging, dst) { + if had_dst && let Err(rollback) = std::fs::rename(&backup, dst) { + return Err(ConfigSyncError::SaveRollback { + save: error.to_string(), + rollback: rollback.to_string(), + }); + } + return Err(error.into()); + } + if had_dst && let Err(error) = remove_path(&backup) { + tracing::warn!( + "Could not remove old config backup '{}': {error}", + backup.display() + ); } - std::fs::rename(&staging, dst)?; Ok(()) })(); @@ -351,7 +409,9 @@ fn profile_payload_exists(profile_dir: &Path) -> Result { } for entry in std::fs::read_dir(profile_dir)? { let entry = entry?; - if entry.file_type()?.is_file() && is_options_file(&entry.file_name().to_string_lossy()) { + if (entry.file_type()?.is_file() || entry.file_type()?.is_symlink()) + && is_options_file(&entry.file_name().to_string_lossy()) + { return Ok(true); } } @@ -359,30 +419,60 @@ fn profile_payload_exists(profile_dir: &Path) -> Result { } fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { - remove_options(dst)?; std::fs::create_dir_all(dst)?; - if !src.exists() { - return Ok(()); + let staging = dst.join(".rmcl-options-stage"); + if staging.exists() { + remove_path(&staging)?; } - - for entry in std::fs::read_dir(src)? { - let entry = entry?; - let name = entry.file_name(); - if entry.file_type()?.is_file() && is_options_file(&name.to_string_lossy()) { - std::fs::copy(entry.path(), dst.join(name))?; + std::fs::create_dir(&staging)?; + let result = (|| { + let mut copied = std::collections::HashSet::new(); + if src.exists() { + for entry in std::fs::read_dir(src)? { + let entry = entry?; + let name = entry.file_name(); + let file_type = entry.file_type()?; + if is_options_file(&name.to_string_lossy()) + && (file_type.is_file() || file_type.is_symlink()) + { + if file_type.is_symlink() { + copy_link(&entry.path(), &staging.join(&name))?; + } else { + std::fs::copy(entry.path(), staging.join(&name))?; + } + copied.insert(name); + } + } } + for entry in std::fs::read_dir(&staging)? { + let entry = entry?; + crate::storage::replace_file(&entry.path(), &dst.join(entry.file_name()))?; + } + remove_options(dst, &copied)?; + Ok(()) + })(); + if let Err(error) = std::fs::remove_dir_all(&staging) { + tracing::warn!( + "Could not remove options staging '{}': {error}", + staging.display() + ); } - Ok(()) + result } -fn remove_options(dir: &Path) -> Result<(), ConfigSyncError> { +fn remove_options( + dir: &Path, + copied: &std::collections::HashSet, +) -> Result<(), ConfigSyncError> { if !dir.exists() { return Ok(()); } for entry in std::fs::read_dir(dir)? { let entry = entry?; - if is_options_file(&entry.file_name().to_string_lossy()) { + if is_options_file(&entry.file_name().to_string_lossy()) + && !copied.contains(&entry.file_name()) + { remove_path(&entry.path())?; } } @@ -415,12 +505,30 @@ fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { copy_dir_contents(&source, &target)?; } else if file_type.is_file() { std::fs::copy(&source, &target)?; + } else if file_type.is_symlink() { + copy_link(&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/content/dependencies.rs b/src/instance/content/dependencies.rs index 5c6d42d..718f739 100644 --- a/src/instance/content/dependencies.rs +++ b/src/instance/content/dependencies.rs @@ -213,6 +213,8 @@ async fn install_staged( }); } + let previous = + ContentManifest::load(manifest_path).map_err(|error| NetError::Parse(error.to_string()))?; let mut committed = Vec::new(); for (index, file) in staged.iter().enumerate() { let item = &plan.items[file.item]; @@ -241,8 +243,6 @@ async fn install_staged( }); } - let previous = - ContentManifest::load(manifest_path).map_err(|error| NetError::Parse(error.to_string()))?; let records = match build_records(plan, &previous, minecraft_dir, &staged) { Ok(records) => records, Err(error) => { diff --git a/src/instance/content/reconcile.rs b/src/instance/content/reconcile.rs index 3c9da05..ff5f6fb 100644 --- a/src/instance/content/reconcile.rs +++ b/src/instance/content/reconcile.rs @@ -620,7 +620,10 @@ fn content_files(minecraft_dir: &Path) -> std::io::Result std::io::Result bool { - if path.is_dir() { + let Ok(metadata) = std::fs::symlink_metadata(path) else { + return false; + }; + if metadata.file_type().is_symlink() { + return false; + } + if metadata.is_dir() { return matches!( kind, ContentKind::ResourcePack | ContentKind::Shader | ContentKind::DataPack ); } - if !path.is_file() { + if !metadata.is_file() { return false; } let Some(name) = path.file_name().and_then(|name| name.to_str()) else { @@ -661,7 +670,10 @@ fn directory_fingerprint_metadata(path: &Path) -> Result std::io::Result<()> { for entry in std::fs::read_dir(path)? { let entry = entry?; - let metadata = entry.metadata()?; + let metadata = std::fs::symlink_metadata(entry.path())?; + if metadata.file_type().is_symlink() { + continue; + } let modified = metadata .modified() .unwrap_or(SystemTime::UNIX_EPOCH) diff --git a/src/instance/desktop.rs b/src/instance/desktop.rs index 82b8654..1cf05bb 100644 --- a/src/instance/desktop.rs +++ b/src/instance/desktop.rs @@ -8,7 +8,7 @@ use crate::instance::models::InstanceConfig; const ICON_BYTES: &[u8] = include_bytes!("../../assets/icon.svg"); pub fn desktop_path(name: &str) -> Option { - let sanitized = sanitize(name); + let sanitized = shortcut_name(name); #[cfg(target_os = "linux")] { @@ -56,14 +56,54 @@ fn ensure_icon() -> Option { Some(path) } +fn shortcut_name(name: &str) -> String { + let mut encoded = String::new(); + for character in name.chars() { + if character.is_alphanumeric() || matches!(character, '-' | '_') { + encoded.push(character); + } else { + for byte in character.to_string().bytes() { + encoded.push_str(&format!("%{byte:02X}")); + } + } + } + encoded +} + +fn legacy_path(name: &str) -> Option { + let legacy = desktop_path(&sanitize(name))?; + (Some(&legacy) != desktop_path(name).as_ref()).then_some(legacy) +} + +fn owns_legacy_shortcut(path: &Path, name: &str) -> bool { + let content = build_content(name, None); + let command = content.lines().find(|line| { + line.starts_with("Exec=") + || line.starts_with("shell.Run ") + || line.starts_with("rmcl instance launch ") + }); + command.is_some_and(|command| { + std::fs::read_to_string(path) + .is_ok_and(|existing| existing.lines().any(|line| line == command)) + }) +} + pub fn exists(name: &str) -> bool { - desktop_path(name).map(|p| p.exists()).unwrap_or(false) + desktop_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name)) + || legacy_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name)) } pub fn create(config: &InstanceConfig) -> std::io::Result { let path = desktop_path(&config.name) .ok_or_else(|| std::io::Error::other("cannot resolve shortcut directory"))?; + if path.exists() && !owns_legacy_shortcut(&path, &config.name) { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + format!("Another shortcut already exists at '{}'", path.display()), + )); + } + if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } @@ -81,6 +121,12 @@ pub fn create(config: &InstanceConfig) -> std::io::Result { std::fs::set_permissions(&path, perms)?; } + if let Some(legacy) = legacy_path(&config.name) + && owns_legacy_shortcut(&legacy, &config.name) + { + std::fs::remove_file(legacy)?; + } + Ok(path) } @@ -88,9 +134,14 @@ pub fn remove(name: &str) -> std::io::Result<()> { let Some(path) = desktop_path(name) else { return Ok(()); }; - if path.exists() { + if owns_legacy_shortcut(&path, name) { std::fs::remove_file(path)?; } + if let Some(legacy) = legacy_path(name) + && owns_legacy_shortcut(&legacy, name) + { + std::fs::remove_file(legacy)?; + } Ok(()) } @@ -109,12 +160,13 @@ pub fn toggle(config: &InstanceConfig) -> std::io::Result { } pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()> { - let Some(old_path) = desktop_path(old_name).filter(|path| path.exists()) else { + if !exists(old_name) { return Ok(()); - }; + } + let same_path = desktop_path(old_name) == desktop_path(&new_config.name); create(new_config)?; - if desktop_path(&new_config.name).as_ref() != Some(&old_path) { - std::fs::remove_file(old_path)?; + if !same_path { + remove(old_name)?; } Ok(()) } diff --git a/src/instance/import/refresh.rs b/src/instance/import/refresh.rs index bb08b58..12aa6ba 100644 --- a/src/instance/import/refresh.rs +++ b/src/instance/import/refresh.rs @@ -6,6 +6,7 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; +use crate::instance::content::manifest::ContentManifest; use crate::instance::{InstanceConfig, InstanceManager, ProviderProject}; use crate::net::modrinth::VersionInfo; use crate::storage::InstancePaths; @@ -170,6 +171,13 @@ pub fn apply( &plan.new_owned, replace_conflicts, )?; + preserve_refresh_state( + &live, + &plan.staged_instance, + &plan.old_owned, + &plan.new_owned, + replace_conflicts, + )?; let backup = live.with_file_name(format!(".{}.rmcl-backup", plan.instance.name)); if backup.exists() { @@ -247,6 +255,54 @@ fn user_file_collisions( Ok(collisions) } +fn preserve_refresh_state( + live: &Path, + staged: &Path, + old_owned: &HashSet, + new_owned: &HashSet, + replace_conflicts: &HashSet, +) -> Result<(), String> { + let old = InstancePaths::new(live); + let new = InstancePaths::new(staged); + let local_config = old.local_config(); + if local_config.exists() { + std::fs::create_dir_all(new.local_config()).map_err(|e| e.to_string())?; + preserve_user_files( + &local_config, + &new.local_config(), + &local_config, + &HashSet::new(), + &HashSet::new(), + &HashSet::new(), + )?; + } + + let old_manifest = ContentManifest::load(&old.content_manifest()).map_err(|e| e.to_string())?; + let mut new_manifest = + ContentManifest::load(&new.content_manifest()).map_err(|e| e.to_string())?; + for record in &old_manifest.files { + let path = &record.relative_path; + if !old_owned.contains(path) + && !(new_owned.contains(path) && replace_conflicts.contains(path)) + && old.minecraft().join(path).exists() + { + new_manifest.upsert(record.clone()); + } + } + for path in new_owned { + if !replace_conflicts.contains(path) + && !old_owned.contains(path) + && old.minecraft().join(path).exists() + && old_manifest.record(path).is_none() + { + new_manifest.remove(path); + } + } + new_manifest + .save(&new.content_manifest()) + .map_err(|e| e.to_string()) +} + fn preserve_user_files( source: &Path, destination: &Path, @@ -260,13 +316,34 @@ fn preserve_user_files( let path = entry.path(); let relative = path.strip_prefix(root).map_err(|error| error.to_string())?; let metadata = std::fs::symlink_metadata(&path).map_err(|error| error.to_string())?; + if old_owned.contains(relative) + || new_owned.contains(relative) && replace_conflicts.contains(relative) + { + continue; + } if metadata.file_type().is_symlink() { + let target = destination.join(entry.file_name()); + if let Ok(existing) = std::fs::symlink_metadata(&target) { + if existing.is_dir() { + return Err(format!( + "Cannot replace directory '{}' with a symbolic link", + target.display() + )); + } + 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 safely preserve symbolic link '{}'", + "Cannot preserve symbolic link '{}' on this platform", path.display() )); - } - if metadata.is_dir() { + } else if metadata.is_dir() { let target = destination.join(entry.file_name()); std::fs::create_dir_all(&target).map_err(|error| error.to_string())?; preserve_user_files( @@ -277,9 +354,7 @@ fn preserve_user_files( new_owned, replace_conflicts, )?; - } else if !(old_owned.contains(relative) - || new_owned.contains(relative) && replace_conflicts.contains(relative)) - { + } else { let target = destination.join(entry.file_name()); std::fs::copy(&path, target).map_err(|error| error.to_string())?; } @@ -301,7 +376,7 @@ fn collect_files( let metadata = std::fs::symlink_metadata(&path).map_err(|error| error.to_string())?; if metadata.is_dir() { collect_files(&path, root, visit)?; - } else if metadata.is_file() { + } else if metadata.is_file() || metadata.file_type().is_symlink() { visit( path.strip_prefix(root).map_err(|error| error.to_string())?, &path, @@ -332,6 +407,101 @@ fn format_bytes(bytes: u64) -> String { mod tests { use super::*; + use crate::instance::content::manifest::{ContentFileRecord, ContentKind, FileFingerprint}; + + fn record(path: &str) -> ContentFileRecord { + ContentFileRecord { + relative_path: path.into(), + kind: ContentKind::Mod, + enabled: true, + fingerprint: FileFingerprint { + size: 1, + modified_ns: 1, + hashes: Default::default(), + }, + resolution: Default::default(), + provider_aliases: Vec::new(), + provider_checks: Vec::new(), + required_dependencies: Vec::new(), + automatic_dependency: false, + cleanup_eligible: false, + } + } + + #[test] + fn refresh_keeps_local_config_and_user_content_records() { + let temp = tempfile::tempdir().unwrap(); + let old = InstancePaths::new(temp.path().join("old")); + let new = InstancePaths::new(temp.path().join("new")); + std::fs::create_dir_all(old.local_config()).unwrap(); + std::fs::write(old.local_config().join("options.txt"), b"local").unwrap(); + std::fs::create_dir_all(old.minecraft().join("mods")).unwrap(); + std::fs::write(old.minecraft().join("mods/user.jar"), b"user").unwrap(); + std::fs::write(old.minecraft().join("mods/replace.jar"), b"user").unwrap(); + std::fs::create_dir_all(new.minecraft().join("mods")).unwrap(); + let mut previous = ContentManifest::default(); + previous.upsert(record("mods/user.jar")); + previous.upsert(record("mods/replace.jar")); + previous.save(&old.content_manifest()).unwrap(); + let mut staged = ContentManifest::default(); + staged.upsert(record("mods/pack.jar")); + staged.save(&new.content_manifest()).unwrap(); + + preserve_refresh_state( + old.root(), + new.root(), + &HashSet::new(), + &HashSet::from([ + PathBuf::from("mods/pack.jar"), + PathBuf::from("mods/replace.jar"), + ]), + &HashSet::from([PathBuf::from("mods/replace.jar")]), + ) + .unwrap(); + + assert_eq!( + std::fs::read(new.local_config().join("options.txt")).unwrap(), + b"local" + ); + let manifest = ContentManifest::load(&new.content_manifest()).unwrap(); + 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()); + } + + #[cfg(unix)] + #[test] + fn refresh_preserves_user_symlinks_without_following_them() { + let temp = tempfile::tempdir().unwrap(); + let old = temp.path().join("old"); + let new = temp.path().join("new"); + std::fs::create_dir_all(&old).unwrap(); + std::fs::create_dir_all(&new).unwrap(); + std::os::unix::fs::symlink("outside", old.join("linked.jar")).unwrap(); + std::os::unix::fs::symlink(&old, old.join("loop")).unwrap(); + let collisions = user_file_collisions( + &old, + &HashSet::new(), + &HashSet::from([PathBuf::from("linked.jar")]), + ) + .unwrap(); + assert_eq!(collisions, vec![PathBuf::from("linked.jar")]); + preserve_user_files( + &old, + &new, + &old, + &HashSet::new(), + &HashSet::new(), + &HashSet::new(), + ) + .unwrap(); + assert_eq!( + std::fs::read_link(new.join("linked.jar")).unwrap(), + PathBuf::from("outside") + ); + assert_eq!(std::fs::read_link(new.join("loop")).unwrap(), old); + } + #[test] fn preservation_replaces_pack_files_and_keeps_user_files() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index ae038b2..a40ffab 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -711,14 +711,12 @@ async fn run_launch_command( } fn finish_config_sync( - active: bool, - profile: Option<&str>, - meta_dir: &Path, + lock: Option, minecraft_dir: &Path, instance: &str, ) { - if active - && let Err(error) = crate::instance::config_sync::finish(profile, meta_dir, minecraft_dir) + if let Some(lock) = lock + && let Err(error) = crate::instance::config_sync::finish_launch(lock, minecraft_dir) { tracing::warn!("Failed to sync config for '{}': {}", instance, error); } @@ -771,7 +769,7 @@ pub async fn launch( changed = true; } if changed { - account_store.save(); + account_store.save()?; } } @@ -800,9 +798,8 @@ pub async fn launch( invocation.game_args.len(), invocation.main_class ); - let config_sync_profile = config.config_sync_profile.clone(); - let config_sync_active = crate::instance::config_sync::prepare( - config_sync_profile.as_deref(), + let config_sync_lock = crate::instance::config_sync::prepare_for_launch( + config.config_sync_profile.as_deref(), meta_dir, &invocation.working_dir, )?; @@ -815,13 +812,7 @@ pub async fn launch( ) .await { - finish_config_sync( - config_sync_active, - config_sync_profile.as_deref(), - meta_dir, - &invocation.working_dir, - &name, - ); + finish_config_sync(config_sync_lock, &invocation.working_dir, &name); return Err(error); } @@ -865,13 +856,7 @@ pub async fn launch( Err(e) => { crate::instance::runtime::cleanup_kill_sender(&name); crate::instance::runtime::remove(&name); - finish_config_sync( - config_sync_active, - config_sync_profile.as_deref(), - meta_dir, - &invocation.working_dir, - &name, - ); + finish_config_sync(config_sync_lock, &invocation.working_dir, &name); tracing::error!("[{}] Failed to spawn Minecraft process: {}", name, e); return Err(LaunchError::Io(e)); } @@ -1009,13 +994,7 @@ pub async fn launch( crate::feedback::errors::push_message(tracing::Level::WARN, error.to_string()); } - finish_config_sync( - config_sync_active, - config_sync_profile.as_deref(), - &meta_dir_owned, - &minecraft_dir_owned, - &name_for_task, - ); + finish_config_sync(config_sync_lock, &minecraft_dir_owned, &name_for_task); if code == Some(0) || killed_by_user { crate::instance::runtime::remove(&name_for_task); tracing::debug!( diff --git a/src/instance/manager.rs b/src/instance/manager.rs index ad89388..1b5362b 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -16,6 +16,8 @@ pub enum InstanceError { AlreadyExists(String), #[error("Instance '{0}' not found")] NotFound(String), + #[error("Stop instance '{0}' before renaming or deleting it")] + InstanceRunning(String), #[error("IO error: {0}")] Io(#[from] std::io::Error), #[error("JSON error: {0}")] @@ -405,6 +407,9 @@ impl InstanceManager { pub fn delete(&self, name: &str) -> Result<(), InstanceError> { validate_name(name)?; + if crate::instance::runtime::is_active(name) { + return Err(InstanceError::InstanceRunning(name.to_owned())); + } let instance_dir = self.instances_dir.join(name); if !instance_dir.exists() { tracing::warn!( @@ -431,6 +436,9 @@ impl InstanceManager { pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> { validate_name(old_name)?; + if crate::instance::runtime::is_active(old_name) { + return Err(InstanceError::InstanceRunning(old_name.to_owned())); + } let new_name = new_name.trim(); if new_name.is_empty() { tracing::warn!("Cannot rename instance '{}': new name is empty", old_name); @@ -533,7 +541,16 @@ impl InstanceManager { } }; match serde_json::from_str::(&contents) { - Ok(config) => instances.push(config), + Ok(mut config) => { + let Some(directory_name) = entry.file_name().to_str().map(str::to_owned) else { + continue; + }; + if validate_name(&directory_name).is_err() { + continue; + } + config.name = directory_name; + instances.push(config); + } Err(e) => { tracing::error!("Failed to parse {}: {}", config_path.display(), e); } @@ -570,7 +587,10 @@ impl InstanceManager { } }; match serde_json::from_str::(&contents) { - Ok(config) => Ok(config), + Ok(mut config) => { + config.name = name.to_owned(); + Ok(config) + } Err(e) => { tracing::error!( "Failed to parse instance '{}' config {}: {}", @@ -609,7 +629,7 @@ impl InstanceManager { } // guard against path traversal and other filesystem shenanigans -fn validate_name(name: &str) -> Result<(), InstanceError> { +pub(crate) fn validate_name(name: &str) -> Result<(), InstanceError> { if name.is_empty() || name.len() > 64 { return Err(InstanceError::InvalidName(format!( "Name must be 1-64 chars, got: {:?}", diff --git a/src/instance/tests/config_sync.rs b/src/instance/tests/config_sync.rs index 26c6a5d..c8f2818 100644 --- a/src/instance/tests/config_sync.rs +++ b/src/instance/tests/config_sync.rs @@ -107,6 +107,141 @@ fn prepare_releases_lock_for_another_instance() { assert!(prepare(Some("main"), &meta, &second).unwrap()); } +#[test] +fn active_launch_keeps_its_profile_locked_until_finish() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let first = tmp.path().join("first/minecraft"); + let second = tmp.path().join("second/minecraft"); + std::fs::create_dir_all(first.join("config")).unwrap(); + std::fs::create_dir_all(second.join("config")).unwrap(); + create_profile(&meta, "main").unwrap(); + + let lock = prepare_for_launch(Some("main"), &meta, &first) + .unwrap() + .unwrap(); + assert!(matches!( + prepare_for_launch(Some("main"), &meta, &second), + Err(ConfigSyncError::ProfileInUse(_)) + )); + assert!(matches!( + delete_profile(&meta, "main"), + Err(ConfigSyncError::ProfileInUse(_)) + )); + finish_launch(lock, &first).unwrap(); + assert!( + prepare_for_launch(Some("main"), &meta, &second) + .unwrap() + .is_some() + ); +} + +#[test] +fn failed_options_source_read_keeps_existing_options() { + let tmp = tempfile::tempdir().unwrap(); + let source = tmp.path().join("not-a-directory"); + let target = tmp.path().join("target"); + std::fs::write(&source, b"invalid").unwrap(); + std::fs::create_dir(&target).unwrap(); + std::fs::write(target.join("options.txt"), b"keep").unwrap(); + + assert!(mirror_options(&source, &target).is_err()); + assert_eq!(std::fs::read(target.join("options.txt")).unwrap(), b"keep"); +} + +#[cfg(unix)] +#[test] +fn config_sync_preserves_symlinked_config_and_options() { + let tmp = tempfile::tempdir().unwrap(); + let minecraft = tmp.path().join("minecraft"); + let profile = tmp.path().join("profile"); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + std::fs::write(tmp.path().join("shared.toml"), "settings").unwrap(); + std::os::unix::fs::symlink( + tmp.path().join("shared.toml"), + minecraft.join("config/mod.toml"), + ) + .unwrap(); + std::os::unix::fs::symlink( + tmp.path().join("shared.toml"), + minecraft.join("options.txt"), + ) + .unwrap(); + + sync_to_profile(&minecraft, &profile).unwrap(); + assert!( + std::fs::symlink_metadata(profile.join("config/mod.toml")) + .unwrap() + .file_type() + .is_symlink() + ); + assert!( + std::fs::symlink_metadata(profile.join("options.txt")) + .unwrap() + .file_type() + .is_symlink() + ); + sync_from_profile(&profile, &minecraft).unwrap(); + assert!( + std::fs::symlink_metadata(minecraft.join("config/mod.toml")) + .unwrap() + .file_type() + .is_symlink() + ); + assert!( + std::fs::symlink_metadata(minecraft.join("options.txt")) + .unwrap() + .file_type() + .is_symlink() + ); +} + +#[cfg(unix)] +#[test] +fn symlink_only_profile_is_not_reinitialized_or_replaced() { + let tmp = tempfile::tempdir().unwrap(); + let minecraft = tmp.path().join("minecraft"); + let meta = tmp.path().join("meta"); + let profile = crate::storage::MetadataPaths::new(&meta) + .profiles() + .join("linked"); + std::fs::create_dir_all(&profile).unwrap(); + std::fs::create_dir_all(&minecraft).unwrap(); + std::fs::write(tmp.path().join("shared-options"), b"profile").unwrap(); + std::os::unix::fs::symlink( + tmp.path().join("shared-options"), + profile.join("options.txt"), + ) + .unwrap(); + + let lock = prepare_for_launch(Some("linked"), &meta, &minecraft).unwrap(); + assert!(lock.is_some()); + assert_eq!( + std::fs::read(minecraft.join("options.txt")).unwrap(), + b"profile" + ); + assert!( + std::fs::symlink_metadata(minecraft.join("options.txt")) + .unwrap() + .file_type() + .is_symlink() + ); + + let external = tmp.path().join("external-config"); + std::fs::create_dir(&external).unwrap(); + std::fs::write(external.join("keep.txt"), b"keep").unwrap(); + std::fs::remove_dir(minecraft.join("config")).unwrap(); + std::os::unix::fs::symlink(&external, minecraft.join("config")).unwrap(); + assert!(sync_from_profile(&profile, &minecraft).is_err()); + assert!( + std::fs::symlink_metadata(minecraft.join("config")) + .unwrap() + .file_type() + .is_symlink() + ); + assert_eq!(std::fs::read(external.join("keep.txt")).unwrap(), b"keep"); +} + #[test] fn profile_rejects_path_traversal() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/instance/tests/content/dependencies.rs b/src/instance/tests/content/dependencies.rs index feb054c..fbcbec6 100644 --- a/src/instance/tests/content/dependencies.rs +++ b/src/instance/tests/content/dependencies.rs @@ -63,6 +63,56 @@ fn merge_keeps_replacement_when_a_dependency_is_also_an_update_root() { assert!(!merged.items[0].automatic_dependency); } +#[tokio::test] +async fn invalid_manifest_does_not_replace_installed_content() { + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join("minecraft"); + let mods = minecraft.join("mods"); + tokio::fs::create_dir_all(&mods).await.unwrap(); + let old = mods.join("old.jar"); + tokio::fs::write(&old, b"original").await.unwrap(); + let manifest = temp.path().join("content.json"); + tokio::fs::write(&manifest, b"{bad JSON").await.unwrap(); + let selected = version( + "new", + "root", + VersionType::Release, + "2026-02-01", + Vec::new(), + ); + let plan = DependencyPlan { + items: vec![PlannedInstall { + provider: "modrinth".to_owned(), + project_id: "root".to_owned(), + title: "Root".to_owned(), + version: selected.clone(), + installed_path: Some(old.clone()), + kind: ContentKind::Mod, + destination: mods.clone(), + provider_aliases: Vec::new(), + required_dependencies: Vec::new(), + automatic_dependency: false, + cleanup_eligible: false, + replacement: true, + }], + root_count: 1, + optional_dependencies: 0, + }; + + assert!( + install( + &provider(vec![selected]).registry(), + &manifest, + &minecraft, + &plan + ) + .await + .is_err() + ); + assert_eq!(tokio::fs::read(old).await.unwrap(), b"original"); + assert!(!mods.join("new.jar").exists()); +} + struct FakeProvider { versions: HashMap, compatible: HashMap>, diff --git a/src/instance/tests/content/reconcile.rs b/src/instance/tests/content/reconcile.rs index 05bf6b1..541c04f 100644 --- a/src/instance/tests/content/reconcile.rs +++ b/src/instance/tests/content/reconcile.rs @@ -5,6 +5,21 @@ use super::*; struct NoopProgress; +#[cfg(unix)] +#[test] +fn linked_pack_contents_cannot_recurse_into_themselves() { + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join("minecraft"); + let pack = minecraft.join("resourcepacks/unpacked"); + std::fs::create_dir_all(&pack).unwrap(); + std::fs::write(pack.join("pack.mcmeta"), b"pack").unwrap(); + std::os::unix::fs::symlink(&pack, pack.join("again")).unwrap(); + + let files = content_files(&minecraft).unwrap(); + assert_eq!(files.len(), 1); + assert_eq!(directory_fingerprint_metadata(&pack).unwrap().size, 4); +} + impl InventoryProgress for NoopProgress { fn set_sub_action(&self, _text: &str) {} diff --git a/src/instance/tests/desktop.rs b/src/instance/tests/desktop.rs index dd9b89c..de99ea0 100644 --- a/src/instance/tests/desktop.rs +++ b/src/instance/tests/desktop.rs @@ -14,6 +14,23 @@ fn sanitize_replaces_special_chars() { assert_eq!(sanitize("path/traversal"), "path_traversal"); } +#[test] +fn shortcut_paths_do_not_collide_after_escaping() { + assert_ne!(shortcut_name("a b"), shortcut_name("a_b")); + assert_ne!(shortcut_name("a?b"), shortcut_name("a b")); + assert_ne!(shortcut_name("a%b"), shortcut_name("a%25b")); + assert_eq!(shortcut_name("my-instance_123"), "my-instance_123"); +} + +#[test] +fn legacy_shortcut_is_attributed_to_the_right_instance() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("rmcl-a_b.desktop"); + std::fs::write(&path, build_content("a b", None)).unwrap(); + assert!(owns_legacy_shortcut(&path, "a b")); + assert!(!owns_legacy_shortcut(&path, "a_b")); +} + #[test] #[cfg(target_os = "linux")] fn build_content_linux() { diff --git a/src/instance/tests/manager.rs b/src/instance/tests/manager.rs index 0709ffc..fc6b65e 100644 --- a/src/instance/tests/manager.rs +++ b/src/instance/tests/manager.rs @@ -62,6 +62,45 @@ fn delete_missing_instance_returns_not_found() { assert!(matches!(result, Err(InstanceError::NotFound(_)))); } +#[test] +fn running_instance_cannot_be_deleted_or_renamed() { + let (manager, tmp) = test_manager(); + let name = format!("running-{}", std::process::id()); + std::fs::create_dir_all(tmp.path().join(&name)).unwrap(); + manager.save(&dummy_config(&name)).unwrap(); + crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Running); + + let deletion = manager.delete(&name); + let rename = manager.rename(&name, "changed"); + crate::instance::runtime::remove(&name); + + assert!(matches!(deletion, Err(InstanceError::InstanceRunning(_)))); + assert!(matches!(rename, Err(InstanceError::InstanceRunning(_)))); + assert!(tmp.path().join(&name).exists()); + assert!(!tmp.path().join("changed").exists()); +} + +#[test] +fn copied_instance_uses_its_directory_as_identity() { + let (manager, tmp) = test_manager(); + std::fs::create_dir_all(tmp.path().join("original")).unwrap(); + manager.save(&dummy_config("original")).unwrap(); + std::fs::create_dir_all(tmp.path().join("copy")).unwrap(); + std::fs::copy( + tmp.path().join("original/instance.json"), + tmp.path().join("copy/instance.json"), + ) + .unwrap(); + + assert_eq!(manager.load_one("copy").unwrap().name, "copy"); + assert!( + manager + .load_all() + .iter() + .any(|config| config.name == "copy") + ); +} + #[tokio::test] async fn create_preserves_directory_without_instance_config() { let (manager, tmp) = test_manager(); diff --git a/src/layout_migration.rs b/src/layout_migration.rs index 62e7987..05b9e1a 100644 --- a/src/layout_migration.rs +++ b/src/layout_migration.rs @@ -84,22 +84,21 @@ pub enum MigrationError { pub fn is_needed(instances_dir: &Path, meta_dir: &Path) -> bool { let metadata = MetadataPaths::new(meta_dir); - if metadata.cache_rebuild_pending().exists() { - return true; - } - if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION) { - return false; - } - has_legacy_instances(instances_dir) - || [ - "versions", - "libraries", - "assets", - "loader-profiles", - "config-sync", - ] - .iter() - .any(|path| meta_dir.join(path).exists()) + metadata.cache_rebuild_pending().exists() + || has_legacy_instances(instances_dir) + || has_legacy_shared_data(meta_dir) +} + +fn has_legacy_shared_data(meta_dir: &Path) -> bool { + [ + "versions", + "libraries", + "assets", + "loader-profiles", + "config-sync", + ] + .iter() + .any(|path| meta_dir.join(path).exists()) } pub fn initialize_new_layout(meta_dir: &Path) -> Result<(), MigrationError> { @@ -137,6 +136,8 @@ pub fn run( let metadata = MetadataPaths::new(meta_dir); if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION) && metadata.cache_rebuild_pending().exists() + && !has_legacy_instances(instances_dir) + && !has_legacy_shared_data(meta_dir) { crate::config::upgrade_config_file(config_file)?; return Ok(latest_layout_backup(&metadata).unwrap_or_else(|| metadata.backups())); diff --git a/src/tests/layout_migration.rs b/src/tests/layout_migration.rs index 479fe0c..44e0a96 100644 --- a/src/tests/layout_migration.rs +++ b/src/tests/layout_migration.rs @@ -3,6 +3,52 @@ use super::*; +#[test] +fn migrated_layout_detects_a_newly_copied_legacy_instance() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + fs::create_dir_all(&instances).unwrap(); + initialize_new_layout(&meta).unwrap(); + assert!(!is_needed(&instances, &meta)); + + fs::create_dir_all(instances.join("copied/.minecraft/saves")).unwrap(); + assert!(is_needed(&instances, &meta)); + fs::write(temp.path().join("config.toml"), b"[paths]").unwrap(); + fs::write( + MetadataPaths::new(&meta).cache_rebuild_pending(), + LAYOUT_VERSION.to_string(), + ) + .unwrap(); + run(&instances, &meta, &temp.path().join("config.toml"), |_| {}).unwrap(); + assert!(instances.join("copied/minecraft/saves").exists()); +} + +#[test] +fn migrated_layout_detects_newly_copied_shared_data() { + 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).unwrap(); + fs::write(&config, b"[paths]").unwrap(); + initialize_new_layout(&meta).unwrap(); + fs::write( + MetadataPaths::new(&meta).cache_rebuild_pending(), + LAYOUT_VERSION.to_string(), + ) + .unwrap(); + fs::create_dir_all(meta.join("versions")).unwrap(); + fs::write(meta.join("versions/copied.json"), b"data").unwrap(); + + assert!(is_needed(&instances, &meta)); + run(&instances, &meta, &config, |_| {}).unwrap(); + assert_eq!( + fs::read(MetadataPaths::new(&meta).versions().join("copied.json")).unwrap(), + b"data" + ); +} + #[test] fn migration_backs_up_and_renames_instance_directories() { let temp = tempfile::tempdir().unwrap(); @@ -155,7 +201,10 @@ fn migration_need_follows_legacy_data_marker_and_pending_rebuild() { assert!(is_needed(&instances, &meta)); initialize_new_layout(&meta).unwrap(); + assert!(is_needed(&instances, &meta)); + fs::remove_dir_all(instances.join("Example/.minecraft")).unwrap(); assert!(!is_needed(&instances, &meta)); + fs::create_dir_all(meta.join("versions")).unwrap(); fs::write(MetadataPaths::new(&meta).layout_marker(), b"invalid marker").unwrap(); assert!(is_needed(&instances, &meta)); initialize_new_layout(&meta).unwrap();