diff --git a/src/cli/instance.rs b/src/cli/instance.rs index e085fad..9c62f86 100644 --- a/src/cli/instance.rs +++ b/src/cli/instance.rs @@ -22,7 +22,7 @@ pub async fn handle_instance(matches: &ArgMatches) -> CliResult { Some(("rename", sub_matches)) => rename_instance(sub_matches), Some(("launch", sub_matches)) => launch_instance(sub_matches).await, Some(("config", sub_matches)) => config_instance(sub_matches), - Some(("profile", sub_matches)) => profile_instance(sub_matches), + Some(("profile", sub_matches)) => profile_instance(sub_matches, &manager()), Some(("desktop", sub_matches)) => desktop_instance(sub_matches), _ => Ok(()), } @@ -206,7 +206,7 @@ fn config_instance(matches: &ArgMatches) -> CliResult { if config.jvm_args.is_empty() { "-".to_string() } else { - config.jvm_args.join(" ") + crate::config::settings::format_tag_values(&config.jvm_args) }, ], vec![ @@ -226,19 +226,10 @@ fn config_instance(matches: &ArgMatches) -> CliResult { Ok(()) } -fn profile_instance(matches: &ArgMatches) -> CliResult { +fn profile_instance(matches: &ArgMatches, manager: &InstanceManager) -> CliResult { let name = required_arg(matches, "name")?; - let manager = manager(); let mut config = manager.load_one(name)?; let profiles = crate::instance::config_sync::list_profiles(&manager.meta_dir)?; - if config - .config_sync_profile - .as_ref() - .is_some_and(|profile| !profiles.iter().any(|candidate| candidate == profile)) - { - config.config_sync_profile = None; - manager.save(&config)?; - } let Some(profile) = matches.get_one::("profile") else { let rows = vec![ @@ -264,7 +255,7 @@ fn profile_instance(matches: &ArgMatches) -> CliResult { } else { Some(profile.as_str()) }; - crate::instance::config_sync::switch_profile_and_save(&manager, &mut config, target)?; + crate::instance::config_sync::switch_profile_and_save(manager, &mut config, target)?; println!( "Updated '{}' config profile to {}.", @@ -308,7 +299,8 @@ fn apply_config_update( } } "jvm-args" => { - config.jvm_args = value.split_whitespace().map(String::from).collect(); + config.jvm_args = + crate::config::settings::parse_tag_values(value).map_err(io::Error::other)?; } "resolution" => { config.resolution = if value.is_empty() { diff --git a/src/cli/tests/instance.rs b/src/cli/tests/instance.rs index 3e0b57f..baa1336 100644 --- a/src/cli/tests/instance.rs +++ b/src/cli/tests/instance.rs @@ -29,3 +29,128 @@ fn invalid_memory_update_keeps_existing_setting() { assert!(super::apply_config_update(&mut config, "memory-max", "garbage").is_err()); assert_eq!(config.memory_max.as_deref(), Some("8G")); } + +#[test] +fn jvm_argument_updates_preserve_quoted_paths_and_repeated_options() { + let mut config: crate::instance::InstanceConfig = serde_json::from_value(serde_json::json!({ + "name": "test", "game_version": "1.21.1", "loader": "vanilla", + "loader_version": null, "created": "2026-01-01T00:00:00Z" + })) + .unwrap(); + super::apply_config_update(&mut config, "jvm-args", r#""-Dpath=C:\Program Files\Java" --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED"#).unwrap(); + assert_eq!( + config.jvm_args, + [ + r"-Dpath=C:\Program Files\Java", + "--add-opens", + "java.base/java.lang=ALL-UNNAMED", + "--add-opens", + "java.base/java.util=ALL-UNNAMED" + ] + ); + let previous = config.jvm_args.clone(); + assert!(super::apply_config_update(&mut config, "jvm-args", "\"unterminated").is_err()); + assert_eq!(config.jvm_args, previous); + super::apply_config_update(&mut config, "jvm-args", "").unwrap(); + assert!(config.jvm_args.is_empty()); +} + +#[test] +fn config_sync_profile_display_is_read_only_and_deleted_profiles_restore_local_defaults() { + for target in ["default", "other"] { + let tmp = tempfile::tempdir().unwrap(); + let manager = crate::instance::InstanceManager::new( + tmp.path().join("instances"), + tmp.path().join("meta"), + ); + let instance = manager.instances_dir.join("inst"); + let minecraft = crate::storage::InstancePaths::new(&instance).minecraft(); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + std::fs::write(minecraft.join("options.txt"), b"local-default").unwrap(); + std::fs::write(minecraft.join("config/value"), b"local-default").unwrap(); + let mut config = serde_json::from_value(serde_json::json!({ + "name": "inst", "game_version": "1.21.1", "loader": "vanilla", "loader_version": null, + "created": "2026-01-01T00:00:00Z" + })) + .unwrap(); + manager.save(&config).unwrap(); + crate::instance::config_sync::switch_profile_and_save(&manager, &mut config, Some("main")) + .unwrap(); + std::fs::write(minecraft.join("options.txt"), b"profile-options").unwrap(); + crate::instance::config_sync::delete_profile(&manager.meta_dir, "main").unwrap(); + crate::instance::config_sync::create_profile(&manager.meta_dir, "other").unwrap(); + std::fs::write( + crate::storage::MetadataPaths::new(&manager.meta_dir) + .profiles() + .join("other/options.txt"), + b"other-options", + ) + .unwrap(); + let original_config = std::fs::read(instance.join("instance.json")).unwrap(); + let matches = crate::cli::build_command() + .try_get_matches_from(["rmcl", "instance", "profile", "inst"]) + .unwrap(); + let profile_matches = matches + .subcommand_matches("instance") + .unwrap() + .subcommand_matches("profile") + .unwrap(); + super::profile_instance(profile_matches, &manager).unwrap(); + assert_eq!( + std::fs::read(instance.join("instance.json")).unwrap(), + original_config + ); + assert_eq!( + std::fs::read(minecraft.join("options.txt")).unwrap(), + b"profile-options" + ); + + let matches = crate::cli::build_command() + .try_get_matches_from(["rmcl", "instance", "profile", "inst", target]) + .unwrap(); + let profile_matches = matches + .subcommand_matches("instance") + .unwrap() + .subcommand_matches("profile") + .unwrap(); + super::profile_instance(profile_matches, &manager).unwrap(); + if target == "other" { + assert_eq!( + manager + .load_one("inst") + .unwrap() + .config_sync_profile + .as_deref(), + Some("other") + ); + assert_eq!( + std::fs::read(minecraft.join("options.txt")).unwrap(), + b"other-options" + ); + let matches = crate::cli::build_command() + .try_get_matches_from(["rmcl", "instance", "profile", "inst", "default"]) + .unwrap(); + let profile_matches = matches + .subcommand_matches("instance") + .unwrap() + .subcommand_matches("profile") + .unwrap(); + super::profile_instance(profile_matches, &manager).unwrap(); + } + assert_eq!(manager.load_one("inst").unwrap().config_sync_profile, None); + assert_eq!( + std::fs::read(minecraft.join("options.txt")).unwrap(), + b"local-default" + ); + assert_eq!( + std::fs::read(minecraft.join("config/value")).unwrap(), + b"local-default" + ); + assert!( + !crate::storage::MetadataPaths::new(&manager.meta_dir) + .profiles() + .join("main") + .exists() + ); + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs index 0bf1ba5..034dc35 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -251,6 +251,13 @@ pub static SETTINGS: LazyLock = LazyLock::new(|| { fn write_config_document(path: &std::path::Path, config: &Config) -> io::Result<()> { write_merged_toml_document(path, config, |document| { + if let Some(environment) = document + .get_mut("defaults") + .and_then(|defaults| defaults.get_mut("environment")) + .and_then(toml_edit::Item::as_table_mut) + { + environment.retain(|key, _| config.defaults.environment.contains_key(key)); + } if config.paths.java_path.is_none() && let Some(paths) = document .get_mut("paths") diff --git a/src/config/settings.rs b/src/config/settings.rs index b35c022..d710c24 100644 --- a/src/config/settings.rs +++ b/src/config/settings.rs @@ -248,7 +248,7 @@ impl Default for Paths { } pub fn resolve_path(raw: &str) -> PathBuf { - if let Some(stripped) = raw.strip_prefix("~/") { + if let Some(stripped) = raw.strip_prefix("~/").or_else(|| raw.strip_prefix("~\\")) { if let Some(home) = dirs::home_dir() { return home.join(stripped); } @@ -315,9 +315,75 @@ impl Default for Defaults { } } +pub(crate) fn parse_tag_values(input: &str) -> Result, String> { + #[derive(Clone, Copy, PartialEq, Eq)] + enum Quote { + None, + Single, + Double, + } + + let mut values = Vec::new(); + let mut current = String::new(); + let mut quote = Quote::None; + let mut started = false; + let mut characters = input.chars().peekable(); + while let Some(character) = characters.next() { + match (quote, character) { + (Quote::None, character) if character.is_whitespace() => { + if started { + values.push(std::mem::take(&mut current)); + started = false; + } + } + (Quote::None, '\'') => { + quote = Quote::Single; + started = true; + } + (Quote::None, '"') => { + quote = Quote::Double; + started = true; + } + (Quote::Single, '\'') => quote = Quote::None, + (Quote::Double, '"') => quote = Quote::None, + (Quote::Double, '\\') if matches!(characters.peek(), Some('"' | '\\')) => { + current.push(characters.next().unwrap_or_default()); + started = true; + } + (_, character) => { + current.push(character); + started = true; + } + } + } + if quote != Quote::None { + return Err("Quoted value is missing its closing quote.".to_owned()); + } + if started { + values.push(current); + } + Ok(values) +} + +pub(crate) fn format_tag_values(values: &[String]) -> String { + values + .iter() + .map(|value| { + if !value.is_empty() + && !value + .chars() + .any(|character| character.is_whitespace() || matches!(character, '\'' | '"')) + { + value.clone() + } else { + format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) + } + }) + .collect::>() + .join(" ") +} + #[derive(Debug, Clone, Serialize, Deserialize)] -// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s, -// fly off screen over 300ms. tweak these if the toasts feel too fast or slow. pub struct Ui { #[serde(default)] pub image_protocol: ImageProtocol, diff --git a/src/config/tests/loading.rs b/src/config/tests/loading.rs index 94672fd..51f3f67 100644 --- a/src/config/tests/loading.rs +++ b/src/config/tests/loading.rs @@ -3,6 +3,28 @@ use super::*; +#[test] +fn saving_settings_removes_deleted_environment_keys_and_keeps_retained_comments() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("config.toml"); + std::fs::write( + &path, + "[defaults.environment]\nKEEP = 'old' # retained\nREMOVE = 'gone'\n[unknown]\nvalue = 1\n", + ) + .unwrap(); + let mut config = Config::default(); + config + .defaults + .environment + .insert("KEEP".to_owned(), "new".to_owned()); + write_config_document(&path, &config).unwrap(); + let source = std::fs::read_to_string(&path).unwrap(); + assert!(!source.contains("REMOVE")); + assert!(source.contains("# retained")); + assert!(source.contains("[unknown]")); + assert_eq!(load_config(&path).unwrap().defaults.environment.len(), 1); +} + #[test] fn load_config_from_valid_toml() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/config/tests/settings.rs b/src/config/tests/settings.rs index 41e6bde..f47d9e2 100644 --- a/src/config/tests/settings.rs +++ b/src/config/tests/settings.rs @@ -80,15 +80,18 @@ fn resolve_path_absolute() { #[test] fn resolve_path_tilde_prefix() { - let resolved = resolve_path("~/games/rmcl"); - assert!(!resolved.to_string_lossy().starts_with('~')); - assert!(resolved.to_string_lossy().ends_with("games/rmcl")); + let home = dirs::home_dir().expect("test environment has a home directory"); + for path in ["~/games/rmcl", r"~\games/rmcl"] { + assert_eq!(resolve_path(path), home.join("games/rmcl")); + } } #[test] fn resolve_path_bare_tilde() { - let resolved = resolve_path("~"); - assert!(!resolved.to_string_lossy().starts_with('~')); + assert_eq!( + resolve_path("~"), + dirs::home_dir().expect("test environment has a home directory") + ); } #[test] diff --git a/src/config/tests/theme.rs b/src/config/tests/theme.rs index 01ae4d1..cbd8918 100644 --- a/src/config/tests/theme.rs +++ b/src/config/tests/theme.rs @@ -3,8 +3,6 @@ use super::*; -// cover every BorderStyle variant. a mutation that swaps two arms of the -// match (e.g. Rounded -> Plain) would slip past testing just one variant. #[rstest::rstest] #[case::plain(BorderStyle::Plain, BorderType::Plain)] #[case::rounded(BorderStyle::Rounded, BorderType::Rounded)] @@ -51,13 +49,43 @@ fn resolve_with_overrides_keeps_base() { }), ..ThemeConfig::default() }; - let theme = resolve_app_theme(&config); - assert_eq!(theme.accent(), Color::Red); + let theme = resolve_app_theme(&config).unwrap(); + assert_eq!( + theme.accent(), + if ratatui_themekit::no_color_active() { + resolve_theme("dracula").accent() + } else { + Color::Red + } + ); let base = resolve_theme("dracula"); assert_eq!(theme.text(), base.text()); assert_eq!(theme.error(), base.error()); } +#[test] +fn missing_and_invalid_custom_themes_are_errors() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("theme.toml"); + let config = ThemeConfig { + theme: path.to_string_lossy().into_owned(), + ..Default::default() + }; + assert!(resolve_app_theme(&config).is_err()); + std::fs::write(&path, "bad theme").unwrap(); + assert!(resolve_app_theme(&config).is_err()); + std::fs::write(&path, include_str!("../../../assets/example-theme.toml")).unwrap(); + let theme = resolve_app_theme(&config).unwrap(); + assert_eq!( + theme.id(), + if ratatui_themekit::no_color_active() { + "no-color" + } else { + "my-theme" + } + ); +} + #[test] fn resolve_builtin_theme() { let theme = resolve_theme("dracula"); @@ -83,7 +111,6 @@ fn custom_theme_file_parses() { toml::from_str::("name = \"X\"\nid = \"x\"\naccent = \"#f97316\"\n").unwrap(); assert_eq!(minimal.accent, Color::Rgb(249, 115, 22)); - // the two failure modes users hit: nesting under [theme], or omitting name/id assert!( toml::from_str::("[theme]\nname = \"X\"\nid = \"x\"\naccent = \"Red\"\n") .is_err() diff --git a/src/config/theme.rs b/src/config/theme.rs index ee147a8..f23040f 100644 --- a/src/config/theme.rs +++ b/src/config/theme.rs @@ -97,14 +97,17 @@ fn ensure_theme_exists(path: &Path) { let _ = std::fs::write(path, include_str!("../../assets/theme.toml")); } -fn resolve_app_theme(config: &ThemeConfig) -> Box { - let base = load_base_theme(&config.theme); +fn resolve_app_theme(config: &ThemeConfig) -> std::io::Result> { + let base = load_base_theme(&config.theme)?; + if ratatui_themekit::no_color_active() { + return Ok(resolve_theme("catppuccin")); + } let Some(overrides) = &config.custom else { - return base; + return Ok(base); }; - Box::new(CustomTheme { + Ok(Box::new(CustomTheme { name: format!("{} (customized)", base.name()), id: base.id().to_owned(), accent: overrides.accent.unwrap_or_else(|| base.accent()), @@ -126,10 +129,10 @@ fn resolve_app_theme(config: &ThemeConfig) -> Box { border: overrides.border.unwrap_or_else(|| base.border()), surface: overrides.surface.unwrap_or_else(|| base.surface()), background: overrides.background.unwrap_or_else(|| base.background()), - }) + })) } -fn load_base_theme(name: &str) -> Box { +fn load_base_theme(name: &str) -> std::io::Result> { let path = if Path::new(name).is_absolute() { Some(std::path::PathBuf::from(name)) } else { @@ -147,20 +150,27 @@ fn load_base_theme(name: &str) -> Box { } }; - if let Some(path) = path - && let Ok(content) = std::fs::read_to_string(&path) - { - match toml::from_str::(&content) { - Ok(custom) => return Box::new(custom), - Err(e) => tracing::warn!( - "Failed to parse theme file {}: {e}. Theme files need top-level \ - name, id and accent keys (not nested under [theme]).", - path.display() - ), - } + if path.is_none() && ratatui_themekit::available_theme_ids().contains(&name) { + return Ok(resolve_theme(name)); } - - resolve_theme(name) + let path = path.unwrap_or_else(|| { + super::get_config_path() + .join("theme") + .join(format!("{name}.toml")) + }); + let content = std::fs::read_to_string(&path).map_err(|error| { + std::io::Error::new( + error.kind(), + format!("failed to load theme {}: {error}", path.display()), + ) + })?; + let custom = toml::from_str::(&content).map_err(|error| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("invalid theme {}: {error}", path.display()), + ) + })?; + Ok(Box::new(custom)) } pub struct ThemeStore(RwLock>); @@ -215,7 +225,11 @@ pub static THEME: LazyLock = LazyLock::new(|| { let config = THEME_CONFIG .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - ThemeStore(RwLock::new(Arc::from(resolve_app_theme(&config)))) + let theme = resolve_app_theme(&config).unwrap_or_else(|error| { + tracing::error!("Could not load theme: {error}"); + resolve_theme("catppuccin") + }); + ThemeStore(RwLock::new(Arc::from(theme))) }); pub static BORDER_STYLE: LazyLock = LazyLock::new(|| { @@ -233,10 +247,10 @@ pub fn current_theme_config() -> ThemeConfig { } pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<()> { - validate_theme_name(&theme)?; let mut config = current_theme_config(); config.theme = theme; config.border_style = border_style.clone(); + let resolved = resolve_app_theme(&config)?; super::write_merged_toml_document( &super::get_config_path().join("theme.toml"), &config, @@ -246,7 +260,7 @@ pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result< } }, )?; - THEME.set(resolve_app_theme(&config)); + THEME.set(resolved); BORDER_STYLE.set(border_style); *THEME_CONFIG .write() @@ -255,42 +269,13 @@ pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result< Ok(()) } -fn validate_theme_name(name: &str) -> std::io::Result<()> { - if ratatui_themekit::available_theme_ids().contains(&name) { - return Ok(()); - } - let path = if Path::new(name).is_absolute() { - std::path::PathBuf::from(name) - } else { - let directory = super::get_config_path().join("theme"); - let direct = directory.join(name); - if direct.exists() { - direct - } else { - directory.join(format!("{name}.toml")) - } - }; - let content = std::fs::read_to_string(&path).map_err(|error| { - std::io::Error::new( - error.kind(), - format!("failed to load theme {}: {error}", path.display()), - ) - })?; - toml::from_str::(&content).map_err(|error| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("invalid theme {}: {error}", path.display()), - ) - })?; - Ok(()) -} - pub fn reload_theme() -> std::io::Result<()> { let path = super::get_config_path().join("theme.toml"); let content = std::fs::read_to_string(path)?; let config: ThemeConfig = toml::from_str(&content) .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?; - THEME.set(resolve_app_theme(&config)); + let resolved = resolve_app_theme(&config)?; + THEME.set(resolved); BORDER_STYLE.set(config.border_style.clone()); *THEME_CONFIG .write() diff --git a/src/instance/config_sync.rs b/src/instance/config_sync.rs index e8755e3..de643f0 100644 --- a/src/instance/config_sync.rs +++ b/src/instance/config_sync.rs @@ -13,18 +13,34 @@ pub enum ConfigSyncError { InstanceRunning { instance: String }, #[error("Config profile '{0}' is in use by another instance")] ProfileInUse(String), + #[error("Config profile '{}' and local settings '{}' have diverged; both were kept", profile.display(), minecraft.display())] + Conflict { + profile: PathBuf, + minecraft: PathBuf, + }, #[error("IO error: {0}")] Io(#[from] std::io::Error), #[error("Failed to save config profile: {0}")] Save(String), - #[error("Failed to save config profile ({save}) and roll back profile files ({rollback})")] + #[error("Config sync failed ({save}) and rollback failed ({rollback})")] SaveRollback { save: String, rollback: String }, + #[error(transparent)] + Instance(#[from] crate::instance::InstanceError), } #[derive(Debug)] pub struct ConfigSyncLock { file: std::fs::File, profile_dir: PathBuf, + recovered_source: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +struct PayloadBaseline { + profile: PathBuf, + // External relative links are re-anchored on import, so these hashes can differ. + local: String, + shared: String, } impl Drop for ConfigSyncLock { @@ -54,22 +70,49 @@ pub fn prepare_for_launch( validate_profile(profile)?; let profile_dir = profile_dir(meta_dir, profile); - if !profile_dir.exists() { + if !profile_exists(&profile_dir)? { return Ok(None); } let lock = acquire_lock(&profile_dir)?; + prepare_locked(lock, minecraft_dir) +} - if !profile_payload_exists(&profile_dir)? { - sync_to_profile(minecraft_dir, &profile_dir)?; +fn prepare_locked( + lock: ConfigSyncLock, + minecraft_dir: &Path, +) -> Result, ConfigSyncError> { + let profile_dir = &lock.profile_dir; + if !profile_exists(profile_dir)? { + return Ok(None); + } + + if !profile_payload_exists(profile_dir)? { + publish_current(minecraft_dir, profile_dir, false)?; + persist_with_baseline(minecraft_dir, Some(profile_dir), || { + mark_unsynced(profile_dir, minecraft_dir) + })?; } else { - sync_from_profile(&profile_dir, minecraft_dir)?; + let identity = std::fs::canonicalize(profile_dir)?; + if read_baseline(minecraft_dir)?.is_some_and(|baseline| baseline.profile == identity) { + publish_current(minecraft_dir, profile_dir, false)?; + } + mirror_payload(profile_dir, minecraft_dir, true, || { + persist_with_baseline(minecraft_dir, Some(profile_dir), || { + mark_unsynced(profile_dir, minecraft_dir) + }) + })?; } Ok(Some(lock)) } pub fn finish_launch(lock: ConfigSyncLock, minecraft_dir: &Path) -> Result<(), ConfigSyncError> { - sync_to_profile(minecraft_dir, &lock.profile_dir) + let allow_untracked = match &lock.recovered_source { + Some(source) => std::fs::canonicalize(source)? == std::fs::canonicalize(minecraft_dir)?, + None => true, + }; + publish_current(minecraft_dir, &lock.profile_dir, allow_untracked)?; + remove_if_exists(&unsynced_marker(&lock.profile_dir)) } pub fn finish( @@ -83,14 +126,13 @@ pub fn finish( validate_profile(profile)?; let profile_dir = profile_dir(meta_dir, profile); - let _lock = acquire_lock(&profile_dir)?; - sync_to_profile(minecraft_dir, &profile_dir) + finish_launch(acquire_lock(&profile_dir)?, minecraft_dir) } pub fn list_profiles(meta_dir: &Path) -> Result, ConfigSyncError> { let root = profiles_dir(meta_dir); let mut profiles = Vec::new(); - if !root.exists() { + if !entry_exists(&root)? { return Ok(profiles); } @@ -112,6 +154,7 @@ pub fn create_profile(meta_dir: &Path, profile: &str) -> Result Result Result<(), ConfigSyncError> { validate_profile(profile)?; let dir = profile_dir(meta_dir, profile); - if dir.exists() { + if profile_exists(&dir)? { let _lock = acquire_lock(&dir)?; - remove_path(&dir)?; + if profile_exists(&dir)? { + remove_path(&dir)?; + } } Ok(()) } +#[cfg(test)] fn switch_profile( instance_name: &str, current_profile: Option<&str>, @@ -133,63 +179,14 @@ fn switch_profile( meta_dir: &Path, instance_dir: &Path, ) -> Result, ConfigSyncError> { - if crate::instance::runtime::is_active(instance_name) { - return Err(ConfigSyncError::InstanceRunning { - instance: instance_name.to_string(), - }); - } - - let current_profile = current_profile.and_then(normalize_profile); - let target_profile = target_profile.and_then(normalize_profile); - if let Some(profile) = current_profile { - validate_profile(profile)?; - } - if let Some(profile) = target_profile { - validate_profile(profile)?; - } - - if current_profile == target_profile { - return Ok(current_profile.map(str::to_string)); - } - - if let Some(profile) = current_profile { - let profile_dir = profile_dir(meta_dir, profile); - if profile_dir.exists() { - let _lock = acquire_lock(&profile_dir)?; - sync_to_profile(&minecraft_dir(instance_dir), &profile_dir)?; - } - } - - match (current_profile, target_profile) { - (None, Some(_)) => { - sync_to_profile( - &minecraft_dir(instance_dir), - &local_backup_dir(instance_dir), - )?; - } - (Some(_), None) => { - let backup = local_backup_dir(instance_dir); - if backup.exists() { - sync_from_profile(&backup, &minecraft_dir(instance_dir))?; - } - return Ok(None); - } - _ => {} - } - - let Some(profile) = target_profile else { - return Ok(None); - }; - - let profile_dir = profile_dir(meta_dir, profile); - let _lock = acquire_lock(&profile_dir)?; - - if !profile_payload_exists(&profile_dir)? { - sync_to_profile(&minecraft_dir(instance_dir), &profile_dir)?; - } - sync_from_profile(&profile_dir, &minecraft_dir(instance_dir))?; - - Ok(Some(profile.to_string())) + switch_profile_and_persist( + instance_name, + current_profile, + target_profile, + meta_dir, + instance_dir, + |_| Ok::<(), std::io::Error>(()), + ) } pub fn switch_profile_and_save( @@ -197,21 +194,24 @@ pub fn switch_profile_and_save( config: &mut crate::instance::InstanceConfig, target_profile: Option<&str>, ) -> Result<(), ConfigSyncError> { - let current_profile = config.config_sync_profile.clone(); - let instance_dir = manager.instances_dir.join(&config.name); - let selected = switch_profile_and_persist( - &config.name, - current_profile.as_deref(), + let _instance_lock = + crate::instance::runtime::lock_instance(&manager.instances_dir, &config.name)?; + let current = manager.load_one(&config.name)?; + let instance_dir = manager.instances_dir.join(¤t.name); + let mut saved = None; + switch_profile_and_persist( + ¤t.name, + current.config_sync_profile.as_deref(), target_profile, &manager.meta_dir, &instance_dir, |selected| { - let mut updated = config.clone(); - updated.config_sync_profile = selected.map(str::to_owned); - manager.save(&updated) + saved = + Some(manager.save_config_sync_profile(¤t.name, selected.map(str::to_owned))?); + Ok::<(), crate::instance::InstanceError>(()) }, )?; - config.config_sync_profile = selected; + *config = saved.expect("successful profile switch persisted its selection"); Ok(()) } @@ -226,31 +226,56 @@ fn switch_profile_and_persist( where E: std::fmt::Display, { - let selected = switch_profile( - instance_name, - current_profile, - target_profile, - meta_dir, - instance_dir, - )?; - let Err(save) = persist(selected.as_deref()) else { - return Ok(selected); - }; - let save = save.to_string(); - - if let Err(rollback) = switch_profile( - instance_name, - selected.as_deref(), - current_profile, - meta_dir, - instance_dir, - ) { - return Err(ConfigSyncError::SaveRollback { - save, - rollback: rollback.to_string(), + if crate::instance::runtime::is_active(instance_name) { + return Err(ConfigSyncError::InstanceRunning { + instance: instance_name.to_owned(), }); } - Err(ConfigSyncError::Save(save)) + let current = current_profile.and_then(normalize_profile); + let target = target_profile.and_then(normalize_profile); + for profile in [current, target].into_iter().flatten() { + validate_profile(profile)?; + profile_exists(&profile_dir(meta_dir, profile))?; + } + let save = + |selected| persist(selected).map_err(|error| ConfigSyncError::Save(error.to_string())); + if current == target { + save(current)?; + return Ok(current.map(str::to_owned)); + } + let minecraft = minecraft_dir(instance_dir); + if let Some(profile) = current { + let dir = profile_dir(meta_dir, profile); + if profile_exists(&dir)? { + let _lock = acquire_lock(&dir)?; + if profile_exists(&dir)? { + publish_current(&minecraft, &dir, false)?; + } + } + } + let local = local_backup_dir(instance_dir); + if current.is_none() && target.is_some() { + sync_to_profile(&minecraft, &local)?; + } + let Some(profile) = target else { + if current.is_some() && entry_exists(&local)? { + return mirror_payload(&local, &minecraft, true, || { + persist_with_baseline(&minecraft, None, || save(None))?; + Ok(None) + }); + } + persist_with_baseline(&minecraft, None, || save(None))?; + return Ok(None); + }; + let dir = profile_dir(meta_dir, profile); + let _lock = acquire_lock(&dir)?; + if !profile_payload_exists(&dir)? { + sync_to_profile(&minecraft, &dir)?; + } + mirror_payload(&dir, &minecraft, true, || { + persist_with_baseline(&minecraft, Some(&dir), || save(Some(profile)))?; + Ok(Some(profile.to_owned())) + }) } fn normalize_profile(profile: &str) -> Option<&str> { @@ -266,16 +291,12 @@ pub fn validate_profile(profile: &str) -> Result<(), ConfigSyncError> { if profile.is_empty() || profile.len() > 64 || profile.starts_with('.') - || profile.contains('/') - || profile.contains('\\') + || !crate::instance::manager::portable_component(profile) || profile.eq_ignore_ascii_case("default") || profile.eq_ignore_ascii_case("none") || profile.eq_ignore_ascii_case("local") || profile.eq_ignore_ascii_case("instance default") || profile.eq_ignore_ascii_case("local default") - || profile - .chars() - .any(|c| c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*')) { return Err(ConfigSyncError::InvalidProfile(profile.to_string())); } @@ -299,8 +320,18 @@ fn local_backup_dir(instance_dir: &Path) -> PathBuf { } fn acquire_lock(profile_dir: &Path) -> Result { - std::fs::create_dir_all(profile_dir)?; - let path = profile_dir.join(".lock"); + let parent = profile_dir + .parent() + .ok_or_else(|| std::io::Error::other("Config profile has no parent"))?; + std::fs::create_dir_all(parent)?; + // Keep locks outside deletable profiles so recreating a profile cannot bypass an old handle. + let path = parent.join(format!( + ".{}.lock", + profile_dir + .file_name() + .unwrap_or_default() + .to_string_lossy() + )); let file = std::fs::OpenOptions::new() .read(true) .write(true) @@ -320,171 +351,477 @@ fn acquire_lock(profile_dir: &Path) -> Result { } Err(std::fs::TryLockError::Error(error)) => return Err(error.into()), } - Ok(ConfigSyncLock { + let mut lock = ConfigSyncLock { file, profile_dir: profile_dir.to_owned(), - }) + recovered_source: None, + }; + profile_exists(profile_dir)?; + lock.recovered_source = recover_unsynced(profile_dir)?; + Ok(lock) } -fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { - let parent = dst.parent().filter(|p| !p.as_os_str().is_empty()); - let Some(parent) = parent else { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!("no parent directory for {}", dst.display()), - ) - .into()); +fn unsynced_marker(profile: &Path) -> PathBuf { + profile.join(".unsynced.json") +} + +fn mark_unsynced(profile: &Path, minecraft: &Path) -> Result<(), ConfigSyncError> { + let source = std::path::absolute(minecraft)?; + if !std::fs::metadata(&source)?.is_dir() { + return Err(std::io::Error::other("Config sync source is not a directory").into()); + } + let bytes = serde_json::to_vec(&source).map_err(std::io::Error::other)?; + crate::storage::write_atomic(&unsynced_marker(profile), &bytes)?; + Ok(()) +} + +fn recover_unsynced(profile: &Path) -> Result, ConfigSyncError> { + let marker = unsynced_marker(profile); + let bytes = match std::fs::read(&marker) { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), }; - 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()) { + let source: PathBuf = serde_json::from_slice(&bytes).map_err(|error| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Invalid config sync marker '{}': {error}", marker.display()), + ) + })?; + if !source.is_absolute() || !std::fs::metadata(&source)?.is_dir() { return Err(std::io::Error::other(format!( - "Cannot replace symlinked config directory '{}'", - dst.display() + "Invalid unsynced config source '{}'", + source.display() )) .into()); } - if backup.exists() { + publish_current(&source, profile, true)?; + std::fs::remove_file(marker)?; + Ok(Some(source)) +} + +fn baseline_path(minecraft: &Path) -> Result { + let instance = minecraft + .parent() + .ok_or_else(|| std::io::Error::other("Config sync source has no parent"))?; + Ok(crate::storage::InstancePaths::new(instance) + .state() + .join("config-sync.json")) +} + +fn read_baseline(minecraft: &Path) -> Result, ConfigSyncError> { + let path = baseline_path(minecraft)?; + match std::fs::read(&path) { + Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|error| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Invalid config sync baseline '{}': {error}", path.display()), + ) + .into() + }), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error.into()), + } +} + +fn baseline_bytes( + profile: &Path, + local: String, + shared: String, +) -> Result, ConfigSyncError> { + let baseline = PayloadBaseline { + profile: std::fs::canonicalize(profile)?, + local, + shared, + }; + Ok(serde_json::to_vec(&baseline).map_err(std::io::Error::other)?) +} + +fn persist_with_baseline( + minecraft: &Path, + profile: Option<&Path>, + persist: impl FnOnce() -> Result, +) -> Result { + let path = baseline_path(minecraft)?; + let previous = match std::fs::read(&path) { + Ok(bytes) => Some(bytes), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(error.into()), + }; + if let Some(profile) = profile { + crate::storage::write_atomic( + &path, + &baseline_bytes(profile, payload_hash(minecraft)?, payload_hash(profile)?)?, + )?; + } else { + remove_if_exists(&path)?; + } + match persist() { + Ok(value) => Ok(value), + Err(error) => { + let rollback = match previous { + Some(bytes) => { + crate::storage::write_atomic(&path, &bytes).map_err(ConfigSyncError::from) + } + None => remove_if_exists(&path), + }; + match rollback { + Ok(()) => Err(error), + Err(rollback) => Err(ConfigSyncError::SaveRollback { + save: error.to_string(), + rollback: format!("Restoring baseline '{}': {rollback}", path.display()), + }), + } + } + } +} + +fn publish_current( + minecraft: &Path, + profile: &Path, + allow_untracked: bool, +) -> Result<(), ConfigSyncError> { + let local = payload_hash(minecraft)?; + let shared = payload_hash(profile)?; + let identity = std::fs::canonicalize(profile)?; + let baseline = read_baseline(minecraft)?.filter(|baseline| baseline.profile == identity); + let needs_export = local != shared; + if needs_export { + match baseline { + Some(baseline) if local == baseline.local => return Ok(()), + Some(baseline) if shared == baseline.shared => {} + None if allow_untracked || !profile_payload_exists(profile)? => {} + _ => { + return Err(ConfigSyncError::Conflict { + profile: profile.to_owned(), + minecraft: minecraft.to_owned(), + }); + } + } + } + let persist = |shared| { + crate::storage::write_atomic( + &baseline_path(minecraft)?, + &baseline_bytes(profile, local, shared)?, + )?; + Ok(()) + }; + if needs_export { + mirror_payload(minecraft, profile, true, || persist(payload_hash(profile)?)) + } else { + persist(shared) + } +} + +fn payload_hash(dir: &Path) -> Result { + use sha2::Digest; + require_source_dir(dir)?; + check_config_root(dir)?; + let mut hash = sha2::Sha256::new(); + for name in payload_names(dir, true)? { + hash_payload_entry(&dir.join(name), dir, &mut hash)?; + } + Ok(format!("{:x}", hash.finalize())) +} + +fn hash_payload_entry( + path: &Path, + root: &Path, + hash: &mut sha2::Sha256, +) -> Result<(), ConfigSyncError> { + use sha2::Digest; + let relative = path.strip_prefix(root).map_err(std::io::Error::other)?; + let bytes = relative.as_os_str().as_encoded_bytes(); + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); + let kind = std::fs::symlink_metadata(path)?.file_type(); + if kind.is_symlink() { + hash.update(b"link"); + #[cfg(windows)] + { + use std::os::windows::fs::FileTypeExt; + hash.update([u8::from(kind.is_symlink_dir())]); + } + let target = std::fs::read_link(path)?; + let bytes = target.as_os_str().as_encoded_bytes(); + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); + } else if kind.is_file() { + hash.update(b"file"); + hash.update( + crate::instance::content::manifest::fingerprint(path)?.hashes["sha512"].as_bytes(), + ); + } else if kind.is_dir() { + hash.update(b"dir"); + let mut entries = std::fs::read_dir(path)? + .map(|entry| entry.map(|entry| entry.path())) + .collect::, _>>()?; + entries.sort(); + for entry in entries { + hash_payload_entry(&entry, root, hash)?; + } + } else { + return Err(std::io::Error::other(format!( + "Unsupported config entry '{}'", + path.display() + )) + .into()); + } + Ok(()) +} + +fn profile_exists(dir: &Path) -> Result { + match std::fs::symlink_metadata(dir) { + Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!( + "Config profile must be a real directory: '{}'", + dir.display() + ), + ) + .into()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error.into()), + } +} + +fn require_source_dir(src: &Path) -> Result<(), ConfigSyncError> { + let metadata = std::fs::metadata(src).map_err(|error| { + std::io::Error::new( + error.kind(), + format!( + "Cannot read config sync source '{}': {error}", + src.display() + ), + ) + })?; + if !metadata.is_dir() { return Err(std::io::Error::new( - std::io::ErrorKind::AlreadyExists, - format!("Previous config backup remains at {}", backup.display()), + std::io::ErrorKind::InvalidInput, + format!("Config sync source is not a directory: '{}'", src.display()), ) .into()); } - if staging.exists() { - remove_path(&staging)?; - } - std::fs::create_dir_all(&staging)?; + Ok(()) +} - let result = (|| { - if src.exists() { - copy_dir_contents(src, &staging)?; - } - 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() - ); - } - Ok(()) - })(); - - if result.is_err() { - let _ = std::fs::remove_dir_all(&staging); +fn check_config_root(dir: &Path) -> Result<(), ConfigSyncError> { + let config = dir.join("config"); + if entry_exists(&config)? && std::fs::symlink_metadata(&config)?.file_type().is_symlink() { + return Err(std::io::Error::other(format!( + "Cannot mirror symlinked config directory '{}'", + config.display() + )) + .into()); } - result + Ok(()) } fn sync_to_profile(minecraft_dir: &Path, profile_dir: &Path) -> Result<(), ConfigSyncError> { - mirror_dir(&minecraft_dir.join("config"), &profile_dir.join("config"))?; - mirror_options(minecraft_dir, profile_dir) + mirror_payload(minecraft_dir, profile_dir, true, || Ok(())) } +#[cfg(test)] fn sync_from_profile(profile_dir: &Path, minecraft_dir: &Path) -> Result<(), ConfigSyncError> { - mirror_dir(&profile_dir.join("config"), &minecraft_dir.join("config"))?; - mirror_options(profile_dir, minecraft_dir) + mirror_payload(profile_dir, minecraft_dir, true, || Ok(())) } fn profile_payload_exists(profile_dir: &Path) -> Result { - if profile_dir.join("config").exists() { - return Ok(true); - } - if !profile_dir.exists() { - return Ok(false); - } - for entry in std::fs::read_dir(profile_dir)? { - let entry = entry?; - if (entry.file_type()?.is_file() || entry.file_type()?.is_symlink()) - && is_options_file(&entry.file_name().to_string_lossy()) - { - return Ok(true); - } - } - Ok(false) + Ok(!payload_names(profile_dir, true)?.is_empty()) } +#[cfg(test)] fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { - std::fs::create_dir_all(dst)?; - let staging = dst.join(".rmcl-options-stage"); - if staging.exists() { - remove_path(&staging)?; - } - 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() { - crate::storage::copy_symlink(&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?; - std::fs::rename(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() - ); - } - result + mirror_payload(src, dst, false, || Ok(())) } -fn remove_options( - dir: &Path, - copied: &std::collections::HashSet, -) -> Result<(), ConfigSyncError> { - if !dir.exists() { - return Ok(()); +fn entry_exists(path: &Path) -> Result { + match std::fs::symlink_metadata(path) { + Ok(_) => Ok(true), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error.into()), } +} - for entry in std::fs::read_dir(dir)? { - let entry = entry?; - if is_options_file(&entry.file_name().to_string_lossy()) - && !copied.contains(&entry.file_name()) - { - remove_path(&entry.path())?; - } +fn remove_if_exists(path: &Path) -> Result<(), ConfigSyncError> { + if entry_exists(path)? { + remove_path(path)?; } Ok(()) } +fn cleanup_sync_path(path: &Path) { + if let Err(error) = remove_if_exists(path) { + tracing::warn!( + "Could not remove config sync staging/backup '{}': {error}", + path.display() + ); + } +} + +fn payload_names( + dir: &Path, + include_config: bool, +) -> Result, ConfigSyncError> { + if !entry_exists(dir)? { + return Ok(Vec::new()); + } + let mut names = Vec::new(); + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let name = entry.file_name(); + let kind = entry.file_type()?; + if include_config && name == "config" + || is_options_file(&name.to_string_lossy()) && (kind.is_file() || kind.is_symlink()) + { + names.push(name); + } + } + names.sort(); + Ok(names) +} + +fn rollback_payload( + dst: &Path, + backup: &Path, + installed: &[std::ffi::OsString], + moved: &[std::ffi::OsString], +) -> Result<(), String> { + let mut errors = Vec::new(); + for name in installed.iter().rev() { + if let Err(error) = remove_if_exists(&dst.join(name)) { + errors.push(format!("Removing '{}': {error}", dst.join(name).display())); + } + } + for name in moved.iter().rev() { + let target = dst.join(name); + match entry_exists(&target) { + Ok(false) => { + if let Err(error) = std::fs::rename(backup.join(name), &target) { + errors.push(format!("Restoring '{}': {error}", target.display())); + } + } + Ok(true) => errors.push(format!("Cannot restore occupied '{}'", target.display())), + Err(error) => errors.push(format!("Inspecting '{}': {error}", target.display())), + } + } + if errors.is_empty() { + Ok(()) + } else { + Err(errors.join("; ")) + } +} + +fn mirror_payload( + src: &Path, + dst: &Path, + include_config: bool, + commit: impl FnOnce() -> Result, +) -> Result { + require_source_dir(src)?; + let parent = dst + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .ok_or_else(|| std::io::Error::other(format!("No parent for '{}'", dst.display())))?; + std::fs::create_dir_all(dst)?; + if include_config { + check_config_root(src)?; + check_config_root(dst)?; + let old_backup = dst.join(".config.mirror-backup"); + if entry_exists(&old_backup)? { + return Err(std::io::Error::other(format!( + "Previous config backup remains at '{}'", + old_backup.display() + )) + .into()); + } + } + let name = dst + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("payload"); + let staging = parent.join(format!(".{name}.sync-stage")); + let backup = parent.join(format!(".{name}.sync-backup")); + // An existing backup belongs to an interrupted transaction and must survive for recovery. + std::fs::create_dir(&backup).map_err(|error| { + std::io::Error::new( + error.kind(), + format!("Cannot create backup '{}': {error}", backup.display()), + ) + })?; + let mut moved = Vec::new(); + let mut installed = Vec::new(); + let result = (|| { + remove_if_exists(&staging)?; + std::fs::create_dir(&staging)?; + if include_config { + std::fs::create_dir(staging.join("config"))?; + if entry_exists(&src.join("config"))? { + copy_dir_contents( + &src.join("config"), + &staging.join("config"), + src, + include_config, + )?; + } + } + for name in payload_names(src, false)? { + let source = src.join(&name); + let target = staging.join(&name); + if std::fs::symlink_metadata(&source)?.file_type().is_symlink() { + copy_payload_symlink(&source, &target, src, include_config)?; + } else { + std::fs::copy(&source, &target)?; + } + } + for name in payload_names(dst, include_config)? { + std::fs::rename(dst.join(&name), backup.join(&name))?; + moved.push(name); + } + for name in payload_names(&staging, include_config)? { + std::fs::rename(staging.join(&name), dst.join(&name))?; + installed.push(name); + } + commit() + })(); + let result = match result { + Ok(value) => { + cleanup_sync_path(&backup); + Ok(value) + } + Err(error) => match rollback_payload(dst, &backup, &installed, &moved) { + Ok(()) => { + cleanup_sync_path(&backup); + Err(error) + } + Err(rollback) => Err(ConfigSyncError::SaveRollback { + save: error.to_string(), + rollback: format!( + "{rollback}; recovery backup retained at '{}'", + backup.display() + ), + }), + }, + }; + cleanup_sync_path(&staging); + result +} + fn is_options_file(name: &str) -> bool { name == "options.txt" || name.starts_with("options") && name.ends_with(".txt") } fn remove_path(path: &Path) -> Result<(), ConfigSyncError> { let meta = std::fs::symlink_metadata(path)?; + #[cfg(windows)] + { + use std::os::windows::fs::FileTypeExt; + if meta.file_type().is_symlink_dir() { + std::fs::remove_dir(path)?; + return Ok(()); + } + } if meta.is_dir() { std::fs::remove_dir_all(path)?; } else { @@ -493,7 +830,12 @@ fn remove_path(path: &Path) -> Result<(), ConfigSyncError> { Ok(()) } -fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { +fn copy_dir_contents( + src: &Path, + dst: &Path, + payload: &Path, + include_config: bool, +) -> Result<(), ConfigSyncError> { for entry in std::fs::read_dir(src)? { let entry = entry?; let source = entry.path(); @@ -502,17 +844,83 @@ fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { if file_type.is_dir() { std::fs::create_dir_all(&target)?; - copy_dir_contents(&source, &target)?; + copy_dir_contents(&source, &target, payload, include_config)?; } else if file_type.is_file() { std::fs::copy(&source, &target)?; } else if file_type.is_symlink() { - crate::storage::copy_symlink(&source, &target)?; + copy_payload_symlink(&source, &target, payload, include_config)?; } } Ok(()) } +fn copy_payload_symlink( + source: &Path, + destination: &Path, + payload: &Path, + include_config: bool, +) -> Result<(), ConfigSyncError> { + let mut target = std::fs::read_link(source)?; + if target.is_relative() { + let relative = source + .strip_prefix(payload) + .map_err(std::io::Error::other)?; + let mut position = relative.parent().unwrap_or(Path::new("")).to_owned(); + let mut internal = true; + for component in target.components() { + match component { + std::path::Component::Normal(name) => position.push(name), + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + if !position.pop() { + internal = false; + break; + } + } + _ => { + internal = false; + break; + } + } + if let Some(first) = position.components().next() { + let name = first.as_os_str(); + if include_config && name == "config" { + continue; + } + if !is_options_file(&name.to_string_lossy()) { + internal = false; + break; + } + match std::fs::symlink_metadata(payload.join(name)) { + Ok(metadata) if metadata.is_file() || metadata.file_type().is_symlink() => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + _ => { + internal = false; + break; + } + } + } + } + internal &= !position.as_os_str().is_empty(); + if !internal { + // External links keep their source anchor; internal links move with the payload. + let anchored = std::path::absolute(source.parent().unwrap().join(target))?; + target = match (anchored.parent(), anchored.file_name()) { + (Some(parent), Some(name)) => match std::fs::canonicalize(parent) { + Ok(parent) => parent.join(name), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => anchored, + Err(error) => return Err(error.into()), + }, + _ => std::fs::canonicalize(anchored)?, + }; + } + } + crate::storage::copy_symlink_target(source, destination, &target)?; + Ok(()) +} + #[cfg(test)] #[path = "tests/config_sync.rs"] mod tests; diff --git a/src/instance/desktop.rs b/src/instance/desktop.rs index 4e07d3b..391aba2 100644 --- a/src/instance/desktop.rs +++ b/src/instance/desktop.rs @@ -76,32 +76,95 @@ fn legacy_path(name: &str) -> Option { } 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)) - }) + let Ok(existing) = read_shortcut(path) else { + return false; + }; + let marker = shortcut_marker(name); + if existing.lines().any(|line| line == marker) { + return true; + } + #[cfg(target_os = "linux")] + let commands = { + let quoted = quote_desktop_exec_arg(name); + [ + format!("Exec=rmcl instance launch {quoted}"), + format!( + "Exec=rmcl instance launch {}", + quoted.replace("\\\\", "\\").replace("%%", "%") + ), + ] + }; + #[cfg(target_os = "windows")] + let commands = { + let command = + format!("rmcl instance launch {}", quote_windows_arg(name)).replace('"', "\"\""); + [format!("shell.Run \"{command}\", 0, False")] + }; + #[cfg(target_os = "macos")] + let commands = [format!("rmcl instance launch {}", quote_shell_arg(name))]; + #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] + let commands: [String; 0] = []; + existing + .lines() + .any(|line| commands.iter().any(|command| line == command)) } +fn read_shortcut(path: &Path) -> std::io::Result { + let bytes = std::fs::read(path)?; + if let Some(bytes) = bytes.strip_prefix(&[0xff, 0xfe]) { + if bytes.len() % 2 != 0 { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "Invalid UTF-16 shortcut", + )); + } + let units = bytes + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) + .collect::>(); + String::from_utf16(&units) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error)) + } else { + String::from_utf8(bytes) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error)) + } +} + +#[cfg(any(windows, test))] +fn windows_script_bytes(content: &str) -> Vec { + // Windows Script Host reads Unicode scripts as BOM-prefixed UTF-16, not UTF-8. + [0xfeff] + .into_iter() + .chain(content.encode_utf16()) + .flat_map(u16::to_le_bytes) + .collect() +} + +fn shortcut_marker(name: &str) -> String { + let prefix = if cfg!(windows) { "'" } else { "#" }; + format!("{prefix} rmcl-instance: {}", shortcut_name(name)) +} pub fn exists(name: &str) -> bool { 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 { + crate::instance::manager::validate_name(&config.name).map_err(std::io::Error::other)?; 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()), - )); + match std::fs::symlink_metadata(&path) { + Ok(_) if !owns_legacy_shortcut(&path, &config.name) => { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + format!("Another shortcut already exists at '{}'", path.display()), + )); + } + Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error), + _ => {} } if let Some(parent) = path.parent() { @@ -109,9 +172,22 @@ pub fn create(config: &InstanceConfig) -> std::io::Result { } let icon = ensure_icon(); - let content = build_content(&config.name, icon.as_deref()); - if std::fs::read_to_string(&path).ok().as_deref() != Some(content.as_str()) { - crate::storage::write_atomic(&path, content.as_bytes())?; + let executable = std::env::current_exe()?; + let executable = executable.to_str().ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + "Launcher executable path is not UTF-8", + ) + })?; + let content = build_content(&config.name, icon.as_deref(), executable); + if read_shortcut(&path).ok().as_deref() != Some(content.as_str()) { + #[cfg(windows)] + let encoded = windows_script_bytes(&content); + #[cfg(windows)] + let bytes = encoded.as_slice(); + #[cfg(not(windows))] + let bytes = content.as_bytes(); + crate::storage::write_atomic(&path, bytes)?; } #[cfg(unix)] @@ -164,6 +240,19 @@ pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<() return Ok(()); } let same_path = desktop_path(old_name) == desktop_path(&new_config.name); + if !same_path && let Some(new_path) = desktop_path(&new_config.name) { + for old_path in [desktop_path(old_name), legacy_path(old_name)] + .into_iter() + .flatten() + { + if rename_shortcut_alias(&old_path, &new_path, old_name, || { + create(new_config).map(|_| ()) + })? { + remove(old_name)?; + return Ok(()); + } + } + } create(new_config)?; if !same_path { remove(old_name)?; @@ -171,41 +260,77 @@ pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<() Ok(()) } -fn build_content(name: &str, icon: Option<&Path>) -> String { +fn rename_shortcut_alias( + old_path: &Path, + new_path: &Path, + old_name: &str, + create: impl FnOnce() -> std::io::Result<()>, +) -> std::io::Result { + if old_path == new_path + || !owns_legacy_shortcut(old_path, old_name) + || !crate::instance::manager::paths_alias(old_path, new_path)? + { + return Ok(false); + } + let temporary = tempfile::Builder::new() + .prefix(".rmcl-shortcut-") + .tempdir_in( + old_path + .parent() + .ok_or_else(|| std::io::Error::other("Shortcut has no parent"))?, + )?; + let original = temporary.path().join("original"); + std::fs::rename(old_path, &original)?; + if let Err(error) = create() { + if let Err(rollback) = std::fs::rename(&original, old_path) { + let retained = temporary.keep(); + return Err(std::io::Error::other(format!( + "Could not update shortcut: {error}; rollback failed: {rollback}; original retained at '{}'", + retained.join("original").display(), + ))); + } + return Err(error); + } + Ok(true) +} + +fn build_content(name: &str, icon: Option<&Path>, executable: &str) -> String { #[cfg(target_os = "linux")] { - build_linux_desktop(name, icon) + build_linux_desktop(name, icon, executable) } #[cfg(target_os = "windows")] { let _ = icon; - build_windows_shortcut(name) + build_windows_shortcut(name, executable) } #[cfg(target_os = "macos")] { let _ = icon; - build_macos_command(name) + build_macos_command(name, executable) } #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] { - let _ = (name, icon); + let _ = (name, icon, executable); String::new() } } -#[cfg(target_os = "linux")] -fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String { +#[cfg(any(target_os = "linux", test))] +fn build_linux_desktop(name: &str, icon: Option<&Path>, executable: &str) -> String { let mut out = String::new(); out.push_str("[Desktop Entry]\n"); - out.push_str("Version=0.3.1\n"); + out.push_str("Version=1.0\n"); out.push_str("Type=Application\n"); out.push_str(&format!("Name=Minecraft - {name}\n")); out.push_str(&format!("Comment=Launch {name} Minecraft instance\n")); + out.push_str(&format!("# rmcl-instance: {}\n", shortcut_name(name))); out.push_str(&format!( - "Exec=rmcl instance launch {}\n", + "Exec={} instance launch {}\n", + quote_desktop_exec_arg(executable), quote_desktop_exec_arg(name) )); if let Some(icon) = icon { @@ -216,26 +341,38 @@ fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String { out } -#[cfg(target_os = "windows")] -fn build_windows_shortcut(name: &str) -> String { - let command = format!("rmcl instance launch {}", quote_windows_arg(name)); - let escaped_command = command.replace('"', "\"\""); - - let mut out = String::new(); - out.push_str("Set shell = CreateObject(\"WScript.Shell\")\r\n"); - out.push_str(&format!("shell.Run \"{escaped_command}\", 0, False\r\n")); +#[cfg(any(target_os = "windows", test))] +fn build_windows_shortcut(name: &str, executable: &str) -> String { + let arguments = format!("instance launch {}", quote_windows_arg(name)); + let mut out = format!("' rmcl-instance: {}\r\n", shortcut_name(name)); + out.push_str(&windows_shell_execute(executable, &arguments)); out } -#[cfg(target_os = "macos")] -fn build_macos_command(name: &str) -> String { +#[cfg(any(target_os = "windows", test))] +fn windows_shell_execute(executable: &str, arguments: &str) -> String { + // ShellExecute passes parameters literally; WScript.Shell.Run expands %VAR% in them. + format!( + "Set shell = CreateObject(\"Shell.Application\")\r\nshell.ShellExecute \"{}\", \"{}\", \"\", \"open\", 0\r\n", + executable.replace('"', "\"\""), + arguments.replace('"', "\"\"") + ) +} + +#[cfg(any(target_os = "macos", test))] +fn build_macos_command(name: &str, executable: &str) -> String { let mut out = String::new(); out.push_str("#!/bin/bash\n"); - out.push_str(&format!("# Launch Minecraft instance: {name}\n")); - out.push_str(&format!("rmcl instance launch {}\n", quote_shell_arg(name))); + out.push_str(&format!("# rmcl-instance: {}\n", shortcut_name(name))); + out.push_str(&format!( + "{} instance launch {}\n", + quote_shell_arg(executable), + quote_shell_arg(name) + )); out } +#[cfg(any(target_os = "linux", test))] fn quote_desktop_exec_arg(value: &str) -> String { let mut escaped = String::with_capacity(value.len() + 2); escaped.push('"'); @@ -246,7 +383,7 @@ fn quote_desktop_exec_arg(value: &str) -> String { escaped.push(character); } escaped.push('"'); - escaped + escaped.replace('\\', "\\\\").replace('%', "%%") } #[cfg(any(target_os = "macos", test))] diff --git a/src/instance/import/archive.rs b/src/instance/import/archive.rs index 4f421bf..d7df6e0 100644 --- a/src/instance/import/archive.rs +++ b/src/instance/import/archive.rs @@ -32,7 +32,13 @@ fn relative_path( let relative = enclosed .strip_prefix(root) .map_err(|_| format!("Invalid override path: {}", entry.name()))?; - Ok(Some(relative.to_owned())) + if relative.as_os_str().is_empty() { + return Ok(Some(relative.to_owned())); + } + let relative = relative + .to_str() + .ok_or_else(|| "Override path is not UTF-8".to_owned())?; + Ok(Some(PathBuf::from(super::portable_pack_path(relative)?))) } pub(super) fn override_files(path: &Path, roots: &[&str]) -> Result, String> { diff --git a/src/instance/import/curseforge.rs b/src/instance/import/curseforge.rs index 29d1c50..2cafd44 100644 --- a/src/instance/import/curseforge.rs +++ b/src/instance/import/curseforge.rs @@ -114,6 +114,7 @@ pub async fn execute_import( manager: &InstanceManager, config: &InstanceConfig, ) -> Result<(), Box> { + crate::instance::manager::validate_name(&config.name)?; let minecraft_dir = manager .instances_dir .join(&config.name) @@ -210,8 +211,9 @@ pub(super) async fn owned_files(path: &Path) -> Result, .iter() .find(|file| file.primary) .or_else(|| version.files.first()) - .map(|file| std::path::PathBuf::from("mods").join(&file.filename)) .ok_or_else(|| format!("CurseForge file '{}' has no artifact", version.id)) + .and_then(|file| super::portable_pack_path(&format!("mods/{}", file.filename))) + .map(std::path::PathBuf::from) }) .collect::>()?; files.extend(overrides); diff --git a/src/instance/import/mmc.rs b/src/instance/import/mmc.rs index 02a5253..e967cc5 100644 --- a/src/instance/import/mmc.rs +++ b/src/instance/import/mmc.rs @@ -95,6 +95,7 @@ pub async fn execute_import( manager: &InstanceManager, config: &crate::instance::InstanceConfig, ) -> Result<(), Box> { + crate::instance::manager::validate_name(&config.name)?; tracing::info!( "Importing MultiMC/Prism pack '{}' as instance '{}'", summary.name, @@ -159,13 +160,20 @@ fn extract_mmc_archive( ) })?; + let relative = if relative.as_os_str().is_empty() { + std::path::PathBuf::new() + } else { + std::path::PathBuf::from(super::portable_pack_path( + relative.to_str().ok_or("Archive path is not UTF-8")?, + )?) + }; if relative.as_os_str().is_empty() || entry_name.ends_with('/') { - std::fs::create_dir_all(minecraft_dir.join(relative))?; + std::fs::create_dir_all(minecraft_dir.join(&relative))?; dirs += 1; continue; } - let dest = minecraft_dir.join(relative); + let dest = minecraft_dir.join(&relative); if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent)?; } diff --git a/src/instance/import/mod.rs b/src/instance/import/mod.rs index 0fa02a3..8c0883a 100644 --- a/src/instance/import/mod.rs +++ b/src/instance/import/mod.rs @@ -31,15 +31,6 @@ pub enum ImportInput { pub fn parse_import_input(input: &str) -> ImportInput { let input = input.trim(); - if input.ends_with(".mrpack") - || input.ends_with(".zip") - || input.starts_with('/') - || input.starts_with("~/") - { - tracing::debug!("Import input resolved as local file: {}", input); - return ImportInput::LocalFile(input.to_string()); - } - if let Some(rest) = input .strip_prefix("https://modrinth.com/modpack/") .or_else(|| input.strip_prefix("http://modrinth.com/modpack/")) @@ -57,6 +48,22 @@ pub fn parse_import_input(input: &str) -> ImportInput { return parsed; } + if input.rsplit_once('.').is_some_and(|(_, extension)| { + extension.eq_ignore_ascii_case("mrpack") || extension.eq_ignore_ascii_case("zip") + }) || input.starts_with('/') + || input.starts_with("~/") + || input.starts_with("./") + || input.starts_with("../") + || input.contains('\\') + || input + .as_bytes() + .get(..2) + .is_some_and(|prefix| prefix[0].is_ascii_alphabetic() && prefix[1] == b':') + { + tracing::debug!("Import input resolved as local file: {}", input); + return ImportInput::LocalFile(input.to_string()); + } + tracing::debug!("Import input resolved as Modrinth project slug: {}", input); ImportInput::ProjectSlug(input.to_string()) } @@ -133,22 +140,27 @@ pub fn build_summary(path: &Path) -> Result { Ok(summary) } -pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String { +pub fn unique_instance_name( + base: &str, + instances_dir: &Path, +) -> Result { + crate::instance::manager::validate_name(base)?; let candidate = base.to_string(); if !instances_dir.join(&candidate).exists() { tracing::trace!("Import instance name '{}' is available", candidate); - return candidate; + return Ok(candidate); } let mut n = 2; loop { let candidate = format!("{base} ({n})"); + crate::instance::manager::validate_name(&candidate)?; if !instances_dir.join(&candidate).exists() { tracing::debug!( "Import instance name '{}' collided; using '{}'", base, candidate ); - return candidate; + return Ok(candidate); } n += 1; } @@ -164,7 +176,8 @@ pub async fn execute_import( summary.name, summary.archive_path.display() ); - let name = unique_instance_name(&summary.name, &manager.instances_dir); + let name = unique_instance_name(&summary.name, &manager.instances_dir) + .inspect_err(|_| crate::feedback::progress::clear())?; crate::feedback::progress::set_action(format!("Importing '{name}'...")); crate::feedback::progress::set_sub_action(format!( "{} {}", @@ -271,6 +284,10 @@ async fn owned_files(summary: &ImportSummary) -> Result, String> { } fn cleanup_failed_import(manager: &InstanceManager, name: &str) { + if let Err(error) = crate::instance::manager::validate_name(name) { + tracing::warn!("Refusing to clean up an invalid imported instance: {error}"); + return; + } let instance_dir = manager.instances_dir.join(name); if let Err(error) = std::fs::remove_dir_all(&instance_dir) && error.kind() != std::io::ErrorKind::NotFound @@ -283,6 +300,18 @@ fn cleanup_failed_import(manager: &InstanceManager, name: &str) { } } +pub(super) fn portable_pack_path(path: &str) -> Result { + let normalized = path.replace('\\', "/"); + if !crate::storage::safe_relative_path(Path::new(&normalized)) + || !normalized + .split('/') + .all(crate::instance::manager::portable_component) + { + return Err(format!("Unsafe pack-owned path: {path:?}")); + } + Ok(normalized) +} + #[cfg(test)] #[path = "../tests/import/format_detection.rs"] mod tests; diff --git a/src/instance/import/mrpack.rs b/src/instance/import/mrpack.rs index e2e39f1..681fab0 100644 --- a/src/instance/import/mrpack.rs +++ b/src/instance/import/mrpack.rs @@ -150,6 +150,7 @@ pub async fn execute_import( manager: &InstanceManager, config: &crate::instance::InstanceConfig, ) -> Result<(), Box> { + crate::instance::manager::validate_name(&config.name)?; tracing::info!( "Importing Modrinth pack '{}' as instance '{}'", summary.name, @@ -251,14 +252,11 @@ async fn download_mod_files( } fn safe_mrpack_path(path: &str) -> Result { - let path = Path::new(path); - if !crate::storage::safe_relative_path(path) { - return Err(crate::net::NetError::Parse(format!( - "Unsafe .mrpack file path '{}'", - path.display() - ))); - } - Ok(path.to_owned()) + super::portable_pack_path(path) + .map(PathBuf::from) + .map_err(|error| { + crate::net::NetError::Parse(format!("Unsafe .mrpack file path '{path}': {error}")) + }) } pub(super) fn owned_files(path: &Path) -> Result, String> { @@ -298,8 +296,8 @@ fn seed_content_manifest( ) -> Result<(), Box> { let mut manifest = ContentManifest::default(); for file in index.client_files() { - let relative_path = Path::new(&file.path); - let Some(kind) = mrpack_content_kind(relative_path) else { + let relative_path = safe_mrpack_path(&file.path)?; + let Some(kind) = mrpack_content_kind(&relative_path) else { continue; }; let Some((project_id, version_id)) = file.downloads.iter().find_map(|url| { @@ -314,7 +312,7 @@ fn seed_content_manifest( let Some(expected_sha512) = file.hashes.get("sha512") else { continue; }; - let file_fingerprint = fingerprint(&paths.minecraft().join(relative_path))?; + let file_fingerprint = fingerprint(&paths.minecraft().join(&relative_path))?; if file_fingerprint .hash("sha512") .is_none_or(|actual| !actual.eq_ignore_ascii_case(expected_sha512)) @@ -326,7 +324,7 @@ fn seed_content_manifest( continue; } manifest.upsert(ContentFileRecord { - relative_path: relative_path.to_owned(), + relative_path, kind, enabled: true, fingerprint: file_fingerprint, diff --git a/src/instance/import/refresh.rs b/src/instance/import/refresh.rs index 7eaa110..a208d5c 100644 --- a/src/instance/import/refresh.rs +++ b/src/instance/import/refresh.rs @@ -16,14 +16,34 @@ use super::ImportSummary; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PackState { pub source: ProviderProject, + #[serde( + serialize_with = "serialize_owned_paths", + deserialize_with = "deserialize_owned_paths" + )] pub files: Vec, } impl PackState { pub fn load(paths: &InstancePaths) -> Option { - std::fs::read(paths.modpack_state()) - .ok() - .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + let path = paths.modpack_state(); + let bytes = match std::fs::read(&path) { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return None, + Err(error) => { + tracing::warn!( + "Could not read pack ownership '{}': {error}", + path.display() + ); + return None; + } + }; + match serde_json::from_slice(&bytes) { + Ok(state) => Some(state), + Err(error) => { + tracing::warn!("Invalid pack ownership '{}': {error}", path.display()); + None + } + } } pub fn save(&self, paths: &InstancePaths) -> Result<(), String> { @@ -33,22 +53,88 @@ impl PackState { } } +fn serialize_owned_paths( + paths: &[PathBuf], + serializer: S, +) -> Result { + let paths = paths + .iter() + .map(|path| { + path.to_str() + .ok_or_else(|| "Pack-owned path is not UTF-8".to_owned()) + .and_then(super::portable_pack_path) + }) + .collect::, _>>() + .map_err(serde::ser::Error::custom)?; + paths.serialize(serializer) +} + +fn deserialize_owned_paths<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + Vec::::deserialize(deserializer)? + .into_iter() + .map(|path| { + super::portable_pack_path(&path) + .map(PathBuf::from) + .map_err(serde::de::Error::custom) + }) + .collect() +} + +struct RefreshStaging { + // Field order closes the lease before TempDir cleanup, also on cancellation. + _lease: std::fs::File, + directory: tempfile::TempDir, +} + +impl RefreshStaging { + fn new(instances_dir: &Path) -> std::io::Result { + // Recovery cannot see a new directory before its lease is installed. + let _creation_lock = lock_refresh_recovery(instances_dir)?; + let directory = tempfile::Builder::new() + .prefix(".rmcl-refresh-") + .tempdir_in(instances_dir)?; + let lease = std::fs::OpenOptions::new() + .create_new(true) + .read(true) + .write(true) + .open(directory.path().join(".lease"))?; + lease.lock()?; + Ok(Self { + _lease: lease, + directory, + }) + } + + fn path(&self) -> &Path { + self.directory.path() + } +} + +fn lock_refresh_recovery(instances_dir: &Path) -> std::io::Result { + let lock = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(instances_dir.join(".rmcl-refresh.lock"))?; + lock.lock()?; + Ok(lock) +} + pub struct RefreshPlan { pub instance: InstanceConfig, pub summary: ImportSummary, pub current_version: String, pub target_version: String, pub conflicts: Vec, - stage_root: PathBuf, + staging: RefreshStaging, staged_instance: PathBuf, old_owned: HashSet, new_owned: HashSet, -} - -impl Drop for RefreshPlan { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.stage_root); - } + previous_source: Option, + meta_dir: PathBuf, } pub async fn prepare( @@ -56,6 +142,7 @@ pub async fn prepare( instance: &InstanceConfig, target: VersionInfo, ) -> Result { + crate::instance::manager::validate_name(&instance.name).map_err(|error| error.to_string())?; if crate::instance::runtime::is_active(&instance.name) { return Err("Stop the instance before changing its modpack".to_owned()); } @@ -91,108 +178,144 @@ pub async fn prepare( )); } - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_err(|error| error.to_string())? - .as_nanos(); - let stage_root = manager.instances_dir.join(format!(".rmcl-refresh-{nonce}")); - let archives = stage_root.join("archives"); - let result = async { - let summary = super::download_provider_summary(&source, &target, &archives.join("target")) - .await - .map_err(|error| error.to_string())?; - let old_owned = match PackState::load(&InstancePaths::new(&live)) - .filter(|state| state.source == source) - { + let staging = RefreshStaging::new(&manager.instances_dir).map_err(|error| error.to_string())?; + let archives = staging.path().join("archives"); + let summary = super::download_provider_summary(&source, &target, &archives.join("target")) + .await + .map_err(|error| error.to_string())?; + let old_owned = + match PackState::load(&InstancePaths::new(&live)).filter(|state| state.source == source) { Some(state) => state.files.into_iter().collect(), None => reconstruct_owned_files(&source, ¤t, &archives.join("current")).await?, }; - let staging_manager = InstanceManager::new(&stage_root, &manager.meta_dir); - let staged_config = super::execute_import(&summary, &staging_manager) - .await + let staging_manager = InstanceManager::new(staging.path().join("instances"), &manager.meta_dir); + let staged_config = super::execute_import(&summary, &staging_manager) + .await + .map_err(|error| error.to_string())?; + let imported = staging_manager.instances_dir.join(&staged_config.name); + let new_owned = PackState::load(&InstancePaths::new(&imported)) + .ok_or_else(|| "The staged pack did not record its owned files".to_owned())? + .files + .into_iter() + .collect::>(); + let staged_instance = staging_manager.instances_dir.join(&instance.name); + if imported != staged_instance { + let aliases_source = crate::instance::manager::paths_alias(&imported, &staged_instance) .map_err(|error| error.to_string())?; - let imported = stage_root.join(&staged_config.name); - let new_owned = PackState::load(&InstancePaths::new(&imported)) - .ok_or_else(|| "The staged pack did not record its owned files".to_owned())? - .files - .into_iter() - .collect::>(); - let staged_instance = stage_root.join(&instance.name); - if imported != staged_instance { - std::fs::rename(&imported, &staged_instance).map_err(|error| error.to_string())?; - } - - let mut config = instance.clone(); - config.game_version = summary.game_version.clone(); - config.loader = summary.loader; - config.loader_version = summary.loader_version.clone(); - config.modpack_source = summary.source.clone(); - let staged_manager = InstanceManager::new(&stage_root, &manager.meta_dir); - staged_manager - .save(&config) + crate::instance::manager::rename_path(&imported, &staged_instance, aliases_source) .map_err(|error| error.to_string())?; + } - let conflicts = user_file_collisions( - &InstancePaths::new(&live).minecraft(), - &old_owned, - &new_owned, - )?; - Ok::<_, String>(RefreshPlan { - instance: config, - current_version: current.version_number, - target_version: target.version_number.clone(), - summary, - conflicts, - stage_root: stage_root.clone(), - staged_instance, - old_owned, - new_owned, - }) - } - .await; - if result.is_err() { - let _ = std::fs::remove_dir_all(&stage_root); - } - result + let mut config = instance.clone(); + config.game_version = summary.game_version.clone(); + config.loader = summary.loader; + config.loader_version = summary.loader_version.clone(); + config.modpack_source = summary.source.clone(); + staging_manager + .save(&config) + .map_err(|error| error.to_string())?; + + let conflicts = user_file_collisions( + &InstancePaths::new(&live).minecraft(), + &old_owned, + &new_owned, + )?; + Ok(RefreshPlan { + instance: config, + current_version: current.version_number, + target_version: target.version_number.clone(), + summary, + conflicts, + staging, + staged_instance, + old_owned, + new_owned, + previous_source: instance.modpack_source.clone(), + meta_dir: manager.meta_dir.clone(), + }) } pub fn apply( plan: RefreshPlan, replace_conflicts: &HashSet, ) -> Result { + crate::instance::manager::validate_name(&plan.instance.name) + .map_err(|error| error.to_string())?; 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 + .staging + .path() .parent() .ok_or_else(|| "Invalid refresh staging path".to_owned())? .join(&plan.instance.name); + let _instance_lock = crate::instance::runtime::lock_instance( + live.parent().ok_or("Invalid instance root")?, + &plan.instance.name, + ) + .map_err(|error| error.to_string())?; + let manager = InstanceManager::new( + live.parent().ok_or("Invalid instance root")?, + &plan.meta_dir, + ); + let _config_lock = manager + .config_lock(&plan.instance.name) + .map_err(|error| error.to_string())?; + let mut config = manager + .load_one(&plan.instance.name) + .map_err(|error| error.to_string())?; + if config.created != plan.instance.created || config.modpack_source != plan.previous_source { + return Err("The instance or its modpack changed while this update was being reviewed; prepare the update again".to_owned()); + } + config.game_version.clone_from(&plan.instance.game_version); + config.loader = plan.instance.loader; + config + .loader_version + .clone_from(&plan.instance.loader_version); + config + .modpack_source + .clone_from(&plan.instance.modpack_source); + crate::storage::write_atomic( + &plan.staged_instance.join("instance.json"), + &serde_json::to_vec_pretty(&config).map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?; let old_minecraft = InstancePaths::new(&live).minecraft(); let staged_minecraft = InstancePaths::new(&plan.staged_instance).minecraft(); + let old_owned = preserve_disabled_pack_files( + &live, + &plan.staged_instance, + &plan.old_owned, + &plan.new_owned, + )?; preserve_user_files( &old_minecraft, &staged_minecraft, &old_minecraft, - &plan.old_owned, + &old_owned, &plan.new_owned, replace_conflicts, )?; preserve_refresh_state( &live, &plan.staged_instance, - &plan.old_owned, + &old_owned, &plan.new_owned, replace_conflicts, )?; let backup = live.with_file_name(format!(".{}.rmcl-backup", plan.instance.name)); - if backup.exists() { - return Err(format!( - "A previous update backup still exists at '{}'", - backup.display() - )); + match std::fs::symlink_metadata(&backup) { + Ok(_) => { + return Err(format!( + "A previous update backup still exists at '{}'", + backup.display() + )); + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.to_string()), } std::fs::rename(&live, &backup).map_err(|error| error.to_string())?; if let Err(error) = std::fs::rename(&plan.staged_instance, &live) { @@ -208,7 +331,7 @@ pub fn apply( if let Err(error) = std::fs::remove_dir_all(&backup) { tracing::warn!("Could not remove successful modpack update backup: {error}"); } - Ok(plan.instance.clone()) + Ok(config) } async fn reconstruct_owned_files( @@ -226,13 +349,76 @@ pub fn recover_interrupted(instances_dir: &Path) { let Ok(entries) = std::fs::read_dir(instances_dir) else { return; }; + let _recovery_lock = match lock_refresh_recovery(instances_dir) { + Ok(lock) => lock, + Err(error) => { + tracing::warn!( + "Could not lock refresh recovery '{}': {error}", + instances_dir.display() + ); + return; + } + }; for entry in entries.flatten() { let path = entry.path(); let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue; }; - if name.starts_with(".rmcl-refresh-") { - let _ = std::fs::remove_dir_all(path); + if !entry.file_type().is_ok_and(|kind| kind.is_dir()) { + continue; + } + if name.starts_with(".rmcl-refresh-") && !name.ends_with(".rmcl-backup") { + let lease_path = path.join(".lease"); + match std::fs::symlink_metadata(&lease_path) { + Ok(metadata) if !metadata.is_file() => { + tracing::warn!("Invalid refresh lease '{}'", lease_path.display()); + continue; + } + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + tracing::warn!( + "Could not inspect refresh lease '{}': {error}", + lease_path.display() + ); + continue; + } + _ => {} + } + let lease = match std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(&lease_path) + { + Ok(lease) => lease, + Err(error) => { + tracing::warn!( + "Could not open refresh lease '{}': {error}", + lease_path.display() + ); + continue; + } + }; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => continue, + Err(error) => { + tracing::warn!( + "Could not lock refresh lease '{}': {error}", + lease_path.display() + ); + continue; + } + } + drop(lease); + if let Err(error) = std::fs::remove_dir_all(&path) + && error.kind() != std::io::ErrorKind::NotFound + { + tracing::warn!( + "Could not remove abandoned refresh staging '{}': {error}", + path.display() + ); + } continue; } let Some(instance_name) = name @@ -241,9 +427,23 @@ pub fn recover_interrupted(instances_dir: &Path) { else { continue; }; + let _instance_lock = + match crate::instance::runtime::lock_instance(instances_dir, instance_name) { + Ok(lock) => lock, + Err(crate::instance::manager::InstanceError::InstanceRunning(_)) => continue, + Err(error) => { + tracing::warn!("Could not lock interrupted update '{instance_name}': {error}"); + continue; + } + }; let live = instances_dir.join(instance_name); if live.join("instance.json").is_file() { - let _ = std::fs::remove_dir_all(path); + if let Err(error) = std::fs::remove_dir_all(&path) { + tracing::warn!( + "Could not remove interrupted update backup '{}': {error}", + path.display() + ); + } } else if let Err(error) = std::fs::rename(&path, &live) { tracing::warn!( "Could not restore interrupted modpack update backup '{}': {error}", @@ -269,6 +469,38 @@ fn user_file_collisions( Ok(collisions) } +fn preserve_disabled_pack_files( + live: &Path, + staged: &Path, + old_owned: &HashSet, + new_owned: &HashSet, +) -> Result, String> { + let old = InstancePaths::new(live); + let new = InstancePaths::new(staged); + let mut owned = old_owned.clone(); + let mut manifest = ContentManifest::load(&new.content_manifest()).map_err(|e| e.to_string())?; + for path in old_owned { + let Some(filename) = path.file_name() else { + continue; + }; + let mut disabled_name = filename.to_os_string(); + disabled_name.push(".disabled"); + let disabled = path.with_file_name(disabled_name); + if !old.minecraft().join(path).exists() && old.minecraft().join(&disabled).is_file() { + owned.insert(disabled.clone()); + if new_owned.contains(path) && new.minecraft().join(path).is_file() { + std::fs::rename(new.minecraft().join(path), new.minecraft().join(&disabled)) + .map_err(|e| e.to_string())?; + manifest.rename_record(path, &disabled, false); + } + } + } + manifest + .save(&new.content_manifest()) + .map_err(|e| e.to_string())?; + Ok(owned) +} + fn preserve_refresh_state( live: &Path, staged: &Path, @@ -278,6 +510,18 @@ fn preserve_refresh_state( ) -> Result<(), String> { let old = InstancePaths::new(live); let new = InstancePaths::new(staged); + let baseline = old.state().join("config-sync.json"); + match std::fs::read(&baseline) { + Ok(bytes) => crate::storage::write_atomic(&new.state().join("config-sync.json"), &bytes) + .map_err(|error| error.to_string())?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(format!( + "Could not preserve config sync baseline '{}': {error}", + baseline.display() + )); + } + } let local_config = old.local_config(); if local_config.exists() { std::fs::create_dir_all(new.local_config()).map_err(|e| e.to_string())?; @@ -429,9 +673,10 @@ mod tests { 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 staging = RefreshStaging::new(temp.path()).unwrap(); + let stage_root = staging.path().to_owned(); let live = temp.path().join(name); - let staged_instance = stage_root.join(name); + let staged_instance = stage_root.join("instances").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!({ @@ -456,10 +701,12 @@ mod tests { current_version: "1".to_owned(), target_version: "2".to_owned(), conflicts: Vec::new(), - stage_root, + staging, staged_instance, old_owned: HashSet::new(), new_owned: HashSet::new(), + previous_source: None, + meta_dir: temp.path().join("meta"), }; crate::instance::runtime::set_state(name, crate::instance::runtime::RunState::Running); let result = apply(plan, &HashSet::new()); @@ -469,6 +716,59 @@ mod tests { assert!(live.join("minecraft").is_dir()); } + #[test] + fn refresh_rejects_a_recreated_instance_without_moving_its_files() { + let temp = tempfile::tempdir().unwrap(); + let name = "recreated"; + let manager = InstanceManager::new(temp.path(), temp.path().join("meta")); + let staging = RefreshStaging::new(temp.path()).unwrap(); + let staged_instance = staging.path().join("instances").join(name); + let live = manager.instances_dir.join(name); + std::fs::create_dir_all(live.join("minecraft")).unwrap(); + std::fs::create_dir_all(staged_instance.join("minecraft")).unwrap(); + std::fs::write(live.join("minecraft/sentinel"), b"new instance").unwrap(); + let instance: InstanceConfig = serde_json::from_value(serde_json::json!({ + "name": name, "game_version": "1.21", "loader": "vanilla", "created": "2026-01-01T00:00:00Z" + })).unwrap(); + let mut current = instance.clone(); + current.created += chrono::TimeDelta::seconds(1); + manager.save(¤t).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: staging.path().join("pack.mrpack"), + source: None, + }, + current_version: "1".to_owned(), + target_version: "2".to_owned(), + conflicts: Vec::new(), + staged_instance, + staging, + old_owned: HashSet::new(), + new_owned: HashSet::new(), + previous_source: None, + meta_dir: manager.meta_dir.clone(), + }; + assert!( + apply(plan, &HashSet::new()) + .unwrap_err() + .contains("changed while") + ); + assert_eq!( + std::fs::read(live.join("minecraft/sentinel")).unwrap(), + b"new instance" + ); + assert_eq!(manager.load_one(name).unwrap().created, current.created); + } + fn record(path: &str) -> ContentFileRecord { ContentFileRecord { relative_path: path.into(), @@ -488,6 +788,46 @@ mod tests { } } + #[test] + fn refreshing_a_disabled_pack_file_keeps_only_the_updated_disabled_file() { + 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.minecraft().join("mods")).unwrap(); + std::fs::create_dir_all(new.minecraft().join("mods")).unwrap(); + std::fs::write(old.minecraft().join("mods/pack.jar.disabled"), b"old").unwrap(); + std::fs::write(new.minecraft().join("mods/pack.jar"), b"updated").unwrap(); + let mut manifest = ContentManifest::default(); + manifest.upsert(record("mods/pack.jar")); + manifest.save(&new.content_manifest()).unwrap(); + let owned = HashSet::from([PathBuf::from("mods/pack.jar")]); + + let previous = + preserve_disabled_pack_files(old.root(), new.root(), &owned, &owned).unwrap(); + preserve_user_files( + &old.minecraft(), + &new.minecraft(), + &old.minecraft(), + &previous, + &owned, + &HashSet::new(), + ) + .unwrap(); + + assert_eq!( + std::fs::read(new.minecraft().join("mods/pack.jar.disabled")).unwrap(), + b"updated" + ); + assert!(!new.minecraft().join("mods/pack.jar").exists()); + assert!( + !ContentManifest::load(&new.content_manifest()) + .unwrap() + .record(Path::new("mods/pack.jar.disabled")) + .unwrap() + .enabled + ); + } + #[test] fn refresh_keeps_local_config_and_user_content_records() { let temp = tempfile::tempdir().unwrap(); @@ -551,6 +891,155 @@ mod tests { ); } + #[test] + fn config_sync_baseline_survives_refresh_and_preserves_publication_conflicts() { + use crate::instance::config_sync::{self, ConfigSyncError}; + + for (pack_changed, shared_changed) in [(false, true), (true, false), (true, true)] { + let temp = tempfile::tempdir().unwrap(); + let manager = + InstanceManager::new(temp.path().join("instances"), temp.path().join("meta")); + let name = "synced-pack"; + let live = InstancePaths::new(manager.instances_dir.join(name)); + std::fs::create_dir_all(live.minecraft().join("config")).unwrap(); + std::fs::write(live.minecraft().join("config/pack.toml"), b"local-default").unwrap(); + std::fs::write(live.minecraft().join("options.txt"), b"default-options").unwrap(); + let source = ProviderProject { + provider: "modrinth".to_owned(), + project_id: "pack".to_owned(), + version_id: "1".to_owned(), + }; + let mut current: InstanceConfig = serde_json::from_value(serde_json::json!({ + "name": name, "game_version": "1.21", "loader": "vanilla", + "created": "2026-01-01T00:00:00Z", "modpack_source": source + })) + .unwrap(); + manager.save(¤t).unwrap(); + + let staging = RefreshStaging::new(&manager.instances_dir).unwrap(); + let staged = InstancePaths::new(staging.path().join("instances").join(name)); + std::fs::create_dir_all(staged.minecraft().join("config")).unwrap(); + let refreshed = if pack_changed { + "refreshed-pack" + } else { + "old-pack" + }; + std::fs::write(staged.minecraft().join("config/pack.toml"), refreshed).unwrap(); + let target_source = ProviderProject { + version_id: "2".to_owned(), + ..source.clone() + }; + let owned = HashSet::from([PathBuf::from("config/pack.toml")]); + PackState { + source: target_source.clone(), + files: owned.iter().cloned().collect(), + } + .save(&staged) + .unwrap(); + let mut instance = current.clone(); + instance.modpack_source = Some(target_source.clone()); + 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: 1, + format: super::super::PackFormat::Mrpack, + archive_path: staging.path().join("pack.mrpack"), + source: Some(target_source), + }, + current_version: "1".to_owned(), + target_version: "2".to_owned(), + conflicts: Vec::new(), + staged_instance: staged.root().to_owned(), + staging, + old_owned: owned.clone(), + new_owned: owned, + previous_source: Some(source), + meta_dir: manager.meta_dir.clone(), + }; + + // Selection and baseline are created while the refresh is being reviewed. + config_sync::create_profile(&manager.meta_dir, "shared").unwrap(); + let profile = crate::storage::MetadataPaths::new(&manager.meta_dir) + .profiles() + .join("shared"); + std::fs::create_dir_all(profile.join("config")).unwrap(); + std::fs::write(profile.join("config/pack.toml"), b"old-pack").unwrap(); + std::fs::write(profile.join("options.txt"), b"shared-options").unwrap(); + config_sync::switch_profile_and_save(&manager, &mut current, Some("shared")).unwrap(); + let baseline = std::fs::read(live.state().join("config-sync.json")).unwrap(); + if shared_changed { + let other = manager.instances_dir.join("other/minecraft"); + std::fs::create_dir_all(&other).unwrap(); + let lock = + config_sync::prepare_for_launch(Some("shared"), &manager.meta_dir, &other) + .unwrap() + .unwrap(); + std::fs::write(other.join("config/pack.toml"), b"new-shared").unwrap(); + config_sync::finish_launch(lock, &other).unwrap(); + } + + let mut applied = apply(plan, &HashSet::new()).unwrap(); + assert_eq!(applied.config_sync_profile.as_deref(), Some("shared")); + assert_eq!( + std::fs::read(live.state().join("config-sync.json")).unwrap(), + baseline + ); + assert_eq!( + std::fs::read_to_string(live.minecraft().join("config/pack.toml")).unwrap(), + refreshed + ); + let result = config_sync::switch_profile_and_save(&manager, &mut applied, None); + if pack_changed && shared_changed { + assert!(matches!(result, Err(ConfigSyncError::Conflict { .. }))); + assert_eq!( + manager + .load_one(name) + .unwrap() + .config_sync_profile + .as_deref(), + Some("shared") + ); + assert_eq!( + std::fs::read(live.minecraft().join("config/pack.toml")).unwrap(), + b"refreshed-pack" + ); + assert_eq!( + std::fs::read(live.state().join("config-sync.json")).unwrap(), + baseline + ); + } else { + result.unwrap(); + assert_eq!(manager.load_one(name).unwrap().config_sync_profile, None); + assert_eq!( + std::fs::read(live.minecraft().join("config/pack.toml")).unwrap(), + b"local-default" + ); + assert_eq!( + std::fs::read(live.minecraft().join("options.txt")).unwrap(), + b"default-options" + ); + } + assert_eq!( + std::fs::read_to_string(profile.join("config/pack.toml")).unwrap(), + if shared_changed { + "new-shared" + } else { + "refreshed-pack" + } + ); + assert_eq!( + std::fs::read(profile.join("options.txt")).unwrap(), + b"shared-options" + ); + } + } + #[cfg(unix)] #[test] fn refresh_preserves_user_symlinks_without_following_them() { @@ -643,4 +1132,298 @@ mod tests { assert!(!backup.exists()); assert!(!staging.exists()); } + + #[test] + fn windows_ownership_fixture_reserializes_portably_and_refresh_removes_obsolete_files() { + let temp = tempfile::tempdir().unwrap(); + let name = "archives"; + let live = InstancePaths::new(temp.path().join(name)); + std::fs::create_dir_all(live.minecraft().join("mods")).unwrap(); + std::fs::create_dir_all(live.minecraft().join("config")).unwrap(); + for (path, bytes) in [ + ("mods/updated.jar", "old"), + ("mods/obsolete.jar", "obsolete"), + ("mods/user.jar", "user"), + ("mods/conflict.jar", "user conflict"), + ("config/pack.toml", "old config"), + ] { + std::fs::write(live.minecraft().join(path), bytes).unwrap(); + } + let raw_windows = br#"{"source":{"provider":"modrinth","project_id":"pack","version_id":"1"},"files":["mods\\updated.jar","mods\\obsolete.jar","config\\pack.toml"]}"#; + crate::storage::write_atomic(&live.modpack_state(), raw_windows).unwrap(); + let previous = PackState::load(&live).unwrap(); + assert_eq!( + previous.files, + vec![ + PathBuf::from("mods/updated.jar"), + PathBuf::from("mods/obsolete.jar"), + PathBuf::from("config/pack.toml") + ] + ); + previous.save(&live).unwrap(); + let serialized: serde_json::Value = + serde_json::from_slice(&std::fs::read(live.modpack_state()).unwrap()).unwrap(); + assert_eq!( + serialized["files"], + serde_json::json!(["mods/updated.jar", "mods/obsolete.jar", "config/pack.toml"]) + ); + + let staging = RefreshStaging::new(temp.path()).unwrap(); + let stage_path = staging.path().to_owned(); + std::fs::create_dir_all(stage_path.join("archives/target")).unwrap(); + std::fs::write(stage_path.join("archives/target/pack.zip"), b"archive").unwrap(); + let staged = InstancePaths::new(stage_path.join("instances").join(name)); + std::fs::create_dir_all(staged.minecraft().join("mods")).unwrap(); + std::fs::create_dir_all(staged.minecraft().join("config")).unwrap(); + for (path, bytes) in [ + ("mods/updated.jar", "updated"), + ("mods/conflict.jar", "pack conflict"), + ("config/pack.toml", "updated config"), + ] { + std::fs::write(staged.minecraft().join(path), bytes).unwrap(); + } + let source = ProviderProject { + version_id: "2".to_owned(), + ..previous.source.clone() + }; + PackState { + source: source.clone(), + files: vec![ + PathBuf::from("mods").join("updated.jar"), + PathBuf::from("mods").join("conflict.jar"), + PathBuf::from("config").join("pack.toml"), + ], + } + .save(&staged) + .unwrap(); + let old_owned = previous.files.into_iter().collect(); + let new_owned = PackState::load(&staged) + .unwrap() + .files + .into_iter() + .collect(); + let conflicts = user_file_collisions(&live.minecraft(), &old_owned, &new_owned).unwrap(); + assert_eq!(conflicts, vec![PathBuf::from("mods/conflict.jar")]); + let mut instance: InstanceConfig = serde_json::from_value(serde_json::json!({ + "name": name, "game_version": "1.21", "loader": "vanilla", "created": "2026-01-01T00:00:00Z" + })).unwrap(); + let manager = InstanceManager::new(temp.path(), temp.path().join("meta")); + let mut current = instance.clone(); + current.game_version = "1.20.1".to_owned(); + current.modpack_source = Some(previous.source.clone()); + manager.save(¤t).unwrap(); + instance.modpack_source = Some(source); + crate::storage::write_atomic( + &staged.root().join("instance.json"), + &serde_json::to_vec(&instance).unwrap(), + ) + .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: 1, + override_count: 1, + format: super::super::PackFormat::Mrpack, + archive_path: stage_path.join("archives/target/pack.zip"), + source: None, + }, + current_version: "1".to_owned(), + target_version: "2".to_owned(), + conflicts, + staging, + staged_instance: staged.root().to_owned(), + old_owned, + new_owned, + previous_source: Some(previous.source), + meta_dir: manager.meta_dir.clone(), + }; + current.memory_max = Some("8G".to_owned()); + current.config_sync_profile = Some("shared".to_owned()); + current.last_played = Some(chrono::Utc::now()); + manager.save(¤t).unwrap(); + manager + .save_config_sync_profile(name, current.config_sync_profile.clone()) + .unwrap(); + recover_interrupted(temp.path()); + assert!(stage_path.join("archives/target/pack.zip").is_file()); + let applied = apply(plan, &HashSet::new()).unwrap(); + assert_eq!(applied.memory_max, current.memory_max); + assert_eq!(applied.config_sync_profile, current.config_sync_profile); + assert_eq!(applied.last_played, current.last_played); + assert_eq!( + manager.load_one(name).unwrap().memory_max, + current.memory_max + ); + assert_eq!( + std::fs::read(live.minecraft().join("mods/updated.jar")).unwrap(), + b"updated" + ); + assert_eq!( + std::fs::read(live.minecraft().join("config/pack.toml")).unwrap(), + b"updated config" + ); + assert_eq!( + std::fs::read(live.minecraft().join("mods/user.jar")).unwrap(), + b"user" + ); + assert_eq!( + std::fs::read(live.minecraft().join("mods/conflict.jar")).unwrap(), + b"user conflict" + ); + assert!(!live.minecraft().join("mods/obsolete.jar").exists()); + assert!(!stage_path.exists()); + let serialized: serde_json::Value = + serde_json::from_slice(&std::fs::read(live.modpack_state()).unwrap()).unwrap(); + assert_eq!( + serialized["files"], + serde_json::json!(["mods/updated.jar", "config/pack.toml"]) + ); + } + + #[test] + fn ownership_rejects_unsafe_paths_without_overwriting_valid_state() { + let temp = tempfile::tempdir().unwrap(); + let paths = InstancePaths::new(temp.path()); + let mut state = PackState { + source: ProviderProject { + provider: "modrinth".to_owned(), + project_id: "pack".to_owned(), + version_id: "1".to_owned(), + }, + files: vec![PathBuf::from("mods").join("pack.jar")], + }; + state.save(&paths).unwrap(); + let original = std::fs::read(paths.modpack_state()).unwrap(); + for path in [ + "../escape", + r"..\escape", + "mods/../escape", + "C:victim", + r"C:\absolute", + r"\rooted", + r"\\server\share\file", + r"\\?\C:\file", + "/absolute", + "mods/C:victim", + "mods/NUL.jar", + "mods/file:stream", + "mods/trailing.", + ] { + let value = serde_json::json!({"source": state.source, "files": [path]}); + assert!( + serde_json::from_value::(value.clone()).is_err(), + "{path}" + ); + state.files = vec![PathBuf::from(path)]; + assert!(state.save(&paths).is_err(), "{path}"); + assert_eq!(std::fs::read(paths.modpack_state()).unwrap(), original); + } + } + + #[test] + fn refresh_lease_child() { + use std::io::Write; + let Some(root) = std::env::var_os("RMCL_REFRESH_LEASE_TEST") else { + return; + }; + let root = Path::new(&root); + let staging = RefreshStaging::new(root).unwrap(); + let _restore_lock = + crate::instance::runtime::lock_instance(root, "rmcl-refresh-Pack").unwrap(); + let _cleanup_lock = crate::instance::runtime::lock_instance(root, "Live").unwrap(); + println!( + "LEASED {}", + staging.path().file_name().unwrap().to_str().unwrap() + ); + std::io::stdout().flush().unwrap(); + let mut line = String::new(); + std::io::stdin().read_line(&mut line).unwrap(); + drop(staging); + } + + #[test] + fn recovery_skips_another_process_staging_and_both_locked_backup_paths() { + use std::io::BufRead; + let temp = tempfile::tempdir().unwrap(); + for directory in [ + ".rmcl-refresh-Pack.rmcl-backup", + ".Live.rmcl-backup", + "Live", + ".rmcl-refresh-legacy", + ] { + std::fs::create_dir(temp.path().join(directory)).unwrap(); + std::fs::write(temp.path().join(directory).join("instance.json"), b"{}").unwrap(); + } + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "instance::import::refresh::tests::refresh_lease_child", + "--nocapture", + ]) + .env("RMCL_REFRESH_LEASE_TEST", temp.path()) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let stage_name = std::io::BufReader::new(child.stdout.take().unwrap()) + .lines() + .find_map(|line| line.unwrap().strip_prefix("LEASED ").map(str::to_owned)) + .expect("child acquired its leases"); + let staging = temp.path().join(stage_name); + recover_interrupted(temp.path()); + let active_stage_survived = staging.is_dir(); + let restore_backup_survived = temp + .path() + .join(".rmcl-refresh-Pack.rmcl-backup/instance.json") + .is_file() + && !temp.path().join("rmcl-refresh-Pack").exists(); + let cleanup_backup_survived = temp + .path() + .join(".Live.rmcl-backup/instance.json") + .is_file(); + let _ = child.kill(); + child.wait().unwrap(); + recover_interrupted(temp.path()); + assert!(active_stage_survived); + assert!(restore_backup_survived); + assert!(cleanup_backup_survived); + assert!(!staging.exists()); + assert!( + temp.path() + .join("rmcl-refresh-Pack/instance.json") + .is_file() + ); + assert!(!temp.path().join(".rmcl-refresh-Pack.rmcl-backup").exists()); + assert!(temp.path().join("Live/instance.json").is_file()); + assert!(!temp.path().join(".Live.rmcl-backup").exists()); + assert!(!temp.path().join(".rmcl-refresh-legacy").exists()); + } + + #[tokio::test] + async fn cancelled_preparation_cleans_its_distinct_leased_staging() { + let temp = tempfile::tempdir().unwrap(); + let other = RefreshStaging::new(temp.path()).unwrap(); + let root = temp.path().to_owned(); + let (ready, received) = tokio::sync::oneshot::channel(); + let preparation = tokio::spawn(async move { + let staging = RefreshStaging::new(&root).unwrap(); + ready.send(staging.path().to_owned()).unwrap(); + std::future::pending::<()>().await; + drop(staging); + }); + let stage = received.await.unwrap(); + assert_ne!(stage, other.path()); + recover_interrupted(temp.path()); + assert!(stage.is_dir()); + assert!(other.path().is_dir()); + preparation.abort(); + assert!(preparation.await.unwrap_err().is_cancelled()); + assert!(!stage.exists()); + assert!(other.path().is_dir()); + } } diff --git a/src/instance/manager.rs b/src/instance/manager.rs index 0948fd9..a29c24c 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use chrono::Utc; use thiserror::Error; @@ -465,6 +465,8 @@ impl InstanceManager { if crate::instance::runtime::is_active(name) { return Err(InstanceError::InstanceRunning(name.to_owned())); } + let _lock = crate::instance::runtime::lock_instance(&self.instances_dir, name)?; + let _config_lock = self.config_lock(name)?; let instance_dir = self.instances_dir.join(name); if !instance_dir.exists() { tracing::warn!( @@ -505,10 +507,8 @@ impl InstanceManager { tracing::debug!("Ignoring no-op instance rename '{}'", old_name); return Ok(()); } - // same path-traversal guards as create: without this, "../x" or ".x" - // would move the instance directory out of (or hide it inside) the - // instances root. validate_name(new_name)?; + let _old_lock = crate::instance::runtime::lock_instance(&self.instances_dir, old_name)?; let old_dir = self.instances_dir.join(old_name); let new_dir = self.instances_dir.join(new_name); if !old_dir.exists() { @@ -519,7 +519,16 @@ impl InstanceManager { ); return Err(InstanceError::NotFound(old_name.to_string())); } - if new_dir.exists() { + let aliases_source = paths_alias(&old_dir, &new_dir)?; + let _new_lock = if aliases_source { + None + } else { + Some(crate::instance::runtime::lock_instance( + &self.instances_dir, + new_name, + )?) + }; + if std::fs::symlink_metadata(&new_dir).is_ok() && !aliases_source { tracing::warn!( "Cannot rename instance '{}' to '{}': destination exists at {}", old_name, @@ -528,11 +537,17 @@ impl InstanceManager { ); return Err(InstanceError::AlreadyExists(new_name.to_string())); } + let _old_config_lock = self.config_lock(old_name)?; + let _new_config_lock = if aliases_source { + None + } else { + Some(self.config_lock(new_name)?) + }; let mut config = self.load_one(old_name)?; config.name = new_name.to_owned(); let json = serde_json::to_vec_pretty(&config)?; tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name); - if let Err(e) = std::fs::rename(&old_dir, &new_dir) { + if let Err(e) = rename_path(&old_dir, &new_dir, aliases_source) { tracing::error!( "Failed to rename instance directory {} to {}: {}", old_dir.display(), @@ -544,7 +559,7 @@ impl InstanceManager { let config_path = new_dir.join("instance.json"); if let Err(error) = crate::storage::write_atomic(&config_path, &json) { - if let Err(rollback_error) = std::fs::rename(&new_dir, &old_dir) { + if let Err(rollback_error) = rename_path(&new_dir, &old_dir, aliases_source) { tracing::error!( "Failed to roll back instance rename from {} to {}: {}", new_dir.display(), @@ -583,6 +598,12 @@ impl InstanceManager { continue; } }; + let Some(directory_name) = entry.file_name().to_str().map(str::to_owned) else { + continue; + }; + if validate_name(&directory_name).is_err() { + continue; + } let config_path = entry.path().join("instance.json"); if !config_path.exists() { tracing::trace!("Skipping non-instance directory {}", entry.path().display()); @@ -597,12 +618,6 @@ impl InstanceManager { }; match serde_json::from_str::(&contents) { 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); } @@ -659,6 +674,47 @@ impl InstanceManager { } pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> { + let _lock = self.config_lock(&instance.name)?; + let mut instance = instance.clone(); + match self.load_one(&instance.name) { + Ok(current) => { + instance.last_played = instance.last_played.max(current.last_played); + // Selection changes must commit with their corresponding filesystem payload. + instance.config_sync_profile = current.config_sync_profile; + } + Err(InstanceError::NotFound(_)) => {} + Err(error) => return Err(error), + } + self.save_unlocked(&instance) + } + + pub(crate) fn save_config_sync_profile( + &self, + name: &str, + profile: Option, + ) -> Result { + let _lock = self.config_lock(name)?; + let mut config = self.load_one(name)?; + config.config_sync_profile = profile; + self.save_unlocked(&config)?; + Ok(config) + } + + pub(crate) fn config_lock(&self, name: &str) -> Result { + validate_name(name)?; + // the lock must survive replacing or renaming the instance directory. + std::fs::create_dir_all(&self.instances_dir)?; + let path = self.instances_dir.join(format!(".rmcl-config-{name}.lock")); + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(path)?; + file.lock()?; + Ok(file) + } + + fn save_unlocked(&self, instance: &InstanceConfig) -> Result<(), InstanceError> { validate_name(&instance.name)?; let instance_dir = self.instances_dir.join(&instance.name); if !instance_dir.is_dir() { @@ -676,10 +732,11 @@ impl InstanceManager { } pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> { + let _lock = self.config_lock(name)?; let mut config = self.load_one(name)?; config.last_played = Some(chrono::Utc::now()); tracing::debug!("Updating last_played for '{}'", name); - self.save(&config) + self.save_unlocked(&config) } } @@ -727,6 +784,78 @@ pub(crate) fn portable_component(name: &str) -> bool { }) } +pub(crate) fn paths_alias(left: &Path, right: &Path) -> std::io::Result { + if left.parent() != right.parent() { + return Ok(false); + } + let right_metadata = match std::fs::symlink_metadata(right) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(error) => return Err(error), + }; + let left_metadata = std::fs::symlink_metadata(left)?; + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if left_metadata.dev() != right_metadata.dev() + || left_metadata.ino() != right_metadata.ino() + { + return Ok(false); + } + // Distinct hard links are not aliases of the same directory entry. + if left.file_name() != right.file_name() { + let mut left_entry = false; + let mut right_entry = false; + for entry in std::fs::read_dir( + left.parent() + .ok_or_else(|| std::io::Error::other("Path has no parent"))?, + )? { + let name = entry?.file_name(); + left_entry |= Some(name.as_os_str()) == left.file_name(); + right_entry |= Some(name.as_os_str()) == right.file_name(); + } + if left_entry && right_entry { + return Ok(false); + } + } + Ok(true) + } + #[cfg(not(unix))] + { + if left_metadata.file_type().is_symlink() || right_metadata.file_type().is_symlink() { + return Ok(false); + } + Ok(std::fs::canonicalize(left)? == std::fs::canonicalize(right)?) + } +} + +pub(crate) fn rename_path(from: &Path, to: &Path, aliases_source: bool) -> std::io::Result<()> { + if !aliases_source { + return std::fs::rename(from, to); + } + let temporary = tempfile::Builder::new() + .prefix(".rmcl-rename-") + .tempdir_in( + from.parent() + .ok_or_else(|| std::io::Error::other("Path has no parent"))?, + )?; + let staged = temporary.path().join("original"); + std::fs::rename(from, &staged)?; + if let Err(error) = std::fs::rename(&staged, to) { + if let Err(rollback) = std::fs::rename(&staged, from) { + let retained = temporary.keep(); + return Err(std::io::Error::other(format!( + "Could not rename '{}' to '{}': {error}; rollback failed: {rollback}; original retained at '{}'", + from.display(), + to.display(), + retained.join("original").display(), + ))); + } + return Err(error); + } + Ok(()) +} + #[cfg(test)] #[path = "tests/manager.rs"] mod tests; diff --git a/src/instance/tests/config_sync.rs b/src/instance/tests/config_sync.rs index c8f2818..aecb07f 100644 --- a/src/instance/tests/config_sync.rs +++ b/src/instance/tests/config_sync.rs @@ -449,6 +449,14 @@ fn failed_profile_save_restores_previous_files() { "local" ); assert!(!minecraft.join("config/shared.txt").exists()); + assert_eq!( + std::fs::read(meta.join("state/profiles/main/options.txt")).unwrap(), + b"shared-options" + ); + assert_eq!( + std::fs::read(meta.join("state/profiles/main/config/shared.txt")).unwrap(), + b"shared" + ); } #[test] @@ -479,3 +487,876 @@ fn second_instance_uses_profile_options_saved_by_first_instance() { "second-local" ); } + +#[test] +fn options_commit_failure_restores_the_entire_payload() { + for sync in [sync_to_profile as fn(&Path, &Path) -> _, sync_from_profile] { + let tmp = tempfile::tempdir().unwrap(); + let src = tmp.path().join("source"); + let dst = tmp.path().join("target"); + std::fs::create_dir_all(src.join("config")).unwrap(); + std::fs::create_dir_all(dst.join("config")).unwrap(); + std::fs::create_dir_all(dst.join("optionsz.txt")).unwrap(); + std::fs::write(src.join("config/new"), b"new").unwrap(); + std::fs::write(src.join("options.txt"), b"new-options").unwrap(); + std::fs::write(src.join("optionsz.txt"), b"collision").unwrap(); + std::fs::write(dst.join("config/old"), b"old").unwrap(); + std::fs::write(dst.join("options.txt"), b"old-options").unwrap(); + std::fs::write(dst.join("optionslegacy.txt"), b"legacy").unwrap(); + std::fs::write(dst.join("optionsz.txt/keep"), b"keep").unwrap(); + assert!(sync(&src, &dst).is_err()); + assert_eq!(std::fs::read(dst.join("config/old")).unwrap(), b"old"); + assert!(!dst.join("config/new").exists()); + assert_eq!( + std::fs::read(dst.join("options.txt")).unwrap(), + b"old-options" + ); + assert_eq!( + std::fs::read(dst.join("optionslegacy.txt")).unwrap(), + b"legacy" + ); + assert_eq!( + std::fs::read(dst.join("optionsz.txt/keep")).unwrap(), + b"keep" + ); + assert!(!tmp.path().join(".target.sync-backup").exists()); + } +} + +#[test] +fn failed_rollback_retains_original_payload_backup() { + let tmp = tempfile::tempdir().unwrap(); + let src = tmp.path().join("source"); + let dst = tmp.path().join("target"); + std::fs::create_dir_all(src.join("config")).unwrap(); + std::fs::create_dir_all(dst.join("config")).unwrap(); + std::fs::write(src.join("config/value"), b"new").unwrap(); + std::fs::write(dst.join("config/value"), b"original").unwrap(); + std::fs::write(dst.join("options.txt"), b"original-options").unwrap(); + let error = mirror_payload(&src, &dst, true, || { + std::fs::rename(&dst, tmp.path().join("displaced"))?; + std::fs::write(&dst, b"blocks restoration")?; + Err::<(), _>(ConfigSyncError::Save("injected failure".to_owned())) + }) + .unwrap_err(); + assert!(matches!(error, ConfigSyncError::SaveRollback { .. })); + let backup = tmp.path().join(".target.sync-backup"); + assert_eq!( + std::fs::read(backup.join("config/value")).unwrap(), + b"original" + ); + assert_eq!( + std::fs::read(backup.join("options.txt")).unwrap(), + b"original-options" + ); +} + +#[test] +fn failed_switch_io_does_not_save_selection_or_change_local_files() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let instance = tmp.path().join("instance"); + let local = minecraft_dir(&instance); + let profile = profile_dir(&meta, "main"); + std::fs::create_dir_all(local.join("config")).unwrap(); + std::fs::create_dir_all(local.join("optionsz.txt")).unwrap(); + std::fs::create_dir_all(profile.join("config")).unwrap(); + std::fs::write(local.join("config/value"), b"local").unwrap(); + std::fs::write(local.join("options.txt"), b"local-options").unwrap(); + std::fs::write(profile.join("config/value"), b"profile").unwrap(); + std::fs::write(profile.join("optionsz.txt"), b"collision").unwrap(); + let mut saved = false; + assert!( + switch_profile_and_persist("inst", None, Some("main"), &meta, &instance, |_| { + saved = true; + Ok::<(), std::io::Error>(()) + }) + .is_err() + ); + assert!(!saved); + assert_eq!(std::fs::read(local.join("config/value")).unwrap(), b"local"); + assert_eq!( + std::fs::read(local.join("options.txt")).unwrap(), + b"local-options" + ); +} + +#[test] +fn failed_publication_recovers_local_changes_before_the_next_import() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let local = tmp.path().join("instance/minecraft"); + std::fs::create_dir_all(local.join("config")).unwrap(); + std::fs::write(local.join("config/value"), b"original").unwrap(); + create_profile(&meta, "main").unwrap(); + let lock = prepare_for_launch(Some("main"), &meta, &local) + .unwrap() + .unwrap(); + let profile = profile_dir(&meta, "main"); + std::fs::write(local.join("config/value"), b"changed").unwrap(); + std::fs::write(local.join("optionsz.txt"), b"changed-options").unwrap(); + std::fs::create_dir(profile.join("optionsz.txt")).unwrap(); + assert!(finish_launch(lock, &local).is_err()); + assert!(unsynced_marker(&profile).exists()); + assert!(prepare_for_launch(Some("main"), &meta, &local).is_err()); + assert_eq!( + std::fs::read(local.join("config/value")).unwrap(), + b"changed" + ); + std::fs::remove_dir(profile.join("optionsz.txt")).unwrap(); + let lock = prepare_for_launch(Some("main"), &meta, &local) + .unwrap() + .unwrap(); + assert_eq!( + std::fs::read(local.join("config/value")).unwrap(), + b"changed" + ); + assert_eq!( + std::fs::read(profile.join("config/value")).unwrap(), + b"changed" + ); + assert_eq!( + std::fs::read(profile.join("optionsz.txt")).unwrap(), + b"changed-options" + ); + finish_launch(lock, &local).unwrap(); + assert!(!unsynced_marker(&profile).exists()); +} + +#[test] +fn invalid_recovery_source_keeps_profile_and_local_payloads() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let local = tmp.path().join("instance/minecraft"); + let profile = profile_dir(&meta, "main"); + std::fs::create_dir_all(local.join("config")).unwrap(); + std::fs::create_dir_all(profile.join("config")).unwrap(); + std::fs::write(local.join("config/value"), b"local").unwrap(); + std::fs::write(profile.join("config/value"), b"shared").unwrap(); + std::fs::write( + unsynced_marker(&profile), + serde_json::to_vec(&tmp.path().join("missing")).unwrap(), + ) + .unwrap(); + assert!(prepare_for_launch(Some("main"), &meta, &local).is_err()); + assert!(unsynced_marker(&profile).exists()); + assert_eq!(std::fs::read(local.join("config/value")).unwrap(), b"local"); + assert_eq!( + std::fs::read(profile.join("config/value")).unwrap(), + b"shared" + ); +} + +#[cfg(unix)] +#[test] +fn relative_symlinks_keep_internal_and_external_referents_at_different_depths() { + let tmp = tempfile::tempdir().unwrap(); + let source = tmp.path().join("source"); + let target = tmp.path().join("deep/target"); + std::fs::create_dir_all(source.join("config/nested")).unwrap(); + std::fs::write(tmp.path().join("shared"), b"external").unwrap(); + std::fs::write(source.join("options.txt"), b"options").unwrap(); + std::fs::write(source.join("config/nested/value"), b"nested").unwrap(); + std::os::unix::fs::symlink("value", source.join("config/nested/sibling")).unwrap(); + std::os::unix::fs::symlink("../options.txt", source.join("config/to-options")).unwrap(); + std::os::unix::fs::symlink("config/nested/value", source.join("optionslinked.txt")).unwrap(); + std::os::unix::fs::symlink("missing", source.join("config/dangling")).unwrap(); + std::os::unix::fs::symlink("../../shared", source.join("config/external")).unwrap(); + std::os::unix::fs::symlink("../shared", source.join("optionsexternal.txt")).unwrap(); + sync_to_profile(&source, &target).unwrap(); + std::fs::remove_dir_all(&source).unwrap(); + for (path, bytes) in [ + ("config/nested/sibling", b"nested".as_slice()), + ("config/to-options", b"options".as_slice()), + ("optionslinked.txt", b"nested".as_slice()), + ("config/external", b"external".as_slice()), + ("optionsexternal.txt", b"external".as_slice()), + ] { + assert_eq!(std::fs::read(target.join(path)).unwrap(), bytes, "{path}"); + } + assert_eq!( + std::fs::read_link(target.join("config/dangling")).unwrap(), + Path::new("missing") + ); +} + +fn write_payload(dir: &Path, value: &str) { + std::fs::create_dir_all(dir.join("config")).unwrap(); + std::fs::write(dir.join("config/value"), value).unwrap(); + std::fs::write(dir.join("options.txt"), value).unwrap(); +} + +fn saved_instance( + manager: &crate::instance::InstanceManager, + name: &str, +) -> crate::instance::InstanceConfig { + let config = serde_json::from_value(serde_json::json!({ + "name": name, "game_version": "1.21.1", "loader": "vanilla", "loader_version": null, + "created": "2026-01-01T00:00:00Z" + })) + .unwrap(); + write_payload( + &minecraft_dir(&manager.instances_dir.join(name)), + "local-default", + ); + manager.save(&config).unwrap(); + config +} + +#[test] +fn missing_launch_source_preserves_profile_and_recovery_marker() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let local = tmp.path().join("instance/minecraft"); + write_payload(&local, "keep"); + create_profile(&meta, "main").unwrap(); + let lock = prepare_for_launch(Some("main"), &meta, &local) + .unwrap() + .unwrap(); + std::fs::remove_dir_all(&local).unwrap(); + assert!(finish_launch(lock, &local).is_err()); + let profile = profile_dir(&meta, "main"); + assert_eq!( + std::fs::read(profile.join("config/value")).unwrap(), + b"keep" + ); + assert_eq!(std::fs::read(profile.join("options.txt")).unwrap(), b"keep"); + assert!(unsynced_marker(&profile).exists()); +} + +#[test] +fn missing_seed_source_does_not_initialize_the_profile() { + let tmp = tempfile::tempdir().unwrap(); + create_profile(tmp.path(), "main").unwrap(); + let local = tmp.path().join("missing/minecraft"); + assert!(prepare_for_launch(Some("main"), tmp.path(), &local).is_err()); + let profile = profile_dir(tmp.path(), "main"); + assert!(std::fs::read_dir(&profile).unwrap().next().is_none()); + assert!(!local.exists()); +} + +#[test] +fn missing_switch_source_does_not_publish_or_save_selection() { + let tmp = tempfile::tempdir().unwrap(); + let manager = crate::instance::InstanceManager::new( + tmp.path().join("instances"), + tmp.path().join("meta"), + ); + saved_instance(&manager, "inst"); + let mut config = manager + .save_config_sync_profile("inst", Some("main".to_owned())) + .unwrap(); + let profile = profile_dir(&manager.meta_dir, "main"); + write_payload(&profile, "shared"); + std::fs::remove_dir_all(minecraft_dir(&manager.instances_dir.join("inst"))).unwrap(); + assert!(switch_profile_and_save(&manager, &mut config, None).is_err()); + assert_eq!( + manager + .load_one("inst") + .unwrap() + .config_sync_profile + .as_deref(), + Some("main") + ); + assert_eq!( + std::fs::read(profile.join("config/value")).unwrap(), + b"shared" + ); + assert_eq!( + std::fs::read(profile.join("options.txt")).unwrap(), + b"shared" + ); +} + +#[test] +fn stale_public_config_reloads_current_profile_and_preserves_newer_fields_and_payload() { + let tmp = tempfile::tempdir().unwrap(); + let manager = crate::instance::InstanceManager::new( + tmp.path().join("instances"), + tmp.path().join("meta"), + ); + let mut stale = saved_instance(&manager, "inst"); + let mut current = stale.clone(); + write_payload(&profile_dir(&manager.meta_dir, "a"), "profile-a"); + write_payload(&profile_dir(&manager.meta_dir, "b"), "profile-b"); + switch_profile_and_save(&manager, &mut current, Some("a")).unwrap(); + current.memory_max = Some("8G".to_owned()); + current + .environment + .insert("UPDATED".to_owned(), "yes".to_owned()); + manager.save(¤t).unwrap(); + + let other = minecraft_dir(&manager.instances_dir.join("other")); + write_payload(&other, "other-default"); + let lock = prepare_for_launch(Some("a"), &manager.meta_dir, &other) + .unwrap() + .unwrap(); + write_payload(&other, "newer-a"); + finish_launch(lock, &other).unwrap(); + + switch_profile_and_save(&manager, &mut stale, Some("b")).unwrap(); + assert_eq!(stale, manager.load_one("inst").unwrap()); + assert_eq!(stale.memory_max.as_deref(), Some("8G")); + assert_eq!(stale.environment["UPDATED"], "yes"); + assert_eq!( + std::fs::read(profile_dir(&manager.meta_dir, "a").join("options.txt")).unwrap(), + b"newer-a" + ); + assert_eq!( + std::fs::read(local_backup_dir(&manager.instances_dir.join("inst")).join("options.txt")) + .unwrap(), + b"local-default" + ); + switch_profile_and_save(&manager, &mut stale, None).unwrap(); + assert_eq!( + std::fs::read(minecraft_dir(&manager.instances_dir.join("inst")).join("options.txt")) + .unwrap(), + b"local-default" + ); +} + +#[test] +fn public_switch_preserves_settings_updated_while_selection_save_is_blocked() { + let tmp = tempfile::tempdir().unwrap(); + let manager = crate::instance::InstanceManager::new( + tmp.path().join("instances"), + tmp.path().join("meta"), + ); + let config = saved_instance(&manager, "inst"); + let instance = manager.instances_dir.join("inst"); + write_payload(&profile_dir(&manager.meta_dir, "main"), "shared"); + let config_lock = manager.config_lock("inst").unwrap(); + let instances_dir = manager.instances_dir.clone(); + let meta_dir = manager.meta_dir.clone(); + let worker = std::thread::spawn(move || { + let manager = crate::instance::InstanceManager::new(instances_dir, meta_dir); + let mut config = config; + switch_profile_and_save(&manager, &mut config, Some("main")).unwrap(); + config + }); + let start = std::time::Instant::now(); + while !std::fs::read(minecraft_dir(&instance).join("options.txt")) + .is_ok_and(|bytes| bytes == b"shared") + { + assert!( + start.elapsed() < std::time::Duration::from_secs(5), + "profile payload was not installed before persistence" + ); + std::thread::yield_now(); + } + let mut concurrent = manager.load_one("inst").unwrap(); + assert_eq!(concurrent.config_sync_profile, None); + concurrent.java_path = Some("changed-during-switch".to_owned()); + // This writer owns the config lock while the switch waits to persist its selection. + crate::storage::write_atomic( + &instance.join("instance.json"), + &serde_json::to_vec_pretty(&concurrent).unwrap(), + ) + .unwrap(); + drop(config_lock); + let saved = worker.join().unwrap(); + assert_eq!(saved.java_path.as_deref(), Some("changed-during-switch")); + assert_eq!(saved.config_sync_profile.as_deref(), Some("main")); + assert_eq!(saved, manager.load_one("inst").unwrap()); +} + +#[test] +fn second_instance_switch_recovers_failed_publication_without_overwriting_it() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let profile = profile_dir(&meta, "main"); + let first = tmp.path().join("first/minecraft"); + let second_instance = tmp.path().join("second"); + let second = minecraft_dir(&second_instance); + write_payload(&profile, "original"); + write_payload(&first, "first-default"); + write_payload(&second, "second-default"); + switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap(); + let lock = prepare_for_launch(Some("main"), &meta, &first) + .unwrap() + .unwrap(); + write_payload(&first, "changed"); + std::fs::write(first.join("optionsz.txt"), b"changed-options").unwrap(); + std::fs::create_dir(profile.join("optionsz.txt")).unwrap(); + assert!(finish_launch(lock, &first).is_err()); + assert!(switch_profile("second", Some("main"), None, &meta, &second_instance).is_err()); + assert!(unsynced_marker(&profile).exists()); + assert_eq!( + std::fs::read(second.join("options.txt")).unwrap(), + b"original" + ); + write_payload(&first, "changed-after-failure"); + std::fs::remove_dir(profile.join("optionsz.txt")).unwrap(); + switch_profile("second", Some("main"), None, &meta, &second_instance).unwrap(); + assert_eq!( + std::fs::read(profile.join("options.txt")).unwrap(), + b"changed-after-failure" + ); + assert_eq!( + std::fs::read(first.join("options.txt")).unwrap(), + b"changed-after-failure" + ); + assert_eq!( + std::fs::read(second.join("options.txt")).unwrap(), + b"second-default" + ); + assert!(!unsynced_marker(&profile).exists()); + + let third = tmp.path().join("third/minecraft"); + write_payload(&third, "third-default"); + let lock = prepare_for_launch(Some("main"), &meta, &third) + .unwrap() + .unwrap(); + assert_eq!( + std::fs::read(third.join("options.txt")).unwrap(), + b"changed-after-failure" + ); + finish_launch(lock, &third).unwrap(); +} + +#[test] +fn successful_publication_keeps_stale_copies_from_overwriting_newer_settings() { + for edited in [false, true] { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let profile = profile_dir(&meta, "main"); + let first = tmp.path().join("first/minecraft"); + let second_instance = tmp.path().join("second"); + let second = minecraft_dir(&second_instance); + write_payload(&profile, "original"); + write_payload(&first, "first-default"); + write_payload(&second, "second-default"); + switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap(); + let lock = prepare_for_launch(Some("main"), &meta, &first) + .unwrap() + .unwrap(); + write_payload(&first, "new-shared"); + finish_launch(lock, &first).unwrap(); + if edited { + write_payload(&second, "local-edits"); + } + let baseline = std::fs::read(baseline_path(&second).unwrap()).unwrap(); + let mut saved = false; + let result = switch_profile_and_persist( + "second", + Some("main"), + None, + &meta, + &second_instance, + |_| { + saved = true; + Ok::<(), std::io::Error>(()) + }, + ); + assert_eq!( + std::fs::read(profile.join("options.txt")).unwrap(), + b"new-shared" + ); + if edited { + assert!(matches!(result, Err(ConfigSyncError::Conflict { .. }))); + assert!(!saved); + assert_eq!( + std::fs::read(second.join("options.txt")).unwrap(), + b"local-edits" + ); + assert_eq!( + std::fs::read(baseline_path(&second).unwrap()).unwrap(), + baseline + ); + assert!(matches!( + prepare_for_launch(Some("main"), &meta, &second), + Err(ConfigSyncError::Conflict { .. }) + )); + assert_eq!( + std::fs::read(second.join("options.txt")).unwrap(), + b"local-edits" + ); + } else { + result.unwrap(); + assert!(saved); + assert_eq!( + std::fs::read(second.join("options.txt")).unwrap(), + b"second-default" + ); + } + } +} + +#[test] +fn local_edits_publish_when_the_imported_profile_has_not_changed() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let instance = tmp.path().join("instance"); + let local = minecraft_dir(&instance); + write_payload(&local, "default"); + write_payload(&profile_dir(&meta, "a"), "profile-a"); + write_payload(&profile_dir(&meta, "b"), "profile-b"); + switch_profile("inst", None, Some("a"), &meta, &instance).unwrap(); + write_payload(&local, "local-edits"); + switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap(); + assert_eq!( + std::fs::read(profile_dir(&meta, "a").join("options.txt")).unwrap(), + b"local-edits" + ); + assert_eq!( + std::fs::read(local.join("options.txt")).unwrap(), + b"profile-b" + ); +} + +#[test] +fn untracked_selected_payload_cannot_overwrite_a_different_existing_profile() { + let tmp = tempfile::tempdir().unwrap(); + let instance = tmp.path().join("instance"); + let meta = tmp.path().join("meta"); + write_payload(&minecraft_dir(&instance), "untracked-local"); + let profile = profile_dir(&meta, "main"); + write_payload(&profile, "shared"); + assert!(matches!( + switch_profile("inst", Some("main"), None, &meta, &instance), + Err(ConfigSyncError::Conflict { .. }) + )); + assert_eq!( + std::fs::read(profile.join("options.txt")).unwrap(), + b"shared" + ); + assert_eq!( + std::fs::read(minecraft_dir(&instance).join("options.txt")).unwrap(), + b"untracked-local" + ); +} + +#[test] +fn next_launch_refreshes_an_unchanged_stale_import() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let profile = profile_dir(&meta, "main"); + let first = tmp.path().join("first/minecraft"); + let second_instance = tmp.path().join("second"); + let second = minecraft_dir(&second_instance); + write_payload(&profile, "original"); + write_payload(&first, "first-default"); + write_payload(&second, "second-default"); + switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap(); + let lock = prepare_for_launch(Some("main"), &meta, &first) + .unwrap() + .unwrap(); + write_payload(&first, "new-shared"); + finish_launch(lock, &first).unwrap(); + let lock = prepare_for_launch(Some("main"), &meta, &second) + .unwrap() + .unwrap(); + assert_eq!( + std::fs::read(second.join("options.txt")).unwrap(), + b"new-shared" + ); + finish_launch(lock, &second).unwrap(); + assert_eq!( + std::fs::read(profile.join("options.txt")).unwrap(), + b"new-shared" + ); +} + +#[test] +fn finishing_an_untracked_second_source_cannot_overwrite_a_recovered_origin() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let profile = profile_dir(&meta, "main"); + let first = tmp.path().join("first/minecraft"); + let second = tmp.path().join("second/minecraft"); + write_payload(&profile, "original"); + write_payload(&first, "first-default"); + write_payload(&second, "original"); + let lock = prepare_for_launch(Some("main"), &meta, &first) + .unwrap() + .unwrap(); + write_payload(&first, "new-shared"); + std::fs::write(first.join("optionsz.txt"), b"new-options").unwrap(); + std::fs::create_dir(profile.join("optionsz.txt")).unwrap(); + assert!(finish_launch(lock, &first).is_err()); + std::fs::remove_dir(profile.join("optionsz.txt")).unwrap(); + assert!(matches!( + finish(Some("main"), &meta, &second), + Err(ConfigSyncError::Conflict { .. }) + )); + assert_eq!( + std::fs::read(profile.join("options.txt")).unwrap(), + b"new-shared" + ); + assert_eq!( + std::fs::read(first.join("options.txt")).unwrap(), + b"new-shared" + ); + assert_eq!( + std::fs::read(second.join("options.txt")).unwrap(), + b"original" + ); +} + +#[test] +fn baseline_io_failure_rolls_back_import_without_saving_selection() { + let tmp = tempfile::tempdir().unwrap(); + let manager = crate::instance::InstanceManager::new( + tmp.path().join("instances"), + tmp.path().join("meta"), + ); + let mut config = saved_instance(&manager, "inst"); + let local = minecraft_dir(&manager.instances_dir.join("inst")); + write_payload(&profile_dir(&manager.meta_dir, "main"), "shared"); + let baseline = baseline_path(&local).unwrap(); + std::fs::create_dir_all(&baseline).unwrap(); + std::fs::write(baseline.join("keep"), b"keep").unwrap(); + assert!(switch_profile_and_save(&manager, &mut config, Some("main")).is_err()); + assert_eq!(manager.load_one("inst").unwrap().config_sync_profile, None); + assert_eq!( + std::fs::read(local.join("options.txt")).unwrap(), + b"local-default" + ); + assert_eq!( + std::fs::read(local.join("config/value")).unwrap(), + b"local-default" + ); + assert_eq!(std::fs::read(baseline.join("keep")).unwrap(), b"keep"); +} + +#[cfg(unix)] +#[test] +fn failed_baseline_write_rolls_back_publication_and_remains_recoverable() { + use std::os::unix::fs::PermissionsExt; + + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let local = tmp.path().join("instance/minecraft"); + write_payload(&local, "original"); + create_profile(&meta, "main").unwrap(); + let lock = prepare_for_launch(Some("main"), &meta, &local) + .unwrap() + .unwrap(); + let profile = profile_dir(&meta, "main"); + let baseline = baseline_path(&local).unwrap(); + let original_baseline = std::fs::read(&baseline).unwrap(); + let state = baseline.parent().unwrap(); + let permissions = std::fs::metadata(state).unwrap().permissions(); + std::fs::set_permissions(state, std::fs::Permissions::from_mode(0o500)).unwrap(); + let probe = state.join("write-probe"); + if std::fs::File::create(&probe).is_ok() { + // Privileged runners can bypass the write denial needed for this check. + std::fs::set_permissions(state, permissions).unwrap(); + std::fs::remove_file(probe).unwrap(); + return; + } + + write_payload(&local, "changed"); + std::fs::write( + local.parent().unwrap().join("shared-options"), + b"new-link-data", + ) + .unwrap(); + std::fs::remove_file(local.join("options.txt")).unwrap(); + std::os::unix::fs::symlink("../shared-options", local.join("options.txt")).unwrap(); + let result = finish_launch(lock, &local); + std::fs::set_permissions(state, permissions).unwrap(); + + assert!(matches!(result, Err(ConfigSyncError::Io(_)))); + assert_eq!( + std::fs::read(profile.join("config/value")).unwrap(), + b"original" + ); + assert_eq!( + std::fs::read(profile.join("options.txt")).unwrap(), + b"original" + ); + assert!( + std::fs::symlink_metadata(profile.join("options.txt")) + .unwrap() + .is_file() + ); + assert_eq!(std::fs::read(&baseline).unwrap(), original_baseline); + assert!(unsynced_marker(&profile).exists()); + assert_eq!( + std::fs::read_link(local.join("options.txt")).unwrap(), + Path::new("../shared-options") + ); + + let lock = prepare_for_launch(Some("main"), &meta, &local) + .unwrap() + .unwrap(); + assert_eq!( + std::fs::read(profile.join("config/value")).unwrap(), + b"changed" + ); + assert_eq!( + std::fs::read(profile.join("options.txt")).unwrap(), + b"new-link-data" + ); + assert_eq!( + std::fs::read(local.join("options.txt")).unwrap(), + b"new-link-data" + ); + finish_launch(lock, &local).unwrap(); + assert!(!unsynced_marker(&profile).exists()); +} + +#[test] +fn prepare_rechecks_a_profile_deleted_before_the_locked_payload_phase() { + let tmp = tempfile::tempdir().unwrap(); + create_profile(tmp.path(), "main").unwrap(); + let profile = profile_dir(tmp.path(), "main"); + let lock = acquire_lock(&profile).unwrap(); + std::fs::remove_dir(&profile).unwrap(); + let local = tmp.path().join("instance/minecraft"); + write_payload(&local, "keep"); + assert!(prepare_locked(lock, &local).unwrap().is_none()); + assert!(!profile.exists()); + assert_eq!(std::fs::read(local.join("options.txt")).unwrap(), b"keep"); +} + +#[test] +fn profile_names_are_portable_components() { + for name in [ + "main.", "main ", "NUL", "Con.cfg", "COM1", "COM¹", "LPT9", "C:victim", "a/b", "a\\b", + ] { + assert!( + matches!( + validate_profile(name), + Err(ConfigSyncError::InvalidProfile(_)) + ), + "{name}" + ); + } + let tmp = tempfile::tempdir().unwrap(); + for name in ["main.", "NUL", "C:victim"] { + assert!(create_profile(tmp.path(), name).is_err()); + } + assert!(list_profiles(tmp.path()).unwrap().is_empty()); +} + +#[cfg(unix)] +#[test] +fn dangling_payload_links_remain_internal_but_non_payload_referents_stay_anchored() { + let tmp = tempfile::tempdir().unwrap(); + let source = tmp.path().join("source"); + let profile = tmp.path().join("profile"); + let replay = tmp.path().join("deep/instance/minecraft"); + std::fs::create_dir(&source).unwrap(); + std::os::unix::fs::symlink("optionsbase.txt", source.join("options.txt")).unwrap(); + std::os::unix::fs::symlink("config/value", source.join("optionsconfig.txt")).unwrap(); + std::os::unix::fs::symlink("custom.txt", source.join("optionsexternal.txt")).unwrap(); + std::fs::create_dir(source.join("optionsdir.txt")).unwrap(); + std::fs::write(source.join("optionsdir.txt/value"), b"external-dir").unwrap(); + std::os::unix::fs::symlink("optionsdir.txt/value", source.join("optionsdirectory.txt")) + .unwrap(); + sync_to_profile(&source, &profile).unwrap(); + sync_from_profile(&profile, &replay).unwrap(); + assert_eq!( + std::fs::read_link(replay.join("options.txt")).unwrap(), + Path::new("optionsbase.txt") + ); + assert_eq!( + std::fs::read_link(replay.join("optionsconfig.txt")).unwrap(), + Path::new("config/value") + ); + assert_eq!( + std::fs::read_link(replay.join("optionsexternal.txt")).unwrap(), + source.join("custom.txt") + ); + assert_eq!( + std::fs::read(replay.join("optionsdirectory.txt")).unwrap(), + b"external-dir" + ); + std::fs::remove_dir_all(&source).unwrap(); + std::fs::write(replay.join("optionsbase.txt"), b"new-options").unwrap(); + std::fs::write(replay.join("config/value"), b"new-config").unwrap(); + assert_eq!( + std::fs::read(replay.join("options.txt")).unwrap(), + b"new-options" + ); + assert_eq!( + std::fs::read(replay.join("optionsconfig.txt")).unwrap(), + b"new-config" + ); +} + +#[cfg(unix)] +#[test] +fn failed_selection_save_restores_the_original_option_symlink_and_baseline() { + use std::os::unix::fs::MetadataExt; + let tmp = tempfile::tempdir().unwrap(); + let instance = tmp.path().join("instance"); + let meta = tmp.path().join("meta"); + let local = minecraft_dir(&instance); + write_payload(&local, "default"); + write_payload(&profile_dir(&meta, "a"), "profile-a"); + write_payload(&profile_dir(&meta, "b"), "profile-b"); + switch_profile("inst", None, Some("a"), &meta, &instance).unwrap(); + std::fs::write(instance.join("shared-options"), b"original-link-data").unwrap(); + std::fs::remove_file(local.join("options.txt")).unwrap(); + std::os::unix::fs::symlink("../shared-options", local.join("options.txt")).unwrap(); + let inode = std::fs::symlink_metadata(local.join("options.txt")) + .unwrap() + .ino(); + let error = switch_profile_and_persist("inst", Some("a"), Some("b"), &meta, &instance, |_| { + assert_eq!( + std::fs::read(local.join("options.txt")).unwrap(), + b"profile-b" + ); + Err(std::io::Error::other("selection save failed")) + }) + .unwrap_err(); + assert!(matches!(error, ConfigSyncError::Save(_))); + assert_eq!( + std::fs::read_link(local.join("options.txt")).unwrap(), + Path::new("../shared-options") + ); + assert_eq!( + std::fs::symlink_metadata(local.join("options.txt")) + .unwrap() + .ino(), + inode + ); + assert_eq!( + std::fs::read(instance.join("shared-options")).unwrap(), + b"original-link-data" + ); + let baseline = read_baseline(&local).unwrap().unwrap(); + assert_eq!( + baseline.profile, + std::fs::canonicalize(profile_dir(&meta, "a")).unwrap() + ); + assert_eq!(baseline.local, payload_hash(&local).unwrap()); + // The failed switch must not turn the restored A payload into an untracked export. + switch_profile("inst", Some("a"), None, &meta, &instance).unwrap(); + assert_eq!( + std::fs::read(local.join("options.txt")).unwrap(), + b"default" + ); +} + +#[cfg(unix)] +#[test] +fn profile_root_symlink_aliases_are_not_listed_or_used() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let instance = tmp.path().join("instance"); + let local = minecraft_dir(&instance); + write_payload(&local, "local"); + create_profile(&meta, "real").unwrap(); + let real = profile_dir(&meta, "real"); + write_payload(&real, "shared"); + let alias = profile_dir(&meta, "alias"); + std::os::unix::fs::symlink(&real, &alias).unwrap(); + assert_eq!(list_profiles(&meta).unwrap(), vec!["real"]); + assert!(prepare_for_launch(Some("alias"), &meta, &local).is_err()); + assert!(switch_profile("inst", None, Some("alias"), &meta, &instance).is_err()); + assert!(switch_profile("inst", Some("alias"), Some("alias"), &meta, &instance).is_err()); + assert!(create_profile(&meta, "alias").is_err()); + assert!(delete_profile(&meta, "alias").is_err()); + assert!( + std::fs::symlink_metadata(&alias) + .unwrap() + .file_type() + .is_symlink() + ); + assert_eq!(std::fs::read(real.join("options.txt")).unwrap(), b"shared"); + assert_eq!(std::fs::read(local.join("options.txt")).unwrap(), b"local"); +} diff --git a/src/instance/tests/desktop.rs b/src/instance/tests/desktop.rs index de99ea0..b21fb03 100644 --- a/src/instance/tests/desktop.rs +++ b/src/instance/tests/desktop.rs @@ -26,7 +26,7 @@ fn shortcut_paths_do_not_collide_after_escaping() { 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(); + std::fs::write(&path, build_content("a b", None, "/path with spaces/rmcl")).unwrap(); assert!(owns_legacy_shortcut(&path, "a b")); assert!(!owns_legacy_shortcut(&path, "a_b")); } @@ -34,9 +34,9 @@ fn legacy_shortcut_is_attributed_to_the_right_instance() { #[test] #[cfg(target_os = "linux")] fn build_content_linux() { - let content = build_content("TestPack", None); + let content = build_content("TestPack", None, "/path with spaces/rmcl"); assert!(content.contains("Name=Minecraft - TestPack")); - assert!(content.contains("Exec=rmcl instance launch \"TestPack\"")); + assert!(content.contains("Exec=\"/path with spaces/rmcl\" instance launch \"TestPack\"")); assert!(content.contains("Terminal=false")); assert!(content.contains("Categories=Game;")); } @@ -45,7 +45,7 @@ fn build_content_linux() { #[cfg(target_os = "linux")] fn build_content_linux_with_icon() { let icon = PathBuf::from("/tmp/icon.png"); - let content = build_content("TestPack", Some(&icon)); + let content = build_content("TestPack", Some(&icon), "/bin/rmcl"); assert!(content.contains("Icon=/tmp/icon.png")); } @@ -53,11 +53,200 @@ fn build_content_linux_with_icon() { fn shortcut_arguments_escape_platform_metacharacters() { assert_eq!( quote_desktop_exec_arg("Pack \"$HOME`\\"), - "\"Pack \\\"\\$HOME\\`\\\\\"" + r#""Pack \\"\\$HOME\\`\\\\""# ); + assert_eq!(quote_desktop_exec_arg("Pack%f %Z"), r#""Pack%%f %%Z""#); assert_eq!(quote_shell_arg("Pack 'quoted'"), "'Pack '\\''quoted'\\'''"); assert_eq!( quote_windows_arg("Pack \\\"quoted"), "\"Pack \\\\\\\"quoted\"" ); } + +#[test] +fn shortcuts_use_the_current_executable_and_literal_instance_arguments() { + let executable = "/path with spaces/rmcl"; + let linux = build_linux_desktop("%USERNAME%", None, executable); + assert!(linux.contains("Exec=\"/path with spaces/rmcl\" instance launch \"%%USERNAME%%\"")); + let macos = build_macos_command("%USERNAME%", executable); + assert!(macos.contains("'/path with spaces/rmcl' instance launch '%USERNAME%'")); + let windows = build_windows_shortcut("%USERNAME%", r"C:\path with spaces\rmcl.exe"); + assert!(windows.contains("shell.ShellExecute \"C:\\path with spaces\\rmcl.exe\", \"instance launch \"\"%USERNAME%\"\"\"")); + assert!(!windows.contains("shell.Run")); +} + +#[test] +fn old_bare_executable_shortcuts_remain_owned() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("shortcut"); + #[cfg(target_os = "linux")] + let content = "Exec=rmcl instance launch \"a b\"\n"; + #[cfg(target_os = "macos")] + let content = "#!/bin/bash\nrmcl instance launch 'a b'\n"; + #[cfg(target_os = "windows")] + let content = "shell.Run \"rmcl instance launch \"\"a b\"\"\", 0, False\r\n"; + std::fs::write(&path, content).unwrap(); + assert!(owns_legacy_shortcut(&path, "a b")); + assert!(!owns_legacy_shortcut(&path, "a_b")); +} + +#[test] +fn unicode_windows_scripts_round_trip_and_keep_ownership() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("unicode.vbs"); + let content = format!( + "{}\r\n{}", + shortcut_marker("世界"), + build_windows_shortcut("世界", r"C:\用户\rmcl.exe") + ); + std::fs::write(&path, windows_script_bytes(&content)).unwrap(); + assert_eq!(read_shortcut(&path).unwrap(), content); + assert!(owns_legacy_shortcut(&path, "世界")); + assert!(!owns_legacy_shortcut(&path, "other")); +} + +#[cfg(windows)] +#[test] +fn windows_shortcut_execution_preserves_percent_expressions() { + let temp = tempfile::tempdir().unwrap(); + let output = temp.path().join("literal.txt"); + let powershell = PathBuf::from(std::env::var_os("SystemRoot").unwrap()) + .join("System32/WindowsPowerShell/v1.0/powershell.exe"); + let script = format!( + "[IO.File]::WriteAllText('{}', '%USERNAME% 世界')", + output.display().to_string().replace('\'', "''") + ); + let arguments = format!( + "-NoProfile -NonInteractive -Command {}", + quote_windows_arg(&script) + ); + let shortcut = temp.path().join("literal.vbs"); + std::fs::write( + &shortcut, + windows_script_bytes(&windows_shell_execute( + powershell.to_str().unwrap(), + &arguments, + )), + ) + .unwrap(); + assert!( + std::process::Command::new("cscript.exe") + .arg("//Nologo") + .arg(&shortcut) + .status() + .unwrap() + .success() + ); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !output.exists() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(25)); + } + assert_eq!(std::fs::read_to_string(output).unwrap(), "%USERNAME% 世界"); +} + +#[test] +fn case_only_shortcut_rename_preserves_current_and_legacy_ownership_on_aliasing_volumes() { + let temp = tempfile::tempdir().unwrap(); + let old_path = temp.path().join("CasePack.shortcut"); + let new_path = temp.path().join("casepack.shortcut"); + let current = build_content( + "CasePack", + None, + std::env::current_exe().unwrap().to_str().unwrap(), + ); + #[cfg(target_os = "linux")] + let legacy = "Exec=rmcl instance launch \"CasePack\"\n"; + #[cfg(target_os = "macos")] + let legacy = "#!/bin/bash\nrmcl instance launch 'CasePack'\n"; + #[cfg(target_os = "windows")] + let legacy = "shell.Run \"rmcl instance launch \"\"CasePack\"\"\", 0, False\r\n"; + for content in [current.as_str(), legacy] { + #[cfg(windows)] + let original = windows_script_bytes(content); + #[cfg(not(windows))] + let original = content.as_bytes().to_vec(); + std::fs::write(&old_path, &original).unwrap(); + if !new_path.exists() { + assert!( + !rename_shortcut_alias(&old_path, &new_path, "CasePack", || panic!( + "Distinct paths are not aliases" + )) + .unwrap() + ); + eprintln!("case-insensitive shortcut branch skipped: test volume is case-sensitive"); + return; + } + let failure = rename_shortcut_alias(&old_path, &new_path, "CasePack", || { + Err(std::io::Error::other("test write failure")) + }); + assert!(failure.is_err()); + assert_eq!(std::fs::read(&old_path).unwrap(), original); + assert!(owns_legacy_shortcut(&old_path, "CasePack")); + let updated = build_content( + "casepack", + None, + std::env::current_exe().unwrap().to_str().unwrap(), + ); + #[cfg(windows)] + let bytes = windows_script_bytes(&updated); + #[cfg(not(windows))] + let bytes = updated.as_bytes().to_vec(); + assert!( + rename_shortcut_alias(&old_path, &new_path, "CasePack", || { + crate::storage::write_atomic(&new_path, &bytes) + }) + .unwrap() + ); + assert!(owns_legacy_shortcut(&new_path, "casepack")); + assert!(!owns_legacy_shortcut(&old_path, "CasePack")); + assert!( + std::fs::read_dir(temp.path()) + .unwrap() + .any(|entry| entry.unwrap().file_name() == "casepack.shortcut") + ); + #[cfg(windows)] + assert!(std::fs::read(&new_path).unwrap().starts_with(&[0xff, 0xfe])); + std::fs::remove_file(&new_path).unwrap(); + } +} + +#[test] +fn disabled_or_foreign_shortcuts_are_not_enabled_by_alias_handling() { + let temp = tempfile::tempdir().unwrap(); + let old = temp.path().join("CasePack.shortcut"); + let new = temp.path().join("casepack.shortcut"); + assert!( + !rename_shortcut_alias(&old, &new, "CasePack", || panic!( + "Disabled shortcut must stay disabled" + )) + .unwrap() + ); + assert!(!old.exists() && !new.exists()); + std::fs::write(&old, build_content("other", None, "/launcher")).unwrap(); + assert!( + !rename_shortcut_alias(&old, &new, "CasePack", || panic!( + "Foreign shortcut must stay untouched" + )) + .unwrap() + ); + assert!(owns_legacy_shortcut(&old, "other")); +} + +#[test] +fn distinct_hard_link_shortcuts_are_not_case_aliases() { + let temp = tempfile::tempdir().unwrap(); + let old = temp.path().join("source.shortcut"); + let new = temp.path().join("destination.shortcut"); + std::fs::write(&old, build_content("Pack", None, "/launcher")).unwrap(); + if std::fs::hard_link(&old, &new).is_err() { + eprintln!("hard-link collision check skipped: test volume does not support hard links"); + return; + } + assert!( + !rename_shortcut_alias(&old, &new, "Pack", || panic!( + "Distinct hard links are not aliases" + )) + .unwrap() + ); + assert!(owns_legacy_shortcut(&old, "Pack") && owns_legacy_shortcut(&new, "Pack")); +} diff --git a/src/instance/tests/import/format_detection.rs b/src/instance/tests/import/format_detection.rs index 6354be3..312c2a4 100644 --- a/src/instance/tests/import/format_detection.rs +++ b/src/instance/tests/import/format_detection.rs @@ -80,7 +80,7 @@ fn detect_format_errors_on_missing_file() { #[test] fn unique_name_no_collision() { let tmp = tempfile::tempdir().unwrap(); - let name = unique_instance_name("TestPack", tmp.path()); + let name = unique_instance_name("TestPack", tmp.path()).unwrap(); assert_eq!(name, "TestPack"); } @@ -90,7 +90,7 @@ fn unique_name_with_collision() { let dir = tmp.path().join("TestPack"); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("instance.json"), "{}").unwrap(); - let name = unique_instance_name("TestPack", tmp.path()); + let name = unique_instance_name("TestPack", tmp.path()).unwrap(); assert_eq!(name, "TestPack (2)"); } @@ -99,7 +99,10 @@ fn unique_name_preserves_directory_without_config() { let tmp = tempfile::tempdir().unwrap(); std::fs::create_dir(tmp.path().join("TestPack")).unwrap(); - assert_eq!(unique_instance_name("TestPack", tmp.path()), "TestPack (2)"); + assert_eq!( + unique_instance_name("TestPack", tmp.path()).unwrap(), + "TestPack (2)" + ); assert!(tmp.path().join("TestPack").exists()); } @@ -111,7 +114,7 @@ fn unique_name_multiple_collisions() { std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("instance.json"), "{}").unwrap(); } - let name = unique_instance_name("TestPack", tmp.path()); + let name = unique_instance_name("TestPack", tmp.path()).unwrap(); assert_eq!(name, "TestPack (4)"); } @@ -123,7 +126,10 @@ fn unique_name_keeps_searching_after_ninety_nine_collisions() { 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)"); + assert_eq!( + unique_instance_name("Pack", tmp.path()).unwrap(), + "Pack (101)" + ); } #[test] @@ -185,6 +191,110 @@ fn parse_input_trims_whitespace() { ); } +#[test] +fn windows_and_mixed_case_archive_inputs_stay_local() { + for input in [ + r"C:\Downloads\Pack.ZIP", + r"c:extensionless", + r"C:/Downloads/Pack.MrPaCk", + r"\\server\share\Pack.ZIP", + r"\\server\share\extensionless", + r"\Downloads\extensionless", + r"\\?\C:\Downloads\Pack", + r".\extensionless", + "./extensionless", + "../extensionless", + "Pack.ZIP", + "Pack.MRPACK", + "~/Downloads/Pack.ZIP", + ] { + assert_eq!( + parse_import_input(input), + ImportInput::LocalFile(input.to_owned()), + "{input}" + ); + } + assert_eq!( + parse_import_input("https://modrinth.com/modpack/pack.zip"), + ImportInput::ProjectSlug("pack.zip".to_owned()) + ); +} + +#[test] +fn imported_names_and_pack_paths_are_validated_before_joining() { + let temp = tempfile::tempdir().unwrap(); + for name in ["C:victim", "CON.txt", "trailing.", "../escape"] { + assert!(unique_instance_name(name, temp.path()).is_err(), "{name}"); + cleanup_failed_import( + &InstanceManager::new(temp.path(), temp.path().join("meta")), + name, + ); + } + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0); + std::fs::create_dir(temp.path().join("a".repeat(64))).unwrap(); + assert!(unique_instance_name(&"a".repeat(64), temp.path()).is_err()); + for path in [ + "../escape", + "mods/../../escape", + "C:victim", + r"\\server\share\file", + "/absolute", + "mods/C:victim", + "mods/NUL.jar", + "mods/trailing. ", + "mods/./file", + "mods//file", + ] { + assert!(portable_pack_path(path).is_err(), "{path}"); + } + assert_eq!( + portable_pack_path(r"config\nested\pack.toml").unwrap(), + "config/nested/pack.toml" + ); + assert_eq!( + portable_pack_path(".config/pack.toml").unwrap(), + ".config/pack.toml" + ); +} + +#[tokio::test] +async fn format_import_entry_points_validate_names_before_opening_archives() { + let temp = tempfile::tempdir().unwrap(); + let manager = InstanceManager::new(temp.path().join("instances"), temp.path().join("meta")); + let config = serde_json::from_value(serde_json::json!({ + "name": "C:victim", "game_version": "1.21", "loader": "vanilla", "created": "2026-01-01T00:00:00Z" + })).unwrap(); + let summary = ImportSummary { + name: "Pack".to_owned(), + pack_version: "1".to_owned(), + game_version: "1.21".to_owned(), + loader: crate::instance::ModLoader::Vanilla, + loader_version: None, + mod_count: 0, + override_count: 0, + format: PackFormat::Mrpack, + archive_path: temp.path().join("missing.zip"), + source: None, + }; + for error in [ + mrpack::execute_import(&summary, &manager, &config) + .await + .unwrap_err(), + curseforge::execute_import(&summary, &manager, &config) + .await + .unwrap_err(), + mmc::execute_import(&summary, &manager, &config) + .await + .unwrap_err(), + ] { + assert!( + error.to_string().contains("Invalid instance name"), + "{error}" + ); + } + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0); +} + #[test] fn failed_import_cleanup_removes_the_partial_instance() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/instance/tests/import/mmc.rs b/src/instance/tests/import/mmc.rs index 6460c62..b6e5f2e 100644 --- a/src/instance/tests/import/mmc.rs +++ b/src/instance/tests/import/mmc.rs @@ -127,3 +127,28 @@ fn extract_mmc_archive_rejects_path_traversal() { assert!(error.to_string().contains("archive path")); assert!(!tmp.path().join("escaped.txt").exists()); } + +#[test] +fn mmc_extraction_rejects_windows_reserved_components_on_every_platform() { + use std::io::Write; + let temp = tempfile::tempdir().unwrap(); + for entry in [ + "Pack/.minecraft/config/NUL.txt", + "Pack/.minecraft/config/file:stream", + r"Pack/.minecraft/config\..\..\escaped.txt", + ] { + let path = temp.path().join("pack.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + zip.start_file("Pack/mmc-pack.json", options).unwrap(); + zip.write_all(b"{}").unwrap(); + zip.start_file(entry, options).unwrap(); + zip.write_all(b"unsafe").unwrap(); + zip.finish().unwrap(); + assert!( + extract_mmc_archive(&path, &temp.path().join("minecraft")).is_err(), + "{entry}" + ); + assert!(!temp.path().join("escaped.txt").exists()); + } +} diff --git a/src/instance/tests/import/mrpack.rs b/src/instance/tests/import/mrpack.rs index e0553ff..57d16a0 100644 --- a/src/instance/tests/import/mrpack.rs +++ b/src/instance/tests/import/mrpack.rs @@ -194,6 +194,25 @@ fn extraction_rejects_path_traversal() { assert!(!tmp.path().join("escaped.txt").exists()); } +#[test] +fn overrides_reject_windows_reserved_and_escaping_components_on_every_platform() { + let temp = tempfile::tempdir().unwrap(); + for entry in [ + "overrides/config/NUL.txt", + "overrides/config/file:stream", + "overrides/config/trailing.", + r"overrides/config\..\..\escaped.txt", + ] { + let path = make_mrpack(temp.path(), &[(entry, b"unsafe")]); + assert!(owned_files(&path).is_err(), "{entry}"); + assert!( + extract_overrides(&path, &temp.path().join("minecraft")).is_err(), + "{entry}" + ); + assert!(!temp.path().join("escaped.txt").exists()); + } +} + #[test] fn mod_files_download_to_their_manifest_paths() { let _guard = crate::tests::TEST_LOCK @@ -383,7 +402,7 @@ fn mod_file_removes_downloads_with_invalid_metadata() { #[test] fn import_seeds_exact_modrinth_content_identity() { let tmp = tempfile::tempdir().unwrap(); - let paths = crate::storage::InstancePaths::new(tmp.path()); + let paths = crate::storage::InstancePaths::new(tmp.path().join("Indexed")); let relative_path = PathBuf::from("resourcepacks/example.zip"); std::fs::create_dir_all(paths.minecraft().join("resourcepacks")).unwrap(); std::fs::write(paths.minecraft().join(&relative_path), b"resource pack").unwrap(); diff --git a/src/instance/tests/manager.rs b/src/instance/tests/manager.rs index 2b6f040..8422d56 100644 --- a/src/instance/tests/manager.rs +++ b/src/instance/tests/manager.rs @@ -5,9 +5,6 @@ use super::*; use crate::instance::models::ModLoader; use tempfile::TempDir; -// tmp owns the temp directory; its Drop impl cleans up everything when -// the test ends. the returned InstanceManager points at tmp.path() so -// tests can join("name") off of either to refer to the same locations. fn test_manager() -> (InstanceManager, TempDir) { let tmp = tempfile::tempdir().unwrap(); let meta = tmp.path().join("meta"); @@ -55,6 +52,135 @@ fn validate_name_rejects_empty_traversal_and_hidden() { assert!(validate_name("line\nbreak").is_err()); } +#[test] +fn instance_names_are_portable_components() { + for name in [ + "C:victim", + "C:", + "a:b", + "CON", + "con.txt", + "CON .txt", + "AUX.jar", + "NUL", + "PRN", + "COM1", + "lpt9.log", + "COM¹", + "LPT².txt", + "CLOCK$", + "CONIN$", + "CONOUT$", + "trailing.", + "trailing ", + "bad?name", + "bad*name", + "bad\"name", + "badname", + "bad|name", + r"path\name", + ".", + "..", + ] { + assert!(validate_name(name).is_err(), "{name}"); + } + for name in ["CONifer", "COM0", "COM10", "世界", "%USERNAME%", "My Pack"] { + assert!(validate_name(name).is_ok(), "{name}"); + } +} + +#[tokio::test] +async fn all_manager_entry_points_reject_nonportable_names_before_io() { + let temp = tempfile::tempdir().unwrap(); + let manager = InstanceManager::new(temp.path().join("instances"), temp.path().join("meta")); + for name in ["C:victim", "CON.txt", "trailing.", "bad?name"] { + let config = dummy_config(name); + assert!(matches!( + manager.create(name, "1.21", ModLoader::Vanilla, None).await, + Err(InstanceError::InvalidName(_)) + )); + assert!(matches!( + manager.repair_runtime_cache(&config).await, + Err(InstanceError::InvalidName(_)) + )); + assert!(matches!( + manager.delete(name), + Err(InstanceError::InvalidName(_)) + )); + assert!(matches!( + manager.rename(name, "safe"), + Err(InstanceError::InvalidName(_)) + )); + assert!(matches!( + manager.rename("safe", name), + Err(InstanceError::InvalidName(_)) + )); + assert!(matches!( + manager.load_one(name), + Err(InstanceError::InvalidName(_)) + )); + assert!(matches!( + manager.save(&config), + Err(InstanceError::InvalidName(_)) + )); + assert!(matches!( + manager.save_config_sync_profile(name, Some("shared".to_owned())), + Err(InstanceError::InvalidName(_)) + )); + assert!(matches!( + manager.touch_last_played(name), + Err(InstanceError::InvalidName(_)) + )); + assert!(matches!( + crate::instance::runtime::lock_instance(&manager.instances_dir, name), + Err(InstanceError::InvalidName(_)) + )); + } + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0); +} + +#[cfg(windows)] +#[test] +fn drive_relative_deletion_preserves_an_external_directory() { + const ROOT: &str = "RMCL_NAME_BOUNDARY_ROOT"; + if let Some(root) = std::env::var_os(ROOT) { + let cwd = std::env::current_dir().unwrap(); + let std::path::Component::Prefix(prefix) = cwd.components().next().unwrap() else { + panic!("Expected a Windows drive"); + }; + let drive = match prefix.kind() { + std::path::Prefix::Disk(drive) | std::path::Prefix::VerbatimDisk(drive) => drive, + other => panic!("Expected a local drive, got {other:?}"), + }; + let name = format!("{}:victim", char::from(drive)); + let manager = InstanceManager::new(&root, cwd.join("meta")); + assert!(matches!( + manager.delete(&name), + Err(InstanceError::InvalidName(_)) + )); + assert_eq!(std::fs::read(cwd.join("victim/keep")).unwrap(), b"keep"); + assert!(!cwd.join("victim.lock").exists()); + return; + } + let temp = tempfile::tempdir().unwrap(); + let cwd = temp.path().join("outside"); + std::fs::create_dir_all(cwd.join("victim")).unwrap(); + std::fs::write(cwd.join("victim/keep"), b"keep").unwrap(); + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "instance::manager::tests::drive_relative_deletion_preserves_an_external_directory", + "--nocapture", + ]) + .env(ROOT, temp.path().join("instances")) + .current_dir(&cwd) + .status() + .unwrap(); + assert!(status.success()); + assert_eq!(std::fs::read(cwd.join("victim/keep")).unwrap(), b"keep"); +} + #[test] fn delete_missing_instance_returns_not_found() { let (manager, _tmp) = test_manager(); @@ -80,6 +206,51 @@ fn running_instance_cannot_be_deleted_or_renamed() { assert!(!tmp.path().join("changed").exists()); } +#[test] +fn instance_lock_child() { + use std::io::Write; + let Some(root) = std::env::var_os("RMCL_INSTANCE_LOCK_TEST") else { + return; + }; + let _lock = + crate::instance::runtime::lock_instance(std::path::Path::new(&root), "locked").unwrap(); + println!("LOCKED"); + std::io::stdout().flush().unwrap(); + std::thread::sleep(std::time::Duration::from_secs(10)); +} + +#[test] +fn another_process_protects_the_instance_from_mutation_and_duplicate_launch() { + use std::io::BufRead; + let (manager, temp) = test_manager(); + std::fs::create_dir_all(temp.path().join("locked")).unwrap(); + manager.save(&dummy_config("locked")).unwrap(); + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "instance::manager::tests::instance_lock_child", + "--nocapture", + ]) + .env("RMCL_INSTANCE_LOCK_TEST", temp.path()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let ready = std::io::BufReader::new(child.stdout.take().unwrap()) + .lines() + .any(|line| line.unwrap() == "LOCKED"); + let deletion = manager.delete("locked"); + let rename = manager.rename("locked", "new"); + let launch = crate::instance::runtime::lock_instance(&manager.instances_dir, "locked"); + let _ = child.kill(); + child.wait().unwrap(); + assert!(ready); + assert!(matches!(deletion, Err(InstanceError::InstanceRunning(_)))); + assert!(matches!(rename, Err(InstanceError::InstanceRunning(_)))); + assert!(matches!(launch, Err(InstanceError::InstanceRunning(_)))); + assert!(temp.path().join("locked").is_dir()); + manager.delete("locked").unwrap(); +} + #[test] fn copied_instance_uses_its_directory_as_identity() { let (manager, tmp) = test_manager(); @@ -101,6 +272,45 @@ fn copied_instance_uses_its_directory_as_identity() { ); } +#[test] +fn configuration_locks_survive_instance_directory_replacement() { + let (manager, temp) = test_manager(); + let name = "replaced"; + std::fs::create_dir(temp.path().join(name)).unwrap(); + manager.save(&dummy_config(name)).unwrap(); + let held = manager.config_lock(name).unwrap(); + std::fs::rename(temp.path().join(name), temp.path().join("backup")).unwrap(); + std::fs::create_dir(temp.path().join(name)).unwrap(); + let root = manager.instances_dir.clone(); + let meta = manager.meta_dir.clone(); + let (sender, receiver) = std::sync::mpsc::channel(); + let contender = std::thread::spawn(move || { + let manager = InstanceManager::new(root, meta); + sender.send("attempting").unwrap(); + let _held = manager.config_lock(name).unwrap(); + sender.send("acquired").unwrap(); + }); + assert_eq!( + receiver + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(), + "attempting" + ); + let while_locked = receiver.recv_timeout(std::time::Duration::from_millis(100)); + drop(held); + assert!(matches!( + while_locked, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) + )); + assert_eq!( + receiver + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(), + "acquired" + ); + contender.join().unwrap(); +} + #[tokio::test] async fn create_preserves_directory_without_instance_config() { let (manager, tmp) = test_manager(); @@ -193,6 +403,54 @@ fn rename_moves_dir_and_updates_config_name() { assert_eq!(reloaded.name, "new-name"); } +#[test] +fn case_only_rename_uses_the_actual_volume_and_updates_directory_spelling() { + let (manager, temp) = test_manager(); + let old = format!( + "CasePack-{}", + temp.path().file_name().unwrap().to_str().unwrap() + ); + let new = old.to_lowercase(); + std::fs::create_dir(temp.path().join(&old)).unwrap(); + manager.save(&dummy_config(&old)).unwrap(); + let aliases = temp.path().join(&new).exists(); + assert_eq!( + paths_alias(&temp.path().join(&old), &temp.path().join(&new)).unwrap(), + aliases + ); + manager.rename(&old, &new).unwrap(); + let names: Vec<_> = std::fs::read_dir(temp.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert!(names.iter().any(|name| name.to_str() == Some(new.as_str()))); + assert!(!names.iter().any(|name| name.to_str() == Some(old.as_str()))); + let raw: InstanceConfig = serde_json::from_slice( + &std::fs::read(temp.path().join(&new).join("instance.json")).unwrap(), + ) + .unwrap(); + assert_eq!(raw.name, new); + if !aliases { + std::fs::create_dir(temp.path().join(&old)).unwrap(); + manager.save(&dummy_config(&old)).unwrap(); + assert!(matches!( + manager.rename(&new, &old), + Err(InstanceError::AlreadyExists(_)) + )); + } +} + +#[test] +fn temporary_rename_rolls_back_when_the_second_step_fails() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("Pack"); + std::fs::create_dir(&source).unwrap(); + std::fs::write(source.join("keep"), b"keep").unwrap(); + assert!(rename_path(&source, &temp.path().join("missing/pack"), true).is_err()); + assert_eq!(std::fs::read(source.join("keep")).unwrap(), b"keep"); + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1); +} + #[test] fn rename_to_same_name_is_noop() { let (manager, tmp) = test_manager(); @@ -275,41 +533,73 @@ fn touch_last_played_updates_field() { } #[test] -fn instance_names_are_portable_components() { - for name in [ - "C:victim", - "C:", - "a:b", - "CON", - "con.txt", - "CON .txt", - "AUX.jar", - "NUL", - "PRN", - "COM1", - "lpt9.log", - "COM¹", - "LPT².txt", - "CLOCK$", - "CONIN$", - "CONOUT$", - "trailing.", - "trailing ", - "bad?name", - "bad*name", - "bad\"name", - "badname", - "bad|name", - r"path\name", - ".", - "..", - ] { - assert!(validate_name(name).is_err(), "{name}"); - } - for name in ["CONifer", "COM0", "COM10", "世界", "%USERNAME%", "My Pack"] { - assert!(validate_name(name).is_ok(), "{name}"); +fn ordinary_settings_saves_preserve_profile_selection_and_malformed_config() { + let (manager, temp) = test_manager(); + let name = "settings"; + std::fs::create_dir(temp.path().join(name)).unwrap(); + let mut stale = dummy_config(name); + manager.save(&stale).unwrap(); + manager + .save_config_sync_profile(name, Some("shared".to_owned())) + .unwrap(); + stale.memory_max = Some("8G".to_owned()); + manager.save(&stale).unwrap(); + let current = manager.load_one(name).unwrap(); + assert_eq!(current.config_sync_profile.as_deref(), Some("shared")); + assert_eq!(current.memory_max.as_deref(), Some("8G")); + let path = temp.path().join(name).join("instance.json"); + std::fs::write(&path, b"invalid json").unwrap(); + assert!(matches!(manager.save(&stale), Err(InstanceError::Json(_)))); + assert_eq!(std::fs::read(path).unwrap(), b"invalid json"); +} + +#[test] +fn config_sync_profile_save_preserves_authoritative_settings_and_last_played() { + let (manager, temp) = test_manager(); + let name = "sync-profile"; + let directory = temp.path().join(name); + std::fs::create_dir(&directory).unwrap(); + manager.save(&dummy_config(name)).unwrap(); + let staged = manager.load_one(name).unwrap(); + + let mut latest = staged.clone(); + latest.config_sync_profile = Some("previous".to_owned()); + latest.memory_max = Some("8G".to_owned()); + latest.jvm_args.push("-Dlocal.setting=new".to_owned()); + latest + .environment + .insert("LOCAL_SETTING".to_owned(), "new".to_owned()); + manager.save(&latest).unwrap(); + manager + .save_config_sync_profile(name, latest.config_sync_profile.clone()) + .unwrap(); + manager.touch_last_played(name).unwrap(); + let mut expected = manager.load_one(name).unwrap(); + let before: serde_json::Value = + serde_json::from_slice(&std::fs::read(directory.join("instance.json")).unwrap()).unwrap(); + + for profile in [Some("shared".to_owned()), None] { + expected.config_sync_profile = profile.clone(); + let saved = manager + .save_config_sync_profile(&staged.name, profile) + .unwrap(); + assert_eq!(saved, expected); + assert_eq!(manager.load_one(name).unwrap(), expected); + let after: serde_json::Value = + serde_json::from_slice(&std::fs::read(directory.join("instance.json")).unwrap()) + .unwrap(); + assert_eq!(after["last_played"], before["last_played"]); } + + std::fs::write(directory.join("instance.json"), b"invalid json").unwrap(); + assert!(matches!( + manager.save_config_sync_profile(name, Some("shared".to_owned())), + Err(InstanceError::Json(_)) + )); + assert_eq!( + std::fs::read(directory.join("instance.json")).unwrap(), + b"invalid json" + ); } #[cfg(unix)]