From e28bcba3d393fab57f1dc242ab1deb3e179d1225 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:31:52 +0100 Subject: [PATCH] launcher: import a shared instance, or route any dropped file `horizon_launcher::import` works out what a file is from its contents: - a shared instance: a .mrpack needing no mod loader (as `instance export` writes) or a game-folder zip; - a Java modpack: a .mrpack with a loader, or a CurseForge zip; - a resource or shader pack; - a data pack. A shared instance becomes a new instance named after the pack, with "(2)" if the name is taken. Its overrides/ (or the zip's entries) are copied in, but only the files an instance keeps, and only paths that stay inside its folder. Its .mrpack files are downloaded from Modrinth and checked against their SHA-512. If anything fails, the half-made folder is removed. CLI and MCP: `horizon-launcher instance import [--instance ]` does what dropping the file on the window will do. Co-Authored-By: Claude Opus 5.5 --- docs/launcher-commands.md | 11 ++ launcher/src/cli.rs | 55 +++++++++ launcher/src/import.rs | 232 +++++++++++++++++++++++++++++++++++ launcher/src/import/tests.rs | 207 +++++++++++++++++++++++++++++++ launcher/src/lib.rs | 1 + 5 files changed, 506 insertions(+) create mode 100644 launcher/src/import.rs create mode 100644 launcher/src/import/tests.rs diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index dc4179468..63f168e38 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -344,6 +344,17 @@ Export an instance (or a port) to share: its settings, packs, Horizon mods and t MCP: `instance_export`. +## `horizon-launcher instance import` + +Import what a file is, as dropping it on the window does: a shared instance (a .mrpack without mod loaders, such as `instance export` writes, or a game folder zip) becomes a new instance; a Java modpack goes to the Modpacks import; a resource or shader pack into the instance (default: the selected one). + + horizon-launcher instance import + +- `FILE` +- `--instance`: The instance a pack goes into + +MCP: `instance_import`. + ## `horizon-launcher worlds list` The worlds: name, mode, version, last played and size (the default). diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index a2be8f7ed..6139a082b 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -198,6 +198,16 @@ enum InstanceCmd { #[arg(long)] out: Option, }, + /// Import what a file is, as dropping it on the window does: a shared instance (a .mrpack + /// without mod loaders, such as `instance export` writes, or a game folder zip) becomes a + /// new instance; a Java modpack goes to the Modpacks import; a resource or shader pack into + /// the instance (default: the selected one) + Import { + file: PathBuf, + /// The instance a pack goes into + #[arg(long)] + instance: Option, + }, } #[derive(Clone, Copy, clap::ValueEnum)] @@ -1765,6 +1775,51 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { }; changed(instances::edit(&instance, |m| m.version = pin)?) } + InstanceCmd::Import { file, instance } => { + use horizon_launcher::import::{self, Dropped}; + use horizon_launcher::modpacks; + match import::what(&file)? { + Dropped::Instance => { + let i = import::import_instance(&file, &|line, _| eprintln!("{line}"))?; + if as_json { + json(value(&i, false)); + } else { + println!( + "Made the instance {} in {}: horizon-launcher instance select \"{}\"", + i.name, + i.home.display(), + i.name + ); + } + } + Dropped::Modpack => { + let pack = modpacks::import(&file, &|line: String| eprintln!("{line}"))?; + println!("{} ({})", modpacks::outcome(&pack), pack.summary()); + println!( + "Port and play it: horizon-launcher modpack port {}", + pack.slug + ); + } + Dropped::Pack(_) => { + let i = match instance { + Some(name) => instances::find(&name)?, + None => instances::selected(), + }; + let p = horizon_launcher::packs::add(&i.home, &file)?; + println!( + "Added {} to {}: turn it on with horizon-launcher packs on", + p.title, i.name + ); + } + Dropped::DataPack => { + return Err(format!( + "{} is a data pack: put it into a world with horizon-launcher worlds \ + datapack-add ", + file.display() + )) + } + } + } InstanceCmd::Export { instance, format, diff --git a/launcher/src/import.rs b/launcher/src/import.rs new file mode 100644 index 000000000..1d8625748 --- /dev/null +++ b/launcher/src/import.rs @@ -0,0 +1,232 @@ +//! A file dropped on the window (or given to `instance import`): what it is, and an instance +//! made from a shared one. +//! +//! - A `.mrpack` that needs no mod loader (only `minecraft` in its dependencies), such as +//! [`crate::export`] writes, or a `.zip` laid out as a game folder: a new instance. Its +//! `overrides/` (and `client-overrides/`) go into the instance's folder; each of its `files` +//! is downloaded from Modrinth and checked against its SHA-512 (`browser::download`). +//! - A `.mrpack` for a mod loader, or a CurseForge modpack zip (`manifest.json`): a Java +//! modpack, for the Modpacks import (`modpacks::import`). +//! - A zip with `pack.mcmeta`: a data pack (`data/`) or a resource pack; with `shaders/`, or a +//! `.hshader`: a shader pack. +//! +//! Only what an instance holds is taken from a shared zip ([`crate::export::FILES`], +//! [`crate::export::FOLDERS`], `saves/`), and every path is checked to stay inside its folder. +use crate::browser::{download, FileRef}; +use crate::export::{FILES, FOLDERS}; +use crate::instances::{self, Instance}; +use crate::packs; +use std::fs; +use std::io::Read; +use std::path::{Component, Path, PathBuf}; + +const INDEX: &str = "modrinth.index.json"; +/// The `.mrpack` folders copied into the game folder; `server-overrides/` is a server's. +const OVERRIDES: [&str; 2] = ["overrides/", "client-overrides/"]; + +/// What a dropped file is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Dropped { + /// A shared instance: a new instance is made from it. + Instance, + /// A Java modpack, for the Modpacks import. + Modpack, + /// A resource or shader pack, for the selected instance. + Pack(packs::Kind), + /// A data pack: it goes into a world. + DataPack, +} + +fn open(file: &Path) -> Result, String> { + fs::File::open(file) + .ok() + .and_then(|f| zip::ZipArchive::new(f).ok()) + .ok_or_else(|| format!("{} is not a zip file that can be read.", name_of(file))) +} + +fn name_of(file: &Path) -> String { + file.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +fn read_index(zip: &mut zip::ZipArchive) -> Result { + let mut text = Vec::new(); + zip.by_name(INDEX) + .map_err(|_| format!("It has no {INDEX}: not a .mrpack."))? + .take(16 << 20) + .read_to_end(&mut text) + .map_err(|e| e.to_string())?; + serde_json::from_slice(&text).map_err(|e| format!("{INDEX}: {e}")) +} + +/// What `file` is, from its name and what is inside. +pub fn what(file: &Path) -> Result { + let name = name_of(file); + let ext = file + .extension() + .map(|e| e.to_string_lossy().to_ascii_lowercase()); + match ext.as_deref() { + Some("hshader") => return Ok(Dropped::Pack(packs::Kind::Shader)), + Some("mrpack") => { + let index = read_index(&mut open(file)?)?; + let loaders = index["dependencies"] + .as_object() + .is_some_and(|d| d.keys().any(|k| k != "minecraft")); + return Ok(match loaders { + true => Dropped::Modpack, + false => Dropped::Instance, + }); + } + Some("zip") => {} + _ => { + return Err(format!( + "{name} can't be imported: drop a .mrpack, a .zip or a .hshader." + )) + } + } + let zip = open(file)?; + let has = |n: &str| zip.index_for_name(n).is_some(); + let under = |p: &str| zip.file_names().any(|n| n.starts_with(p)); + if has("manifest.json") && !has("pack.mcmeta") { + return Ok(Dropped::Modpack); + } + if has("pack.mcmeta") { + return Ok(match under("data/") { + true => Dropped::DataPack, + false => Dropped::Pack(packs::Kind::Resource), + }); + } + if under("shaders/") { + return Ok(Dropped::Pack(packs::Kind::Shader)); + } + if FILES.iter().any(|f| has(f)) + || under("saves/") + || FOLDERS.iter().any(|f| under(&format!("{f}/"))) + { + return Ok(Dropped::Instance); + } + Err(format!( + "{name} is neither a pack nor a shared instance: nothing in it that Horizon reads." + )) +} + +/// Where an archive entry goes in the instance's folder, when it is one an instance holds and +/// stays inside it. +fn target(home: &Path, relative: &str) -> Option { + let path = Path::new(relative); + if relative.ends_with('/') || !path.components().all(|c| matches!(c, Component::Normal(_))) { + return None; + } + let top = relative.split('/').next()?; + let kept = FILES.contains(&relative) + || (relative.contains('/') && (FOLDERS.contains(&top) || top == "saves")); + kept.then(|| home.join(path)) +} + +/// Makes a new instance from a shared one: `file` is a `.mrpack` without mod loaders or a game +/// folder `.zip`. Named after the pack (or the file), with "(2)" when the name is taken. +pub fn import_instance(file: &Path, progress: &dyn Fn(&str, f32)) -> Result { + import_into(file, progress, &|name| instances::create(name, None)) +} + +/// [`import_instance`] with the instance made by `create`. +pub fn import_into( + file: &Path, + progress: &dyn Fn(&str, f32), + create: &dyn Fn(&str) -> Result, +) -> Result { + if what(file)? != Dropped::Instance { + return Err(format!("{} is not a shared instance.", name_of(file))); + } + let mut zip = open(file)?; + let mrpack = zip.index_for_name(INDEX).is_some(); + let index = match mrpack { + true => Some(read_index(&mut zip)?), + false => None, + }; + let stem = file + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_else(|| "Imported".into()); + let base = index + .as_ref() + .and_then(|i| i["name"].as_str()) + .map(str::trim) + .filter(|n| !n.is_empty()) + .map(str::to_string) + .unwrap_or(stem); + let instance = (1..20) + .map(|n| match n { + 1 => base.clone(), + n => format!("{base} ({n})"), + }) + .find_map(|name| create(&name).ok()) + .ok_or_else(|| format!("Could not make an instance called {base}."))?; + let home = instance.home.clone(); + let filled = fill(&mut zip, index.as_ref(), &home, progress); + if let Err(e) = filled { + let _ = fs::remove_dir_all(&home); + return Err(e); + } + Ok(instance) +} + +fn fill( + zip: &mut zip::ZipArchive, + index: Option<&serde_json::Value>, + home: &Path, + progress: &dyn Fn(&str, f32), +) -> Result<(), String> { + let count = zip.len(); + for i in 0..count { + let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; + let name = entry.name().to_string(); + let relative = match index { + Some(_) => match OVERRIDES.iter().find_map(|o| name.strip_prefix(o)) { + Some(r) => r.to_string(), + None => continue, + }, + None => name.clone(), + }; + let Some(to) = target(home, &relative) else { + continue; + }; + fs::create_dir_all(to.parent().expect("inside home")).map_err(|e| e.to_string())?; + let mut out = fs::File::create(&to).map_err(|e| format!("{}: {e}", to.display()))?; + std::io::copy(&mut entry, &mut out).map_err(|e| format!("{}: {e}", to.display()))?; + progress( + &format!("Copying {relative}"), + (i + 1) as f32 / count as f32, + ); + } + let files = index + .and_then(|i| i["files"].as_array()) + .cloned() + .unwrap_or_default(); + for f in files { + if f["env"]["client"] == "unsupported" { + continue; + } + let relative = f["path"].as_str().unwrap_or_default(); + let to = target(home, relative) + .ok_or_else(|| format!("{relative} isn't a place an instance keeps files."))?; + let file = FileRef { + url: f["downloads"][0].as_str().unwrap_or_default().to_string(), + name: to.file_name().unwrap().to_string_lossy().into_owned(), + size: f["fileSize"].as_u64().unwrap_or(0), + sha512: f["hashes"]["sha512"].as_str().map(str::to_ascii_lowercase), + sha256: None, + sha1: f["hashes"]["sha1"].as_str().map(str::to_ascii_lowercase), + primary: true, + }; + let folder = to.parent().expect("inside home"); + download::fetch(&file, folder, &|p| progress(&file.name, p)) + .map_err(|e| format!("{relative}: {e}"))?; + } + Ok(()) +} + +#[cfg(test)] +#[path = "import/tests.rs"] +mod tests; diff --git a/launcher/src/import/tests.rs b/launcher/src/import/tests.rs new file mode 100644 index 000000000..dcbe0e548 --- /dev/null +++ b/launcher/src/import/tests.rs @@ -0,0 +1,207 @@ +use super::*; +use crate::export::{export, Format}; +use std::io::Write; +use std::time::Duration; + +fn scratch(name: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!( + "horizon-launcher-import-{name}-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + root +} + +fn zip_file(path: &Path, files: &[(&str, &[u8])]) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut zip = zip::ZipWriter::new(fs::File::create(path).unwrap()); + for (name, bytes) in files { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap(); +} + +fn put(path: &Path, bytes: &[u8]) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, bytes).unwrap(); +} + +/// Makes instances as folders of `root`, refusing a name already taken, as the launcher does. +fn maker(root: &Path) -> impl Fn(&str) -> Result + '_ { + move |name: &str| { + let home = root.join(crate::modpacks::slug(name)); + if home.exists() { + return Err(format!("There is already an instance called {name}.")); + } + fs::create_dir_all(&home).unwrap(); + Ok(Instance { + id: crate::modpacks::slug(name), + name: name.into(), + kind: instances::Kind::Own, + work: home.clone(), + home, + icon: None, + group: None, + version: None, + played: Duration::ZERO, + last_played: None, + }) + } +} + +const NONE: &dyn Fn(&str, f32) = &|_, _| {}; + +#[test] +fn says_what_a_dropped_file_is() { + let dir = scratch("what"); + let mrpack = |name: &str, deps: &str| { + let path = dir.join(name); + let index = format!(r#"{{"formatVersion":1,"name":"P","files":[],"dependencies":{deps}}}"#); + zip_file(&path, &[("modrinth.index.json", index.as_bytes())]); + path + }; + let cases: Vec<(PathBuf, Result)> = vec![ + ( + mrpack("shared.mrpack", r#"{"minecraft":"26.3"}"#), + Ok(Dropped::Instance), + ), + ( + mrpack( + "java.mrpack", + r#"{"minecraft":"1.21.1","fabric-loader":"0.16"}"#, + ), + Ok(Dropped::Modpack), + ), + { + let p = dir.join("cf.zip"); + zip_file( + &p, + &[("manifest.json", b"{}"), ("overrides/config/a.toml", b"")], + ); + (p, Ok(Dropped::Modpack)) + }, + { + let p = dir.join("rp.zip"); + zip_file(&p, &[("pack.mcmeta", b"{}"), ("assets/a.png", b"")]); + (p, Ok(Dropped::Pack(packs::Kind::Resource))) + }, + { + let p = dir.join("dp.zip"); + zip_file( + &p, + &[ + ("pack.mcmeta", b"{}"), + ("data/a/function/f.mcfunction", b""), + ], + ); + (p, Ok(Dropped::DataPack)) + }, + { + let p = dir.join("sp.zip"); + zip_file(&p, &[("shaders/final.fsh", b"")]); + (p, Ok(Dropped::Pack(packs::Kind::Shader))) + }, + { + let p = dir.join("glow.hshader"); + put(&p, b"PK"); + (p, Ok(Dropped::Pack(packs::Kind::Shader))) + }, + { + let p = dir.join("folder.zip"); + zip_file( + &p, + &[("options.txt", b"lang:fr_ch\n"), ("saves/W/level.dat", b"")], + ); + (p, Ok(Dropped::Instance)) + }, + { + let p = dir.join("random.zip"); + zip_file(&p, &[("readme.txt", b"")]); + (p, Err(())) + }, + { + let p = dir.join("picture.png"); + put(&p, b"png"); + (p, Err(())) + }, + ]; + for (file, want) in cases { + assert_eq!(what(&file).map_err(|_| ()), want, "{}", file.display()); + } + fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn an_export_comes_back_as_an_instance_and_nothing_escapes_its_folder() { + let dir = scratch("roundtrip"); + let home = dir.join("from"); + put(&home.join("options.txt"), b"lang:fr_ch\n"); + put(&home.join("resourcepacks/Glass.zip"), b"glass"); + put( + &home.join("horizon-mods/coords/horizon-mod.toml"), + b"id = \"coords\"\n", + ); + put(&home.join("saves/Base/region/r.0.0.mca"), b"region"); + put(&home.join("saves/Base/level.dat"), b"not nbt"); + let made = dir.join("instances"); + for format in [Format::Mrpack, Format::Zip] { + let out = dir.join(format!("Shared.{}", format.extension())); + export(&home, "Shared", format, &["Base".into()], &[], &out).unwrap(); + let i = import_into(&out, NONE, &maker(&made)).unwrap(); + for f in [ + "options.txt", + "resourcepacks/Glass.zip", + "horizon-mods/coords/horizon-mod.toml", + "saves/Base/region/r.0.0.mca", + ] { + assert_eq!( + fs::read(i.home.join(f)).unwrap(), + fs::read(home.join(f)).unwrap(), + "{f}" + ); + } + } + // The .mrpack took the pack's name; the zip came second and got "(2)". + assert!(made.join("shared").is_dir() && made.join("shared-2").is_dir()); + + // A zip that reaches out of its folder, or carries what an instance doesn't keep. + let evil = dir.join("evil.zip"); + zip_file( + &evil, + &[ + ("options.txt", b"ok"), + ("../outside.txt", b"no"), + ("saves/../../up.txt", b"no"), + ("logs/latest.log", b"no"), + ("session.json", b"no"), + ], + ); + let i = import_into(&evil, NONE, &maker(&made)).unwrap(); + assert!(i.home.join("options.txt").is_file()); + assert!(!dir.join("outside.txt").exists() && !made.join("up.txt").exists()); + assert!(!i.home.join("logs").exists() && !i.home.join("session.json").exists()); + + // A file to download from anywhere but Modrinth is refused, and the half-made folder goes. + let index = r#"{"formatVersion":1,"name":"Far","dependencies":{"minecraft":"26.3"}, + "files":[{"path":"resourcepacks/x.zip","hashes":{"sha1":"00","sha512":"00"}, + "downloads":["https://example.com/x.zip"],"fileSize":1}]}"#; + let far = dir.join("far.mrpack"); + zip_file(&far, &[("modrinth.index.json", index.as_bytes())]); + let refused = import_into(&far, NONE, &maker(&made)).unwrap_err(); + assert!(refused.contains("resourcepacks/x.zip"), "{refused}"); + assert!(!made.join("far").exists()); + + let java = dir.join("java.mrpack"); + zip_file( + &java, + &[( + "modrinth.index.json", + br#"{"name":"J","files":[],"dependencies":{"neoforge":"21"}}"#, + )], + ); + assert!(import_into(&java, NONE, &maker(&made)).is_err()); + fs::remove_dir_all(&dir).unwrap(); +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index b8ff41253..85238283d 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -10,6 +10,7 @@ pub mod export; #[cfg(unix)] pub mod game_app; pub mod heads; +pub mod import; pub mod instances; pub mod modpacks; pub mod mojang;