From e7b549b4a4534484fc5549b20e30a89501c1b019 Mon Sep 17 00:00:00 2001 From: GeckoEidechse <40122905+GeckoEidechse@users.noreply.github.com> Date: Mon, 28 Nov 2022 07:08:12 +0100 Subject: feat: Rebuild `enabledmods.json` if value not found (#69) * feat: Rebuild enabledmods.json if value not found When toggling a mod on enabled mods that is not present in `enabledmods.json` we would previously just error out. Now we rebuild the `enabledmods.json` file in a Northstar compatible format and then toggle the mod in question. * feat: Handle missing or corrupted enabledmods.json * chore: Remove leftover print statement --- src-tauri/src/mod_management/mod.rs | 47 +++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) (limited to 'src-tauri/src') diff --git a/src-tauri/src/mod_management/mod.rs b/src-tauri/src/mod_management/mod.rs index a057532f..09c01593 100644 --- a/src-tauri/src/mod_management/mod.rs +++ b/src-tauri/src/mod_management/mod.rs @@ -10,6 +10,32 @@ use app::get_enabled_mods; use json5; +/// Gets all currently installed and enabled/disabled mods to rebuild `enabledmods.json` +pub fn rebuild_enabled_mods_json(game_install: GameInstall) -> Result<(), String> { + let enabledmods_json_path = format!("{}/R2Northstar/enabledmods.json", game_install.game_path); + let mods_and_properties = get_installed_mods_and_properties(game_install)?; + + // Create new mapping + let mut my_map = serde_json::Map::new(); + + // Build mapping + for ns_mod in mods_and_properties.into_iter() { + my_map.insert(ns_mod.name, serde_json::Value::Bool(ns_mod.enabled)); + } + + // Turn into serde object + let obj = serde_json::Value::Object(my_map); + + // Write to file + std::fs::write( + enabledmods_json_path, + serde_json::to_string_pretty(&obj).unwrap(), + ) + .unwrap(); + + Ok(()) +} + /// Set the status of a passed mod to enabled/disabled pub fn set_mod_enabled_status( game_install: GameInstall, @@ -19,11 +45,28 @@ pub fn set_mod_enabled_status( let enabledmods_json_path = format!("{}/R2Northstar/enabledmods.json", game_install.game_path); // Parse JSON - let mut res: serde_json::Value = get_enabled_mods(game_install)?; + let mut res: serde_json::Value = match get_enabled_mods(game_install.clone()) { + Ok(res) => res, + Err(err) => { + println!("Couldn't parse `enabledmod.json`: {}", err); + println!("Rebuilding file."); + + rebuild_enabled_mods_json(game_install.clone())?; + + // Then try again + let res = get_enabled_mods(game_install.clone())?; + res + } + }; // Check if key exists if res.get(mod_name.clone()).is_none() { - return Err("Value not found in enabledmod.json".to_string()); + // If it doesn't exist, rebuild `enabledmod.json` + println!("Value not found in `enabledmod.json`. Rebuilding file"); + rebuild_enabled_mods_json(game_install.clone())?; + + // Then try again + res = get_enabled_mods(game_install)?; } // Update value -- cgit v1.2.3