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:
objz committed 2026-04-20 19:24:47 +02:00
1 parent e1353bbcdd
commit 5f3f7890aa
7 files changed
+552 -234

No files matched your search

+8 -11
View File
@@ -1,7 +1,8 @@
// modpack importing from modrinth (remote slug/url) or local .mrpack files. // modpack importing from modrinth (remote slug/url) or local files (.mrpack, mmc zips).
// resolves the input, downloads if needed, then hands off to the import engine. // resolves the input, downloads if needed, then hands off to the import engine.
use clap::ArgMatches; use clap::ArgMatches;
use crate::instance::import::{parse_import_input, ImportInput};
use crate::instance::InstanceManager; use crate::instance::InstanceManager;
use crate::net::modrinth; use crate::net::modrinth;
@@ -17,18 +18,17 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
let manager = InstanceManager::new(instances_dir, meta_dir); let manager = InstanceManager::new(instances_dir, meta_dir);
let client = crate::net::HttpClient::new(); let client = crate::net::HttpClient::new();
// figure out what the user gave us: a local file, a project slug, or a versioned URL let parsed = parse_import_input(input);
let parsed = modrinth::parse_input(input);
let mrpack_path = match parsed { let archive_path = match parsed {
modrinth::ModrinthInput::LocalFile(ref path) => { ImportInput::LocalFile(ref path) => {
let resolved = crate::config::settings::resolve_path(path); let resolved = crate::config::settings::resolve_path(path);
if !resolved.exists() { if !resolved.exists() {
return Err(format!("File not found: {}", resolved.display()).into()); return Err(format!("File not found: {}", resolved.display()).into());
} }
resolved resolved
} }
modrinth::ModrinthInput::ProjectSlug(ref slug) => { ImportInput::ProjectSlug(ref slug) => {
println!("Fetching project '{slug}'..."); println!("Fetching project '{slug}'...");
let project = modrinth::fetch_project(&client, slug) let project = modrinth::fetch_project(&client, slug)
.await .await
@@ -64,7 +64,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
.await .await
.map_err(|e| format!("Failed to download .mrpack: {e}"))? .map_err(|e| format!("Failed to download .mrpack: {e}"))?
} }
modrinth::ModrinthInput::VersionId { ImportInput::VersionId {
slug: _, slug: _,
ref version_id, ref version_id,
} => { } => {
@@ -87,10 +87,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
} }
}; };
let index = modrinth::parse_mrpack(&mrpack_path) let mut summary = crate::instance::import::build_summary(&archive_path)
.map_err(|e| format!("Failed to parse .mrpack: {e}"))?;
let mut summary = crate::instance::import::build_summary(&index, mrpack_path)
.map_err(|e| format!("Invalid modpack: {e}"))?; .map_err(|e| format!("Invalid modpack: {e}"))?;
if let Some(name) = override_name { if let Some(name) = override_name {
+273
View File
@@ -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());
}
}
+216
View File
@@ -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())
);
}
}
@@ -1,26 +1,18 @@
// importing modrinth .mrpack modpacks: parse the manifest, create the instance, // modrinth .mrpack import: parse the manifest, download all the mods,
// download all the mods, and extract config/resource overrides from the zip // and extract config/resource overrides from the zip
use std::path::{Path, PathBuf}; use std::path::Path;
use crate::instance::manager::InstanceManager; use crate::instance::manager::InstanceManager;
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
use crate::net::modrinth::MrpackIndex; use crate::net::modrinth::MrpackIndex;
use crate::tui::progress; use crate::tui::progress;
#[derive(Debug, Clone)] use super::{ImportSummary, PackFormat};
pub struct ImportSummary {
pub name: String, pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
pub pack_version: String, let index = crate::net::modrinth::parse_mrpack(path)?;
pub game_version: String,
pub loader: ModLoader,
pub loader_version: Option<String>,
pub mod_count: usize,
pub override_count: usize,
pub mrpack_path: PathBuf,
}
pub fn build_summary(index: &MrpackIndex, mrpack_path: PathBuf) -> Result<ImportSummary, String> {
let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies) let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies)
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?; .ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
@@ -28,7 +20,7 @@ pub fn build_summary(index: &MrpackIndex, mrpack_path: PathBuf) -> Result<Import
crate::net::modrinth::loader_from_dependencies(&index.dependencies); crate::net::modrinth::loader_from_dependencies(&index.dependencies);
let loader = loader_opt.unwrap_or(ModLoader::Vanilla); let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
let override_count = count_overrides(&mrpack_path).unwrap_or(0); let override_count = count_overrides(path).unwrap_or(0);
Ok(ImportSummary { Ok(ImportSummary {
name: index.name.clone(), name: index.name.clone(),
@@ -38,7 +30,8 @@ pub fn build_summary(index: &MrpackIndex, mrpack_path: PathBuf) -> Result<Import
loader_version, loader_version,
mod_count: index.files.len(), mod_count: index.files.len(),
override_count, override_count,
mrpack_path, format: PackFormat::Mrpack,
archive_path: path.to_path_buf(),
}) })
} }
@@ -56,25 +49,11 @@ fn count_overrides(mrpack_path: &Path) -> Result<usize, String> {
Ok(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( pub async fn execute_import(
summary: &ImportSummary, summary: &ImportSummary,
manager: &InstanceManager, manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> { ) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
let name = unique_instance_name(&summary.name, &manager.instances_dir); let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
progress::set_action(format!("Importing '{name}'...")); progress::set_action(format!("Importing '{name}'..."));
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader)); progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
@@ -91,12 +70,12 @@ pub async fn execute_import(
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft"); let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft");
let index = crate::net::modrinth::parse_mrpack(&summary.mrpack_path) let index = crate::net::modrinth::parse_mrpack(&summary.archive_path)
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?; .map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
download_mod_files(&index, &minecraft_dir).await?; download_mod_files(&index, &minecraft_dir).await?;
extract_overrides(&summary.mrpack_path, &minecraft_dir)?; extract_overrides(&summary.archive_path, &minecraft_dir)?;
progress::clear(); progress::clear();
Ok(config) Ok(config)
@@ -227,37 +206,3 @@ fn extract_overrides(
Ok(()) 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)");
}
}
+2 -92
View File
@@ -1,5 +1,5 @@
// modrinth modpack support: parses URLs/slugs, fetches project metadata, // modrinth modpack support: fetches project metadata, downloads .mrpack files,
// downloads .mrpack files, and extracts loader info from pack manifests. // and extracts loader info from pack manifests.
use serde::Deserialize; use serde::Deserialize;
use std::collections::HashMap; use std::collections::HashMap;
@@ -51,44 +51,6 @@ pub struct MrpackFile {
pub file_size: u64, pub file_size: u64,
} }
#[derive(Debug, Clone, PartialEq)]
pub enum ModrinthInput {
ProjectSlug(String),
VersionId { slug: String, version_id: String },
LocalFile(String),
}
// figures out what the user gave us: a modrinth URL, a local .mrpack 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_input(input: &str) -> ModrinthInput {
let input = input.trim();
if input.ends_with(".mrpack")
|| input.starts_with('/')
|| input.starts_with("~/")
{
return ModrinthInput::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, ..] => ModrinthInput::VersionId {
slug: slug.to_string(),
version_id: version_id.to_string(),
},
[slug, ..] => ModrinthInput::ProjectSlug(slug.to_string()),
[] => ModrinthInput::ProjectSlug(String::new()),
};
}
ModrinthInput::ProjectSlug(input.to_string())
}
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
// mrpack dependencies use keys like "fabric-loader", "forge", etc. // mrpack dependencies use keys like "fabric-loader", "forge", etc.
@@ -192,58 +154,6 @@ pub fn parse_mrpack(path: &std::path::Path) -> Result<MrpackIndex, String> {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn parse_project_url() {
assert_eq!(
parse_input("https://modrinth.com/modpack/fabulously-optimized"),
ModrinthInput::ProjectSlug("fabulously-optimized".to_string())
);
}
#[test]
fn parse_version_url() {
let result = parse_input("https://modrinth.com/modpack/fabulously-optimized/version/abc123");
assert_eq!(
result,
ModrinthInput::VersionId {
slug: "fabulously-optimized".to_string(),
version_id: "abc123".to_string(),
}
);
}
#[test]
fn parse_local_mrpack() {
assert_eq!(
parse_input("/home/user/pack.mrpack"),
ModrinthInput::LocalFile("/home/user/pack.mrpack".to_string())
);
}
#[test]
fn parse_tilde_path() {
assert_eq!(
parse_input("~/Downloads/pack.mrpack"),
ModrinthInput::LocalFile("~/Downloads/pack.mrpack".to_string())
);
}
#[test]
fn parse_bare_slug() {
assert_eq!(
parse_input("fabulously-optimized"),
ModrinthInput::ProjectSlug("fabulously-optimized".to_string())
);
}
#[test]
fn parse_input_trims_whitespace() {
assert_eq!(
parse_input(" fabulously-optimized "),
ModrinthInput::ProjectSlug("fabulously-optimized".to_string())
);
}
#[test] #[test]
fn loader_from_fabric_deps() { fn loader_from_fabric_deps() {
let mut deps = HashMap::new(); let mut deps = HashMap::new();
@@ -103,7 +103,7 @@ fn render_input_step(
let input_line = if state.input.is_empty() { let input_line = if state.input.is_empty() {
Line::from(vec![ Line::from(vec![
Span::styled( Span::styled(
"URL, slug, or .mrpack path...", "URL, slug, or pack file path...",
Style::default().fg(theme.text_dim()), Style::default().fg(theme.text_dim()),
), ),
Span::styled( Span::styled(
+39 -62
View File
@@ -1,11 +1,11 @@
// state machine for the modpack import wizard. // state machine for the modpack import wizard.
// accepts modrinth URLs, project slugs, version IDs, or local .mrpack paths. // accepts modrinth URLs, project slugs, version IDs, or local pack archives
// for remote packs, it fetches project info then lets the user pick a version. // (.mrpack, mmc/prism zips). remote packs go through version selection,
// local files skip straight to the confirm step. // local files skip straight to the confirm step.
use super::super::new_instance::LoadState; use super::super::new_instance::LoadState;
use crate::instance::import::ImportSummary; use crate::instance::import::{parse_import_input, ImportInput, ImportSummary};
use crate::net::modrinth::{self, ModrinthInput, VersionInfo}; use crate::net::modrinth::{self, VersionInfo};
use crate::tui::widgets::instances; use crate::tui::widgets::instances;
use crate::tui::widgets::search::SearchState; use crate::tui::widgets::search::SearchState;
use crossterm::event::{KeyCode, KeyEvent}; use crossterm::event::{KeyCode, KeyEvent};
@@ -241,19 +241,19 @@ fn start_resolve(state: &mut ImportWizardState) {
tokio::spawn(async move { tokio::spawn(async move {
let client = crate::net::HttpClient::new(); let client = crate::net::HttpClient::new();
let parsed = modrinth::parse_input(&input_text); let parsed = parse_import_input(&input_text);
match parsed { match parsed {
ModrinthInput::ProjectSlug(slug) => { ImportInput::ProjectSlug(slug) => {
resolve_project_slug(state_arc, &client, &slug).await; resolve_project_slug(state_arc, &client, &slug).await;
} }
ModrinthInput::VersionId { ImportInput::VersionId {
slug: _, slug: _,
version_id, version_id,
} => { } => {
resolve_version_id(state_arc, &client, &version_id).await; resolve_version_id(state_arc, &client, &version_id).await;
} }
ModrinthInput::LocalFile(path) => { ImportInput::LocalFile(path) => {
resolve_local_file(state_arc, &path); resolve_local_file(state_arc, &path);
} }
} }
@@ -309,28 +309,21 @@ async fn resolve_version_id(
} }
match modrinth::download_mrpack(client, &version, &tmp_dir).await { match modrinth::download_mrpack(client, &version, &tmp_dir).await {
Ok(mrpack_path) => match modrinth::parse_mrpack(&mrpack_path) { Ok(mrpack_path) => {
Ok(index) => { match crate::instance::import::build_summary(&mrpack_path) {
match crate::instance::import::build_summary(&index, mrpack_path) { Ok(summary) => {
Ok(summary) => { if let Ok(mut s) = state_arc.lock() {
if let Ok(mut s) = state_arc.lock() { s.summary = Some(summary);
s.summary = Some(summary); s.step = ImportStep::Confirm;
s.step = ImportStep::Confirm;
}
} }
Err(e) => set_error_and_back(
&state_arc,
format!("Failed to build summary: {}", e),
ImportStep::Input,
),
} }
Err(e) => set_error_and_back(
&state_arc,
format!("Failed to build summary: {}", e),
ImportStep::Input,
),
} }
Err(e) => set_error_and_back( }
&state_arc,
format!("Failed to parse mrpack: {}", e),
ImportStep::Input,
),
},
Err(e) => set_error_and_back( Err(e) => set_error_and_back(
&state_arc, &state_arc,
format!("Failed to download mrpack: {}", e), format!("Failed to download mrpack: {}", e),
@@ -349,31 +342,22 @@ async fn resolve_version_id(
fn resolve_local_file(state_arc: Arc<Mutex<ImportWizardState>>, path: &str) { fn resolve_local_file(state_arc: Arc<Mutex<ImportWizardState>>, path: &str) {
let resolved = crate::config::settings::resolve_path(path); let resolved = crate::config::settings::resolve_path(path);
match modrinth::parse_mrpack(&resolved) { match crate::instance::import::build_summary(&resolved) {
Ok(index) => { Ok(summary) => {
match crate::instance::import::build_summary(&index, resolved) { if let Ok(mut s) = state_arc.lock() {
Ok(summary) => { s.summary = Some(summary);
if let Ok(mut s) = state_arc.lock() { s.step = ImportStep::Confirm;
s.summary = Some(summary);
s.step = ImportStep::Confirm;
}
}
Err(e) => set_error_and_back(
&state_arc,
format!("Failed to build summary: {}", e),
ImportStep::Input,
),
} }
} }
Err(e) => set_error_and_back( Err(e) => set_error_and_back(
&state_arc, &state_arc,
format!("Failed to parse mrpack: {}", e), format!("Failed to parse pack: {}", e),
ImportStep::Input, ImportStep::Input,
), ),
} }
} }
// user picked a version from the list. download the .mrpack, parse it, // user picked a version from the list. download the .mrpack,
// build a summary, and move to confirm. // build a summary, and move to confirm.
fn start_version_download(state: &mut ImportWizardState) { fn start_version_download(state: &mut ImportWizardState) {
let version = match selected_version(state) { let version = match selected_version(state) {
@@ -399,28 +383,21 @@ fn start_version_download(state: &mut ImportWizardState) {
} }
match modrinth::download_mrpack(&client, &version, &tmp_dir).await { match modrinth::download_mrpack(&client, &version, &tmp_dir).await {
Ok(mrpack_path) => match modrinth::parse_mrpack(&mrpack_path) { Ok(mrpack_path) => {
Ok(index) => { match crate::instance::import::build_summary(&mrpack_path) {
match crate::instance::import::build_summary(&index, mrpack_path) { Ok(summary) => {
Ok(summary) => { if let Ok(mut s) = state_arc.lock() {
if let Ok(mut s) = state_arc.lock() { s.summary = Some(summary);
s.summary = Some(summary); s.step = ImportStep::Confirm;
s.step = ImportStep::Confirm;
}
} }
Err(e) => set_error_and_back(
&state_arc,
format!("Failed to build summary: {}", e),
ImportStep::Version,
),
} }
Err(e) => set_error_and_back(
&state_arc,
format!("Failed to build summary: {}", e),
ImportStep::Version,
),
} }
Err(e) => set_error_and_back( }
&state_arc,
format!("Failed to parse mrpack: {}", e),
ImportStep::Version,
),
},
Err(e) => set_error_and_back( Err(e) => set_error_and_back(
&state_arc, &state_arc,
format!("Failed to download mrpack: {}", e), format!("Failed to download mrpack: {}", e),