From 1079680513dbb26c511b0cc6d60925202d6e485c Mon Sep 17 00:00:00 2001 From: objz Date: Fri, 4 Sep 2026 23:53:35 +0200 Subject: [PATCH] fix(config): preserve values during schema upgrades --- src/cli/mod.rs | 4 +- src/config/mod.rs | 182 ++++++++++++++++++++++++++++------ src/config/tests/loading.rs | 75 +++++++++++++- src/config/theme.rs | 10 +- src/layout_migration.rs | 19 +++- src/migrate.rs | 7 ++ src/tests/layout_migration.rs | 7 ++ src/tui/mod.rs | 9 +- 8 files changed, 273 insertions(+), 40 deletions(-) diff --git a/src/cli/mod.rs b/src/cli/mod.rs index f32af79..e155c3c 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -29,8 +29,8 @@ pub async fn init() { let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); + let config = crate::config::get_config_path().join("config.toml"); if crate::layout_migration::is_needed(&instances_dir, &meta_dir) { - let config = crate::config::get_config_path().join("config.toml"); if let Err(error) = crate::layout_migration::run(&instances_dir, &meta_dir, &config, |progress| { eprintln!( @@ -45,6 +45,8 @@ pub async fn init() { } else if let Err(error) = crate::layout_migration::initialize_new_layout(&meta_dir) { eprintln!("error: cannot initialize metadata layout: {error}"); std::process::exit(1); + } else if let Err(error) = crate::config::upgrade_config_file(&config) { + eprintln!("warning: cannot upgrade launcher config: {error}"); } if crate::layout_migration::cache_rebuild_pending(&meta_dir) { let manager = crate::instance::InstanceManager::new(&instances_dir, &meta_dir); diff --git a/src/config/mod.rs b/src/config/mod.rs index 745649f..77c657a 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -58,6 +58,90 @@ pub fn load_config(config_path: &std::path::Path) -> Result .map(Config::normalize) } +pub(crate) fn upgrade_config_file(path: &std::path::Path) -> io::Result { + let source = match fs::read_to_string(path) { + Ok(source) => source, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + crate::storage::write_atomic( + path, + include_str!("../../assets/config.toml").as_bytes(), + )?; + return Ok(true); + } + Err(error) => return Err(error), + }; + let mut document = parse_toml_document(path, &source)?; + let template = include_str!("../../assets/config.toml") + .parse::() + .map_err(io::Error::other)?; + merge_missing_table(document.as_table_mut(), template.as_table()); + let upgraded = document.to_string(); + toml::from_str::(&upgraded).map_err(|error| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("cannot upgrade {}: {error}", path.display()), + ) + })?; + if upgraded == source { + return Ok(false); + } + crate::storage::write_atomic(path, upgraded.as_bytes())?; + Ok(true) +} + +pub(crate) fn migrate_legacy_data_paths(path: &std::path::Path) -> io::Result { + let Some(data_dir) = dirs_next::data_dir() else { + return Ok(false); + }; + migrate_legacy_data_paths_from(path, &data_dir) +} + +fn migrate_legacy_data_paths_from( + path: &std::path::Path, + data_dir: &std::path::Path, +) -> io::Result { + let source = match fs::read_to_string(path) { + Ok(source) => source, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false), + Err(error) => return Err(error), + }; + let mut document = parse_toml_document(path, &source)?; + let Some(paths) = document + .get_mut("paths") + .and_then(toml_edit::Item::as_table_mut) + else { + return Ok(false); + }; + let old_root = data_dir.join("mcl"); + let new_root = data_dir.join("rmcl"); + let mut changed = false; + for (key, old_path, replacement) in [ + ( + "instances_dir", + old_root.join("instances"), + new_root.join("instances"), + ), + ("meta_dir", old_root.join("meta"), new_root.join("meta")), + ] { + let Some(value) = paths.get_mut(key).and_then(toml_edit::Item::as_value_mut) else { + continue; + }; + if value + .as_str() + .is_some_and(|raw| settings::resolve_path(raw) == old_path) + { + let decor = value.decor().clone(); + *value = toml_edit::Value::from(replacement.to_string_lossy().into_owned()); + *value.decor_mut() = decor; + changed = true; + } + } + if changed { + crate::storage::write_atomic(path, document.to_string().as_bytes())?; + } + Ok(changed) +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct LauncherSettingsSave { pub restart_required: bool, @@ -170,51 +254,69 @@ 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 config.paths.java_path.is_none() + && let Some(paths) = document + .get_mut("paths") + .and_then(|item| item.as_table_mut()) + { + paths.remove("java_path"); + } + let default_paths = settings::Paths::default(); + if let Some(paths) = document + .get_mut("paths") + .and_then(|item| item.as_table_mut()) + { + if config.paths.instances_dir == default_paths.instances_dir { + paths.remove("instances_dir"); + } + if config.paths.meta_dir == default_paths.meta_dir { + paths.remove("meta_dir"); + } + } + if config.defaults.resolution.is_none() + && let Some(defaults) = document + .get_mut("defaults") + .and_then(|item| item.as_table_mut()) + { + defaults.remove("resolution"); + } + }) +} + +pub(crate) fn write_merged_toml_document( + path: &std::path::Path, + value: &T, + edit: F, +) -> io::Result<()> +where + T: serde::Serialize, + F: FnOnce(&mut toml_edit::DocumentMut), +{ let source = match fs::read_to_string(path) { Ok(source) => source, Err(error) if error.kind() == io::ErrorKind::NotFound => String::new(), Err(error) => return Err(error), }; - let mut document = source.parse::().map_err(|error| { - io::Error::new( - io::ErrorKind::InvalidData, - format!("cannot update {}: {error}", path.display()), - ) - })?; - let generated = toml::to_string_pretty(config) + let mut document = parse_toml_document(path, &source)?; + let generated = toml::to_string_pretty(value) .map_err(io::Error::other)? .parse::() .map_err(io::Error::other)?; merge_table(document.as_table_mut(), generated.as_table()); - if config.paths.java_path.is_none() - && let Some(paths) = document - .get_mut("paths") - .and_then(|item| item.as_table_mut()) - { - paths.remove("java_path"); - } - let default_paths = settings::Paths::default(); - if let Some(paths) = document - .get_mut("paths") - .and_then(|item| item.as_table_mut()) - { - if config.paths.instances_dir == default_paths.instances_dir { - paths.remove("instances_dir"); - } - if config.paths.meta_dir == default_paths.meta_dir { - paths.remove("meta_dir"); - } - } - if config.defaults.resolution.is_none() - && let Some(defaults) = document - .get_mut("defaults") - .and_then(|item| item.as_table_mut()) - { - defaults.remove("resolution"); - } + edit(&mut document); crate::storage::write_atomic(path, document.to_string().as_bytes()) } +fn parse_toml_document(path: &std::path::Path, source: &str) -> io::Result { + source.parse::().map_err(|error| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("cannot update {}: {error}", path.display()), + ) + }) +} + fn merge_table(target: &mut toml_edit::Table, source: &toml_edit::Table) { for (key, source_item) in source { if let Some(target_item) = target.get_mut(key) { @@ -239,6 +341,20 @@ fn merge_table(target: &mut toml_edit::Table, source: &toml_edit::Table) { } } +fn merge_missing_table(target: &mut toml_edit::Table, defaults: &toml_edit::Table) { + for (key, default_item) in defaults { + if let Some(target_item) = target.get_mut(key) { + if let (Some(target_table), Some(default_table)) = + (target_item.as_table_mut(), default_item.as_table()) + { + merge_missing_table(target_table, default_table); + } + } else { + target.insert(key, default_item.clone()); + } + } +} + #[cfg(test)] #[path = "tests/loading.rs"] mod tests; diff --git a/src/config/tests/loading.rs b/src/config/tests/loading.rs index 47b7e28..94f0e35 100644 --- a/src/config/tests/loading.rs +++ b/src/config/tests/loading.rs @@ -85,7 +85,7 @@ fn config_normalizes_memory_java_and_notification_bounds() { defaults: settings::Defaults { memory_min: "invalid".to_owned(), memory_max: "1G".to_owned(), - resolution: None, + resolution: Some((0, 1080)), ..Default::default() }, ui: settings::Ui { @@ -136,3 +136,76 @@ fn settings_writer_preserves_comments_and_unknown_keys() { assert!(!saved.contains("instances_dir")); assert!(!saved.contains("meta_dir")); } + +#[test] +fn config_upgrade_adds_new_defaults_without_replacing_old_values() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("config.toml"); + let old = r#"# user comment +[paths] +instances_dir = "/custom/instances" +meta_dir = "/custom/meta" +java_path = "/custom/java" + +[defaults] +memory_min = "1G" +memory_max = "8G" + +[ui] +image_protocol = "kitty" + +[future] +value = 42 +"#; + std::fs::write(&path, old).unwrap(); + + assert!(upgrade_config_file(&path).unwrap()); + let upgraded = std::fs::read_to_string(&path).unwrap(); + let config = load_config(&path).unwrap(); + + assert!(upgraded.contains("# user comment"), "{upgraded}"); + assert!(upgraded.contains("[future]"), "{upgraded}"); + assert!(upgraded.contains("value = 42"), "{upgraded}"); + assert!(upgraded.contains("jvm_args = []"), "{upgraded}"); + assert!( + upgraded.contains("check_modpack_updates = true"), + "{upgraded}" + ); + assert_eq!(config.paths.instances_dir, "/custom/instances"); + assert_eq!(config.paths.meta_dir, "/custom/meta"); + assert_eq!(config.paths.java_path.as_deref(), Some("/custom/java")); + assert_eq!(config.defaults.memory_min, "1G"); + assert_eq!(config.defaults.memory_max, "8G"); + assert_eq!(config.ui.image_protocol, settings::ImageProtocol::Kitty); + + assert!(!upgrade_config_file(&path).unwrap()); + assert_eq!(std::fs::read_to_string(path).unwrap(), upgraded); +} + +#[test] +fn legacy_default_data_paths_follow_the_renamed_data_directory() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("config.toml"); + let data = tmp.path().join("data"); + std::fs::write( + &path, + format!( + "[paths]\ninstances_dir = {:?}\nmeta_dir = {:?}\n", + data.join("mcl/instances").to_string_lossy(), + data.join("mcl/meta").to_string_lossy() + ), + ) + .unwrap(); + + assert!(migrate_legacy_data_paths_from(&path, &data).unwrap()); + let migrated = std::fs::read_to_string(path).unwrap(); + + assert!( + migrated.contains(&data.join("rmcl/instances").to_string_lossy().to_string()), + "{migrated}" + ); + assert!( + migrated.contains(&data.join("rmcl/meta").to_string_lossy().to_string()), + "{migrated}" + ); +} diff --git a/src/config/theme.rs b/src/config/theme.rs index 3629844..49d55fa 100644 --- a/src/config/theme.rs +++ b/src/config/theme.rs @@ -236,10 +236,14 @@ pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result< let mut config = current_theme_config(); config.theme = theme; config.border_style = border_style.clone(); - let serialized = toml::to_string_pretty(&config).map_err(std::io::Error::other)?; - crate::storage::write_atomic( + super::write_merged_toml_document( &super::get_config_path().join("theme.toml"), - serialized.as_bytes(), + &config, + |document| { + if config.custom.is_none() { + document.as_table_mut().remove("custom"); + } + }, )?; THEME.set(resolve_app_theme(&config)); BORDER_STYLE.set(border_style); diff --git a/src/layout_migration.rs b/src/layout_migration.rs index 826a1e3..7a9d97f 100644 --- a/src/layout_migration.rs +++ b/src/layout_migration.rs @@ -138,9 +138,11 @@ pub fn run( if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION) && metadata.cache_rebuild_pending().exists() { + crate::config::upgrade_config_file(config_file)?; return Ok(latest_layout_backup(&metadata).unwrap_or_else(|| metadata.backups())); } if !is_needed(instances_dir, meta_dir) { + crate::config::upgrade_config_file(config_file)?; initialize_new_layout(meta_dir)?; return Ok(metadata.backups()); } @@ -149,7 +151,7 @@ pub fn run( let mut journal = load_or_create_journal(instances_dir, &metadata)?; let instances = instance_directories(instances_dir)?; - let total = instances.len() as u64 + 7; + let total = instances.len() as u64 + 8; let mut current = journal.completed.len() as u64; if !is_complete(&journal, "backup") { @@ -176,6 +178,21 @@ pub fn run( current += 1; } + if !is_complete(&journal, "config") { + report( + MigrationProgress::new( + "Upgrading launcher config", + config_file.display().to_string(), + current, + total, + ) + .with_backup(&journal.backup_dir), + ); + crate::config::upgrade_config_file(config_file)?; + complete(&mut journal, &metadata, "config")?; + current += 1; + } + validate_migration_conflicts(&instances, meta_dir)?; for instance in &instances { diff --git a/src/migrate.rs b/src/migrate.rs index c47743c..2c64ff1 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -27,6 +27,13 @@ pub fn run_legacy_rename() { if let (Some(desk), Some(data)) = (dirs::desktop_dir(), dirs_next::data_dir()) { rewrite_native_desktop_shortcuts(&desk, &data.join(NEW_NAME).join("instances")); } + if let (Some(config_dir), Some(data_dir)) = (dirs_next::config_dir(), dirs_next::data_dir()) + && !data_dir.join(OLD_NAME).exists() + && let Err(error) = + crate::config::migrate_legacy_data_paths(&config_dir.join(NEW_NAME).join("config.toml")) + { + eprintln!("rmcl migration: failed to update legacy config paths: {error}"); + } } fn rename_top_level(old: &Path, new: &Path) { diff --git a/src/tests/layout_migration.rs b/src/tests/layout_migration.rs index ff54e72..479fe0c 100644 --- a/src/tests/layout_migration.rs +++ b/src/tests/layout_migration.rs @@ -38,6 +38,13 @@ fn migration_backs_up_and_renames_instance_directories() { b"options" ); assert!(backup.join("instances/Example/.minecraft").exists()); + assert_eq!( + fs::read_to_string(backup.join("config/config.toml")).unwrap(), + "[paths]" + ); + let upgraded_config = fs::read_to_string(&config).unwrap(); + assert!(upgraded_config.contains("check_modpack_updates = true")); + assert!(upgraded_config.contains("resolution = [854, 480]")); assert!(backup.join("profiles/legacy/main/options.txt").exists()); assert!( backup diff --git a/src/tui/mod.rs b/src/tui/mod.rs index b37d678..f79d343 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -109,11 +109,18 @@ async fn run_layout_migration_screen( let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); + let config = crate::config::get_config_path().join("config.toml"); if !crate::layout_migration::is_needed(&instances_dir, &meta_dir) { crate::layout_migration::initialize_new_layout(&meta_dir)?; + if let Err(error) = crate::config::upgrade_config_file(&config) { + tracing::warn!("Could not upgrade launcher config: {error}"); + crate::feedback::errors::push_message( + tracing::Level::ERROR, + format!("Could not upgrade config.toml: {error}"), + ); + } return Ok(MigrationScreenOutcome::NotNeeded); } - let config = crate::config::get_config_path().join("config.toml"); loop { let progress = Arc::new(Mutex::new(crate::layout_migration::MigrationProgress {