added mmc/prism modpack import and refactored import module
split import.rs into import/ module with mod.rs, mrpack.rs, mmc.rs. auto-detects pack format from zip contents (modrinth.index.json or mmc-pack.json). moved input parsing from net/modrinth.rs to the import module since it handles routing for all formats now.
This commit is contained in:
1 parent
e1353bbcdd
commit
5f3f7890aa
7 files changed
+552
-234
No files matched your search
@@ -0,0 +1,273 @@
|
||||
// multimc / prism launcher instance import: mods and configs are bundled
|
||||
// in the zip. we install the game + loader normally, then extract the
|
||||
// archive contents over it.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::instance::manager::InstanceManager;
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::tui::progress;
|
||||
|
||||
use super::{ImportSummary, PackFormat};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct MmcPack {
|
||||
#[serde(default)]
|
||||
components: Vec<MmcComponent>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct MmcComponent {
|
||||
uid: String,
|
||||
#[serde(default)]
|
||||
version: String,
|
||||
}
|
||||
|
||||
impl MmcPack {
|
||||
fn game_version(&self) -> Option<String> {
|
||||
self.components
|
||||
.iter()
|
||||
.find(|c| c.uid == "net.minecraft")
|
||||
.map(|c| c.version.clone())
|
||||
}
|
||||
|
||||
fn loader(&self) -> (Option<ModLoader>, Option<String>) {
|
||||
let loaders = [
|
||||
("net.fabricmc.fabric-loader", ModLoader::Fabric),
|
||||
("net.minecraftforge", ModLoader::Forge),
|
||||
("net.neoforged", ModLoader::NeoForge),
|
||||
("org.quiltmc.quilt-loader", ModLoader::Quilt),
|
||||
];
|
||||
|
||||
for (uid, loader) in &loaders {
|
||||
if let Some(component) = self.components.iter().find(|c| c.uid == *uid) {
|
||||
return (Some(*loader), Some(component.version.clone()));
|
||||
}
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
let pack = parse_mmc_pack(path)?;
|
||||
|
||||
let game_version = pack
|
||||
.game_version()
|
||||
.ok_or_else(|| "mmc-pack.json missing net.minecraft component".to_string())?;
|
||||
|
||||
let (loader_opt, loader_version) = pack.loader();
|
||||
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
|
||||
|
||||
let name = instance_name_from_cfg(path)
|
||||
.unwrap_or_else(|| "Imported Pack".to_string());
|
||||
|
||||
let (mod_count, override_count) = count_content_files(path)?;
|
||||
|
||||
Ok(ImportSummary {
|
||||
name,
|
||||
pack_version: String::new(),
|
||||
game_version,
|
||||
loader,
|
||||
loader_version,
|
||||
mod_count,
|
||||
override_count,
|
||||
format: PackFormat::Mmc,
|
||||
archive_path: path.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn execute_import(
|
||||
summary: &ImportSummary,
|
||||
manager: &InstanceManager,
|
||||
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let name = super::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<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
||||
|
||||
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft");
|
||||
extract_mmc_archive(&summary.archive_path, &minecraft_dir)?;
|
||||
|
||||
progress::clear();
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
// extracts everything under .minecraft/ from the archive into the instance dir
|
||||
fn extract_mmc_archive(
|
||||
archive_path: &Path,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
use std::io::Read;
|
||||
|
||||
progress::set_action("Extracting pack contents...".to_string());
|
||||
progress::set_sub_action(String::new());
|
||||
|
||||
let file = std::fs::File::open(archive_path)?;
|
||||
let mut archive = zip::ZipArchive::new(file)?;
|
||||
|
||||
let prefix = find_archive_prefix(&archive);
|
||||
let minecraft_prefix = format!("{prefix}.minecraft/");
|
||||
|
||||
let total = archive.len();
|
||||
for i in 0..total {
|
||||
let mut entry = archive.by_index(i)?;
|
||||
let entry_name = entry.name().to_string();
|
||||
|
||||
let Some(relative) = entry_name.strip_prefix(&minecraft_prefix) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if relative.is_empty() || entry_name.ends_with('/') {
|
||||
std::fs::create_dir_all(minecraft_dir.join(relative))?;
|
||||
continue;
|
||||
}
|
||||
|
||||
let dest = minecraft_dir.join(relative);
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let filename = relative.rsplit('/').next().unwrap_or(relative);
|
||||
progress::set_sub_action(filename.to_string());
|
||||
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf)?;
|
||||
std::fs::write(&dest, &buf)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_mmc_pack(path: &Path) -> Result<MmcPack, String> {
|
||||
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open archive: {e}"))?;
|
||||
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
|
||||
|
||||
let entry_name = find_entry(&archive, "mmc-pack.json")
|
||||
.ok_or_else(|| "Missing mmc-pack.json in archive".to_string())?;
|
||||
|
||||
let entry = archive
|
||||
.by_name(&entry_name)
|
||||
.map_err(|e| format!("Failed to read mmc-pack.json: {e}"))?;
|
||||
|
||||
serde_json::from_reader(entry).map_err(|e| format!("Invalid mmc-pack.json: {e}"))
|
||||
}
|
||||
|
||||
fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||
|
||||
let entry_name = find_entry(&archive, "instance.cfg")?;
|
||||
let entry = archive.by_name(&entry_name).ok()?;
|
||||
|
||||
let reader = std::io::BufRead::lines(std::io::BufReader::new(entry));
|
||||
for line in reader.map_while(Result::ok) {
|
||||
if let Some(value) = line.strip_prefix("name=") {
|
||||
let name = value.trim().to_string();
|
||||
if !name.is_empty() {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// finds the prefix for the archive — empty for flat zips, "DirName/" for nested
|
||||
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
|
||||
for name in archive.file_names() {
|
||||
if name.ends_with("mmc-pack.json") {
|
||||
return name.strip_suffix("mmc-pack.json").unwrap_or("").to_string();
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
// looks for a file at root or one level deep (some archives nest everything
|
||||
// under a single top-level directory like "GT New Horizons 2.8.4/")
|
||||
fn find_entry(archive: &zip::ZipArchive<std::fs::File>, filename: &str) -> Option<String> {
|
||||
if archive.file_names().any(|n| n == filename) {
|
||||
return Some(filename.to_string());
|
||||
}
|
||||
for name in archive.file_names() {
|
||||
if name.ends_with(&format!("/{filename}")) && name.matches('/').count() == 1 {
|
||||
return Some(name.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn count_content_files(path: &Path) -> Result<(usize, usize), String> {
|
||||
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
||||
let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
|
||||
let prefix = find_archive_prefix(&archive);
|
||||
|
||||
let minecraft_prefix = format!("{prefix}.minecraft/");
|
||||
let mods_prefix = format!("{prefix}.minecraft/mods/");
|
||||
|
||||
let mut mod_count = 0;
|
||||
let mut override_count = 0;
|
||||
|
||||
for name in archive.file_names() {
|
||||
if name.ends_with('/') {
|
||||
continue;
|
||||
}
|
||||
if name.starts_with(&mods_prefix) {
|
||||
mod_count += 1;
|
||||
} else if name.starts_with(&minecraft_prefix) {
|
||||
override_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok((mod_count, override_count))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_mmc_pack_json() {
|
||||
let json = r#"{
|
||||
"formatVersion": 1,
|
||||
"components": [
|
||||
{
|
||||
"uid": "net.minecraft",
|
||||
"version": "1.7.10",
|
||||
"cachedName": "Minecraft"
|
||||
},
|
||||
{
|
||||
"uid": "net.minecraftforge",
|
||||
"version": "10.13.4.1614",
|
||||
"cachedName": "Forge"
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
let pack: MmcPack = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(pack.game_version(), Some("1.7.10".to_string()));
|
||||
let (loader, version) = pack.loader();
|
||||
assert_eq!(loader, Some(ModLoader::Forge));
|
||||
assert_eq!(version, Some("10.13.4.1614".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_mmc_pack_vanilla() {
|
||||
let json = r#"{
|
||||
"formatVersion": 1,
|
||||
"components": [
|
||||
{"uid": "net.minecraft", "version": "1.21.4"}
|
||||
]
|
||||
}"#;
|
||||
let pack: MmcPack = serde_json::from_str(json).unwrap();
|
||||
assert!(pack.loader().0.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
// modpack importing: parses user input, detects pack format from zip contents,
|
||||
// builds a summary, and delegates the actual import to format-specific modules.
|
||||
|
||||
pub mod mmc;
|
||||
pub mod mrpack;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::instance::manager::InstanceManager;
|
||||
use crate::instance::models::ModLoader;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PackFormat {
|
||||
Mrpack,
|
||||
Mmc,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ImportInput {
|
||||
ProjectSlug(String),
|
||||
VersionId { slug: String, version_id: String },
|
||||
LocalFile(String),
|
||||
}
|
||||
|
||||
// figures out what the user gave us: a modrinth URL, a local pack file,
|
||||
// or just a project slug. accepts a pretty wide range of inputs so users
|
||||
// don't have to think about it.
|
||||
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("~/")
|
||||
{
|
||||
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/"))
|
||||
{
|
||||
let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
|
||||
return match parts.as_slice() {
|
||||
[slug, "version", version_id, ..] => ImportInput::VersionId {
|
||||
slug: slug.to_string(),
|
||||
version_id: version_id.to_string(),
|
||||
},
|
||||
[slug, ..] => ImportInput::ProjectSlug(slug.to_string()),
|
||||
[] => ImportInput::ProjectSlug(String::new()),
|
||||
};
|
||||
}
|
||||
|
||||
ImportInput::ProjectSlug(input.to_string())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ImportSummary {
|
||||
pub name: String,
|
||||
pub pack_version: String,
|
||||
pub game_version: String,
|
||||
pub loader: ModLoader,
|
||||
pub loader_version: Option<String>,
|
||||
pub mod_count: usize,
|
||||
pub override_count: usize,
|
||||
pub format: PackFormat,
|
||||
pub archive_path: PathBuf,
|
||||
}
|
||||
|
||||
// peeks inside a zip to figure out what format it is.
|
||||
// checks for modrinth.index.json first, then mmc-pack.json.
|
||||
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
|
||||
let file = std::fs::File::open(path)
|
||||
.map_err(|e| format!("Cannot open '{}': {e}", path.display()))?;
|
||||
let archive = zip::ZipArchive::new(file)
|
||||
.map_err(|e| format!("Invalid ZIP '{}': {e}", path.display()))?;
|
||||
|
||||
if archive.file_names().any(|n| n == "modrinth.index.json") {
|
||||
return Ok(PackFormat::Mrpack);
|
||||
}
|
||||
|
||||
// mmc-pack.json can be at root or one directory deep
|
||||
if archive.file_names().any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json")) {
|
||||
return Ok(PackFormat::Mmc);
|
||||
}
|
||||
|
||||
Err("Unknown pack format: no modrinth.index.json or mmc-pack.json found".to_string())
|
||||
}
|
||||
|
||||
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
if !path.exists() {
|
||||
return Err(format!("File not found: {}", path.display()));
|
||||
}
|
||||
let format = detect_format(path)?;
|
||||
match format {
|
||||
PackFormat::Mrpack => mrpack::build_summary(path),
|
||||
PackFormat::Mmc => mmc::build_summary(path),
|
||||
}
|
||||
}
|
||||
|
||||
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<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||
match summary.format {
|
||||
PackFormat::Mrpack => mrpack::execute_import(summary, manager).await,
|
||||
PackFormat::Mmc => mmc::execute_import(summary, manager).await,
|
||||
}
|
||||
}
|
||||
|
||||
#[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)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_project_url() {
|
||||
assert_eq!(
|
||||
parse_import_input("https://modrinth.com/modpack/fabulously-optimized"),
|
||||
ImportInput::ProjectSlug("fabulously-optimized".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_version_url() {
|
||||
assert_eq!(
|
||||
parse_import_input("https://modrinth.com/modpack/fabulously-optimized/version/abc123"),
|
||||
ImportInput::VersionId {
|
||||
slug: "fabulously-optimized".to_string(),
|
||||
version_id: "abc123".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_local_mrpack() {
|
||||
assert_eq!(
|
||||
parse_import_input("/home/user/pack.mrpack"),
|
||||
ImportInput::LocalFile("/home/user/pack.mrpack".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_local_zip() {
|
||||
assert_eq!(
|
||||
parse_import_input("GT_New_Horizons.zip"),
|
||||
ImportInput::LocalFile("GT_New_Horizons.zip".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_tilde_path() {
|
||||
assert_eq!(
|
||||
parse_import_input("~/Downloads/pack.mrpack"),
|
||||
ImportInput::LocalFile("~/Downloads/pack.mrpack".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_bare_slug() {
|
||||
assert_eq!(
|
||||
parse_import_input("fabulously-optimized"),
|
||||
ImportInput::ProjectSlug("fabulously-optimized".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_input_trims_whitespace() {
|
||||
assert_eq!(
|
||||
parse_import_input(" fabulously-optimized "),
|
||||
ImportInput::ProjectSlug("fabulously-optimized".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// modrinth .mrpack import: parse the manifest, download all the mods,
|
||||
// and extract config/resource overrides from the zip
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::instance::manager::InstanceManager;
|
||||
use crate::instance::models::ModLoader;
|
||||
use crate::net::modrinth::MrpackIndex;
|
||||
use crate::tui::progress;
|
||||
|
||||
use super::{ImportSummary, PackFormat};
|
||||
|
||||
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
let index = crate::net::modrinth::parse_mrpack(path)?;
|
||||
|
||||
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(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,
|
||||
format: PackFormat::Mrpack,
|
||||
archive_path: path.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
// peek into the zip to count files under overrides/ and client-overrides/
|
||||
fn count_overrides(mrpack_path: &Path) -> Result<usize, String> {
|
||||
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 async fn execute_import(
|
||||
summary: &ImportSummary,
|
||||
manager: &InstanceManager,
|
||||
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let name = super::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<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
||||
|
||||
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft");
|
||||
|
||||
let index = crate::net::modrinth::parse_mrpack(&summary.archive_path)
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
|
||||
|
||||
download_mod_files(&index, &minecraft_dir).await?;
|
||||
|
||||
extract_overrides(&summary.archive_path, &minecraft_dir)?;
|
||||
|
||||
progress::clear();
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
// downloads all mod files listed in the mrpack index, capped at 10 concurrent
|
||||
// downloads to avoid getting rate-limited into oblivion
|
||||
async fn download_mod_files(
|
||||
index: &MrpackIndex,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
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}"));
|
||||
|
||||
// bounded concurrency via manual JoinSet draining: seed with max_concurrent
|
||||
// tasks, then spawn a new one each time one finishes
|
||||
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();
|
||||
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<dyn std::error::Error + Send + Sync> { Box::new(e) })?
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { 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();
|
||||
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<dyn std::error::Error + Send + Sync> { Box::new(e) })?
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_overrides(
|
||||
mrpack_path: &Path,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
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(())
|
||||
}
|
||||
Reference in new issue
Block a user