From 9dbbe2d448b1fe54dd137bb121a72af6ec69dcd2 Mon Sep 17 00:00:00 2001 From: objz Date: Sat, 14 Mar 2026 14:15:38 +0100 Subject: [PATCH] feat(import): add import execution with parallel downloads --- src/instance/import.rs | 257 +++++++++++++++++++++++++++++++++++++++++ src/instance/mod.rs | 1 + 2 files changed, 258 insertions(+) create mode 100644 src/instance/import.rs diff --git a/src/instance/import.rs b/src/instance/import.rs new file mode 100644 index 0000000..89075fd --- /dev/null +++ b/src/instance/import.rs @@ -0,0 +1,257 @@ +use std::path::{Path, PathBuf}; + +use crate::instance::manager::InstanceManager; +use crate::instance::models::ModLoader; +use crate::net::modrinth::MrpackIndex; +use crate::tui::progress; + +#[derive(Debug, Clone)] +pub struct ImportSummary { + pub name: String, + pub pack_version: String, + pub game_version: String, + pub loader: ModLoader, + pub loader_version: Option, + pub mod_count: usize, + pub override_count: usize, + pub mrpack_path: PathBuf, +} + +pub fn build_summary(index: &MrpackIndex, mrpack_path: PathBuf) -> Result { + let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies) + .ok_or_else(|| "Manifest missing minecraft dependency".to_string())?; + + let (loader_opt, loader_version) = + crate::net::modrinth::loader_from_dependencies(&index.dependencies); + let loader = loader_opt.unwrap_or(ModLoader::Vanilla); + + let override_count = count_overrides(&mrpack_path).unwrap_or(0); + + Ok(ImportSummary { + name: index.name.clone(), + pack_version: index.version_id.clone(), + game_version, + loader, + loader_version, + mod_count: index.files.len(), + override_count, + mrpack_path, + }) +} + +fn count_overrides(mrpack_path: &Path) -> Result { + let file = std::fs::File::open(mrpack_path).map_err(|e| e.to_string())?; + let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; + let count = archive + .file_names() + .filter(|name| { + (name.starts_with("overrides/") || name.starts_with("client-overrides/")) + && !name.ends_with('/') + }) + .count(); + Ok(count) +} + +pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String { + let candidate = base.to_string(); + if !instances_dir.join(&candidate).join("instance.json").exists() { + return candidate; + } + for n in 2..100 { + let candidate = format!("{base} ({n})"); + if !instances_dir.join(&candidate).join("instance.json").exists() { + return candidate; + } + } + format!("{base} (import)") +} + +pub async fn execute_import( + summary: &ImportSummary, + manager: &InstanceManager, +) -> Result> { + let name = unique_instance_name(&summary.name, &manager.instances_dir); + + progress::set_action(format!("Importing '{name}'...")); + progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader)); + + let config = manager + .create( + &name, + &summary.game_version, + summary.loader, + summary.loader_version.as_deref(), + ) + .await + .map_err(|e| -> Box { Box::new(e) })?; + + let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft"); + + let index = crate::net::modrinth::parse_mrpack(&summary.mrpack_path) + .map_err(|e| -> Box { e.into() })?; + + download_mod_files(&index, &minecraft_dir).await?; + + extract_overrides(&summary.mrpack_path, &minecraft_dir)?; + + progress::clear(); + Ok(config) +} + +async fn download_mod_files( + index: &MrpackIndex, + minecraft_dir: &Path, +) -> Result<(), Box> { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + let client = crate::net::HttpClient::new(); + let total = index.files.len(); + let completed = Arc::new(AtomicUsize::new(0)); + + progress::set_action(format!("Downloading mods... 0/{total}")); + + let mut tasks = tokio::task::JoinSet::new(); + let max_concurrent = 10; + let mut file_iter = index.files.iter(); + + for _ in 0..max_concurrent { + if let Some(file) = file_iter.next() { + let client = client.clone(); + let dest = minecraft_dir.join(&file.path); + let url = file.downloads.first().cloned().unwrap_or_default(); + let filename = file + .path + .rsplit('/') + .next() + .unwrap_or(&file.path) + .to_string(); + let completed = completed.clone(); + let total = total; + tasks.spawn(async move { + if let Some(parent) = dest.parent() { + let _ = tokio::fs::create_dir_all(parent).await; + } + progress::set_sub_action(filename); + crate::net::download_file(&client, &url, &dest, |_, _| {}).await?; + let done = completed.fetch_add(1, Ordering::Relaxed) + 1; + progress::set_action(format!("Downloading mods... {done}/{total}")); + Ok::<(), crate::net::NetError>(()) + }); + } + } + + for file in file_iter { + if let Some(result) = tasks.join_next().await { + result + .map_err(|e| -> Box { Box::new(e) })? + .map_err(|e| -> Box { Box::new(e) })?; + } + let client = client.clone(); + let dest = minecraft_dir.join(&file.path); + let url = file.downloads.first().cloned().unwrap_or_default(); + let filename = file + .path + .rsplit('/') + .next() + .unwrap_or(&file.path) + .to_string(); + let completed = completed.clone(); + let total = total; + tasks.spawn(async move { + if let Some(parent) = dest.parent() { + let _ = tokio::fs::create_dir_all(parent).await; + } + progress::set_sub_action(filename); + crate::net::download_file(&client, &url, &dest, |_, _| {}).await?; + let done = completed.fetch_add(1, Ordering::Relaxed) + 1; + progress::set_action(format!("Downloading mods... {done}/{total}")); + Ok::<(), crate::net::NetError>(()) + }); + } + + while let Some(result) = tasks.join_next().await { + result + .map_err(|e| -> Box { Box::new(e) })? + .map_err(|e| -> Box { Box::new(e) })?; + } + + Ok(()) +} + +fn extract_overrides( + mrpack_path: &Path, + minecraft_dir: &Path, +) -> Result<(), Box> { + use std::io::Read; + + progress::set_action("Extracting overrides...".to_string()); + progress::set_sub_action(String::new()); + + let file = std::fs::File::open(mrpack_path)?; + let mut archive = zip::ZipArchive::new(file)?; + + for i in 0..archive.len() { + let mut entry = archive.by_index(i)?; + let entry_name = entry.name().to_string(); + + let relative = entry_name + .strip_prefix("overrides/") + .or_else(|| entry_name.strip_prefix("client-overrides/")); + + let Some(relative) = relative else { + continue; + }; + + if relative.is_empty() || entry_name.ends_with('/') { + let dir = minecraft_dir.join(relative); + std::fs::create_dir_all(dir)?; + continue; + } + + let dest = minecraft_dir.join(relative); + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + + let mut buf = Vec::new(); + entry.read_to_end(&mut buf)?; + std::fs::write(&dest, &buf)?; + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unique_name_no_collision() { + let tmp = tempfile::tempdir().unwrap(); + let name = unique_instance_name("TestPack", tmp.path()); + assert_eq!(name, "TestPack"); + } + + #[test] + fn unique_name_with_collision() { + let tmp = tempfile::tempdir().unwrap(); + 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()); + assert_eq!(name, "TestPack (2)"); + } + + #[test] + fn unique_name_multiple_collisions() { + let tmp = tempfile::tempdir().unwrap(); + for suffix in ["", " (2)", " (3)"] { + let dir = tmp.path().join(format!("TestPack{suffix}")); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("instance.json"), "{}").unwrap(); + } + let name = unique_instance_name("TestPack", tmp.path()); + assert_eq!(name, "TestPack (4)"); + } +} diff --git a/src/instance/mod.rs b/src/instance/mod.rs index 810e16f..5656507 100644 --- a/src/instance/mod.rs +++ b/src/instance/mod.rs @@ -8,6 +8,7 @@ pub mod resource_packs; pub mod screenshots; pub mod shaders; pub mod worlds; +pub mod import; pub use launch::LaunchError; pub use loader::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller};