Merge pull request #438 from ludovic111/feat/launcher-other-launchers

Launcher: prepare from Prism, MultiMC, Modrinth App, ATLauncher or GDLauncher
This commit is contained in:
Ludovic Marie
2026-10-16 00:53:37 +02:00
committed by GitHub
9 changed files with 872 additions and 93 deletions
+1
View File
@@ -2673,6 +2673,7 @@ dependencies = [
"self-replace",
"serde",
"serde_json",
"sha1",
"tar",
"ureq",
"winresource",
+2
View File
@@ -12,6 +12,8 @@ gpui = "0.2.2"
ureq = { version = "2", features = ["json", "tls"], default-features = false }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Checks the client jar and the version file found in other launchers' folders (sources.rs).
sha1 = "0.10"
pulldown-cmark = { version = "0.12", default-features = false }
flate2 = "1"
tar = { version = "0.4", default-features = false }
+44 -87
View File
@@ -1,6 +1,7 @@
//! Everything that is not UI: GitHub, installs, resource preparation, the game's processes and
//! updates. The GUI, the CLI and the MCP server all go through this module. Functions here
//! block; the GUI runs them on threads and reads their messages.
use crate::sources;
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
@@ -594,17 +595,14 @@ fn reuse_prepared_in(versions: &Path) -> Vec<(String, String)> {
.collect()
}
/// The official launcher's game directory, where horizon-prepare looks by default.
/// The official launcher's game directory, else the first other launcher's found
/// (sources.rs); preparing looks in all of them anyway.
pub fn default_minecraft_dir() -> Option<PathBuf> {
let home = dirs::home_dir()?;
let dir = if cfg!(target_os = "macos") {
home.join("Library/Application Support/minecraft")
} else if cfg!(windows) {
dirs::config_dir()?.join(".minecraft")
} else {
home.join(".minecraft")
};
dir.is_dir().then_some(dir)
let folders = sources::Folders::current()?;
sources::known_folders(sources::Os::current(), &folders)
.into_iter()
.map(|(_, dir)| dir)
.find(|dir| dir.is_dir())
}
fn found(program: &str, arg: &str) -> bool {
@@ -644,59 +642,43 @@ fn preparer_binary(dir: &Path) -> Option<PathBuf> {
binary.is_file().then_some(binary)
}
/// What a Minecraft folder lacks of `version`'s files in the official launcher's layout, or
/// None when it has them.
fn missing_game_files(minecraft: &Path, version: &str) -> Option<String> {
if !minecraft.is_dir() {
return Some("the folder doesn't exist".into());
}
let files = [format!("{version}.json"), format!("{version}.jar")];
let missing: Vec<String> = files
.iter()
.filter(|file| {
!minecraft
.join("versions")
.join(version)
.join(file)
.is_file()
})
.map(|file| format!("versions/{version}/{file}"))
.collect();
(!missing.is_empty()).then(|| format!("no {}", missing.join(" or ")))
}
/// The error when no folder has Minecraft `version`: every folder looked in with what it
/// lacks, and what the player can do about it (#419).
fn not_found(version: &str, checked: &[(PathBuf, String)]) -> String {
let mut text = format!("Minecraft {version} was not found. Horizon looked in:");
for (dir, missing) in checked {
text += &format!("\n {} ({missing})", dir.display());
}
text += &format!(
"\nTo fix it:\n \
• Play {version} once in the official Minecraft launcher, then prepare again.\n \
• Or choose the folder where your launcher keeps Minecraft {version} (Minecraft folder › \
Choose… in the launcher, --minecraft on the command line)."
);
text
}
/// Checks what the preparation needs and picks how to run it. PLAY.txt describes the same
/// steps: the player's own launcher install, the server jar from that version's own json, and
/// Java (and Python, for versions before horizon-prepare).
pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result<Preparer, String> {
/// Java (and Python, for versions before horizon-prepare). Also returns the Minecraft folder
/// to prepare from: `minecraft`, or the files another launcher keeps, linked into the official
/// launcher's layout (sources.rs).
pub fn preparer(
tag: &str,
minecraft: &Path,
log: &dyn Fn(String),
) -> Result<(Preparer, PathBuf), String> {
let version = game_version(tag);
let dir = version_dir(tag);
let reused = horizon_prepare::artifacts::reuse_imported(&dir, &|line| log(line.to_string()))?;
let minecraft = if reused {
minecraft.to_path_buf()
} else {
let pins = read_json(&dir.join("research-lock.json"))
.and_then(|lock| sources::Pins::read(&lock))
.ok_or("The version's research-lock.json doesn't pin the Minecraft files")?;
let known = sources::Folders::current()
.map(|f| sources::known_folders(sources::Os::current(), &f))
.unwrap_or_default();
let fetch = |url: &str| -> Result<Vec<u8>, String> {
let mut body = Vec::new();
get(url)?
.into_reader()
.read_to_end(&mut body)
.map_err(|e| e.to_string())?;
Ok(body)
};
let linked = data_dir().join("linked-minecraft");
sources::resolve(minecraft, &pins, &known, &linked, &fetch, log)?
};
let manifest = minecraft
.join("versions")
.join(&version)
.join(format!("{version}.json"));
if !reused {
if let Some(missing) = missing_game_files(minecraft, &version) {
return Err(not_found(&version, &[(minecraft.to_path_buf(), missing)]));
}
}
let binary = preparer_binary(&dir);
let python = if binary.is_some() {
// The JDK the version pins, found as horizon-prepare finds it, so a missing one is
@@ -743,20 +725,21 @@ pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result<Pre
if horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref()
== Some(horizon_prepare::SOURCES_SHA256)
{
return Ok(Preparer::InProcess(horizon_prepare::Options {
let options = horizon_prepare::Options {
root: dir,
import: !reused,
minecraft_dir: Some(minecraft.to_path_buf()),
minecraft_dir: Some(minecraft.clone()),
server_jar: (!reused).then_some(jar),
}));
};
return Ok((Preparer::InProcess(options), minecraft));
}
let mut cmd = Command::new(binary);
cmd.current_dir(&dir).arg("--root").arg(&dir);
if !reused {
cmd.args(["--prepare", "--server-jar"]).arg(&jar);
}
cmd.arg("--minecraft-dir").arg(minecraft);
return Ok(Preparer::Process(cmd));
cmd.arg("--minecraft-dir").arg(&minecraft);
return Ok((Preparer::Process(cmd), minecraft));
}
let mut cmd = Command::new(python.unwrap());
cmd.current_dir(&dir)
@@ -764,8 +747,8 @@ pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result<Pre
if !reused {
cmd.args(["--prepare", "--server-jar"]).arg(&jar);
}
cmd.arg("--minecraft-dir").arg(minecraft);
Ok(Preparer::Process(cmd))
cmd.arg("--minecraft-dir").arg(&minecraft);
Ok((Preparer::Process(cmd), minecraft))
}
/// Copies the pinned version's sounds from the player's own launcher install into the version's
@@ -1720,32 +1703,6 @@ mod tests {
use super::*;
use std::cmp::Ordering::*;
#[test]
fn a_folder_without_the_game_says_what_it_lacks_and_what_to_do() {
let dir = std::env::temp_dir().join(format!("horizon-missing-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
assert_eq!(
missing_game_files(&dir, "26.3").as_deref(),
Some("the folder doesn't exist")
);
fs::create_dir_all(dir.join("versions/26.3")).unwrap();
assert_eq!(
missing_game_files(&dir, "26.3").as_deref(),
Some("no versions/26.3/26.3.json or versions/26.3/26.3.jar")
);
fs::write(dir.join("versions/26.3/26.3.json"), "{}").unwrap();
let missing = missing_game_files(&dir, "26.3").unwrap();
assert_eq!(missing, "no versions/26.3/26.3.jar");
let error = not_found("26.3", &[(dir.clone(), missing)]);
assert!(error.starts_with("Minecraft 26.3 was not found. Horizon looked in:\n"));
assert!(error.contains(&format!("{} (no versions/26.3/26.3.jar)", dir.display())));
assert!(error.contains("Play 26.3 once in the official Minecraft launcher"));
assert!(error.contains("--minecraft on the command line"));
fs::write(dir.join("versions/26.3/26.3.jar"), "jar").unwrap();
assert_eq!(missing_game_files(&dir, "26.3"), None);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_game_plays_under_its_own_audio_stream_name() {
if std::env::var_os("PIPEWIRE_PROPS").is_some() {
+4 -2
View File
@@ -90,7 +90,8 @@ enum Cmd {
Remove { tag: String },
/// Prepare a version's resources from your own Minecraft install
Prepare {
/// The official launcher's game folder (default: the one the launcher uses)
/// The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App,
/// ATLauncher or GDLauncher (default: the launcher's, then every launcher's default)
#[arg(long)]
minecraft: Option<PathBuf>,
/// The installed version (default: the selected one)
@@ -299,7 +300,8 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
Cmd::Prepare { minecraft, version } => {
let tag = backend::resolve_version(version.as_deref())?;
let minecraft = backend::minecraft_dir(minecraft)?;
let preparer = backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?;
let (preparer, minecraft) =
backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?;
backend::sounds(&tag, &minecraft, &|line| println!("{line}"));
match preparer {
backend::Preparer::Process(cmd) => attached(cmd)?,
+1
View File
@@ -2,4 +2,5 @@
pub mod account;
pub mod backend;
pub mod desktop;
pub mod sources;
pub mod telemetry;
+2 -2
View File
@@ -638,8 +638,8 @@ impl Launcher {
let _ = tx.send(Msg::Line(Job::Prepare, line));
};
let result = backend::preparer(&tag, &minecraft, &log)
.inspect(|_| backend::sounds(&tag, &minecraft, &log))
.and_then(|p| match p {
.inspect(|(_, minecraft)| backend::sounds(&tag, minecraft, &log))
.and_then(|(p, _)| match p {
backend::Preparer::Process(cmd) => {
backend::spawn(Job::Prepare, cmd, tx.clone()).map(|_running| false)
}
+2 -2
View File
@@ -32,7 +32,7 @@ fn tools() -> Value {
{ "name": "remove_version", "description": "Remove an installed Horizon version and its prepared resources.",
"inputSchema": { "type": "object", "properties": { "tag": { "type": "string" } }, "required": ["tag"] } },
{ "name": "prepare_resources", "description": "Prepare a version's resources from the player's own Minecraft install (needs Minecraft 26.3 played once in the official launcher and Java 25; versions before horizon-prepare also need Python 3.10+). Can take several minutes; returns the end of the log.",
"inputSchema": { "type": "object", "properties": { "version": version, "minecraft_dir": { "type": "string", "description": "The official launcher's game folder. Default: the launcher's setting, else the platform default." } } } },
"inputSchema": { "type": "object", "properties": { "version": version, "minecraft_dir": { "type": "string", "description": "The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher. Default: the launcher's setting, then every launcher's default folder." } } } },
{ "name": "launch_client", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world.",
"inputSchema": { "type": "object", "properties": { "version": version,
"world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." },
@@ -120,7 +120,7 @@ impl Session {
let tag = backend::resolve_version(arg_str(args, "version"))?;
let minecraft =
backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?;
let preparer = backend::preparer(&tag, &minecraft, &|_| {})?;
let (preparer, minecraft) = backend::preparer(&tag, &minecraft, &|_| {})?;
let sound = std::cell::RefCell::new(Vec::new());
backend::sounds(&tag, &minecraft, &|line| sound.borrow_mut().push(line));
let (result, tail) = match preparer {
+407
View File
@@ -0,0 +1,407 @@
//! Where the player's own Minecraft files are: the folder they chose, the official launcher's,
//! or another launcher's (Prism Launcher, MultiMC, Modrinth App, ATLauncher, GDLauncher), #434.
//! horizon-prepare reads the official launcher's layout and pins the version JSON's own sha1, so
//! files found elsewhere are linked into that layout in the launcher's data folder, with the
//! pinned version JSON from Mojang when the other launcher keeps its own rewrite of it.
use serde_json::Value;
use sha1::{Digest, Sha1};
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
/// What a version's research-lock.json pins about the game files.
pub struct Pins {
pub version: String,
pub client_sha1: String,
/// The version JSON's sha1, then the earlier ones Mojang republished.
pub manifests: Vec<String>,
}
impl Pins {
pub fn read(lock: &Value) -> Option<Pins> {
let game = &lock["minecraft"];
let text = |key: &str| game[key].as_str().map(String::from);
let mut manifests = vec![text("manifest_sha1")?];
if let Some(list) = game["accepted_manifest_sha1"].as_array() {
manifests.extend(list.iter().filter_map(Value::as_str).map(String::from));
}
Some(Pins {
version: text("version")?,
client_sha1: text("client_sha1")?,
manifests,
})
}
fn manifest_accepted(&self, path: &Path) -> bool {
sha1_file(path).is_some_and(|sha1| self.manifests.contains(&sha1))
}
}
/// A launcher's copy of the pinned version.
#[derive(Debug, PartialEq)]
pub struct Found {
/// The folder holding the launcher's `libraries` and `assets`.
pub base: PathBuf,
/// The client jar, checked against the pin.
pub client: PathBuf,
/// The launcher's version JSON when it is one Horizon pins.
pub manifest: Option<PathBuf>,
}
impl Found {
/// Whether `base` is in the official launcher's layout, so horizon-prepare reads it as is.
fn official_layout(&self, version: &str) -> bool {
let dir = self.base.join("versions").join(version);
self.client == dir.join(format!("{version}.jar"))
&& self.manifest == Some(dir.join(format!("{version}.json")))
}
}
pub struct Folders {
pub home: PathBuf,
/// `dirs::data_dir()`: ~/.local/share (XDG_DATA_HOME), ~/Library/Application Support,
/// %APPDATA%.
pub data: PathBuf,
/// `dirs::config_dir()`: ~/.config (XDG_CONFIG_HOME), the same as `data` elsewhere.
pub config: PathBuf,
}
impl Folders {
pub fn current() -> Option<Folders> {
Some(Folders {
home: dirs::home_dir()?,
data: dirs::data_dir()?,
config: dirs::config_dir()?,
})
}
}
#[derive(Clone, Copy, PartialEq)]
pub enum Os {
Linux,
MacOs,
Windows,
}
impl Os {
pub fn current() -> Os {
if cfg!(target_os = "macos") {
Os::MacOs
} else if cfg!(windows) {
Os::Windows
} else {
Os::Linux
}
}
}
const OFFICIAL: &str = "the official launcher";
/// Every launcher's default game folder on `os`, the official launcher's first. MultiMC on
/// macOS and Windows has none (it lives where it was unzipped): it is chosen by hand.
pub fn known_folders(os: Os, f: &Folders) -> Vec<(&'static str, PathBuf)> {
let flatpak = |app: &str, rest: &str| f.home.join(".var/app").join(app).join(rest);
let mut list = match os {
Os::Linux => vec![
(OFFICIAL, f.home.join(".minecraft")),
(OFFICIAL, flatpak("com.mojang.Minecraft", ".minecraft")),
("Prism Launcher", f.data.join("PrismLauncher")),
(
"Prism Launcher",
flatpak("org.prismlauncher.PrismLauncher", "data/PrismLauncher"),
),
("MultiMC", f.data.join("multimc")),
("Modrinth App", f.data.join("ModrinthApp")),
(
"Modrinth App",
flatpak("com.modrinth.ModrinthApp", "data/ModrinthApp"),
),
("ATLauncher", f.data.join("atlauncher")),
(
"ATLauncher",
flatpak("com.atlauncher.ATLauncher", "data/atlauncher"),
),
],
Os::MacOs => vec![
(OFFICIAL, f.data.join("minecraft")),
("Prism Launcher", f.data.join("PrismLauncher")),
("MultiMC", f.data.join("MultiMC")),
("Modrinth App", f.data.join("ModrinthApp")),
("ATLauncher", f.data.join("ATLauncher")),
],
Os::Windows => vec![
(OFFICIAL, f.data.join(".minecraft")),
("Prism Launcher", f.data.join("PrismLauncher")),
("Modrinth App", f.data.join("ModrinthApp")),
("ATLauncher", f.data.join("ATLauncher")),
],
};
// Names every system shares: the Modrinth App before its rename, GDLauncher and its
// previous version (GDLauncher Next).
list.extend([
("Modrinth App", f.data.join("com.modrinth.theseus")),
("GDLauncher", f.data.join("gdlauncher_carbon")),
("GDLauncher", f.config.join("gdlauncher_next")),
]);
list
}
/// The client jar's path in a Maven repository: `com.mojang:minecraft:26.3:client` is
/// `com/mojang/minecraft/26.3/minecraft-26.3-client.jar`.
pub fn maven_path(name: &str) -> Option<String> {
let (name, extension) = name.split_once('@').unwrap_or((name, "jar"));
let parts: Vec<&str> = name.split(':').collect();
let (group, artifact, version) = match parts[..] {
[group, artifact, version] | [group, artifact, version, _] => (group, artifact, version),
_ => return None,
};
let classifier = parts.get(3).map(|c| format!("-{c}")).unwrap_or_default();
let unsafe_part = |p: &str| p.is_empty() || p.contains(['/', '\\']) || p.contains("..");
if parts.iter().any(|p| unsafe_part(p)) || unsafe_part(extension) {
return None;
}
Some(format!(
"{}/{artifact}/{version}/{artifact}-{version}{classifier}.{extension}",
group.replace('.', "/")
))
}
/// The client jar Prism Launcher's and MultiMC's metadata name (`meta/net.minecraft/<v>.json`,
/// their own format, `mainJar` a Maven name in `libraries`).
fn meta_client_jar(base: &Path, version: &str) -> Option<String> {
let meta = fs::read_to_string(base.join(format!("meta/net.minecraft/{version}.json"))).ok()?;
let meta: Value = serde_json::from_str(&meta).ok()?;
maven_path(meta["mainJar"]["name"].as_str()?).map(|path| format!("libraries/{path}"))
}
/// Where launchers keep the client jar, relative to the folder holding their `libraries`.
fn client_jars(base: &Path, version: &str) -> Vec<String> {
let v = version;
let mut jars: Vec<String> = meta_client_jar(base, v).into_iter().collect();
for jar in [
// The official launcher; the Modrinth App, in meta/.
format!("versions/{v}/{v}.jar"),
// Prism Launcher and MultiMC.
format!("libraries/com/mojang/minecraft/{v}/minecraft-{v}-client.jar"),
// ATLauncher and GDLauncher.
format!("libraries/net/minecraft/client/{v}/client-{v}.jar"),
] {
if !jars.contains(&jar) {
jars.push(jar);
}
}
jars
}
fn sha1_file(path: &Path) -> Option<String> {
let mut file = fs::File::open(path).ok()?;
let mut hash = Sha1::new();
let mut buffer = vec![0; 1 << 20];
loop {
match file.read(&mut buffer).ok()? {
0 => break,
n => hash.update(&buffer[..n]),
}
}
Some(hash.finalize().iter().map(|b| format!("{b:02x}")).collect())
}
/// The pinned version in one launcher folder, or what the folder lacks. The folder holding
/// `libraries` is the folder itself or its `meta` (Modrinth App), `data` (GDLauncher) or
/// `datastore` (GDLauncher Next).
pub fn find(dir: &Path, pins: &Pins) -> Result<Found, String> {
if !dir.is_dir() {
return Err("the folder doesn't exist".into());
}
let v = &pins.version;
let mut other = None;
let bases = [dir.to_path_buf()]
.into_iter()
.chain(["meta", "data", "datastore"].map(|sub| dir.join(sub)));
for base in bases {
for jar in client_jars(&base, v) {
let client = base.join(&jar);
if !client.is_file() {
continue;
}
if sha1_file(&client).as_ref() != Some(&pins.client_sha1) {
other.get_or_insert(client);
continue;
}
let manifest = base.join(format!("versions/{v}/{v}.json"));
let manifest = pins.manifest_accepted(&manifest).then_some(manifest);
return Ok(Found {
base,
client,
manifest,
});
}
}
Err(match other {
Some(jar) => format!(
"{} is not the {v} release Horizon was made for",
jar.strip_prefix(dir).unwrap_or(&jar).display()
),
None => format!("no Minecraft {v} client jar"),
})
}
/// The error when no folder has the pinned version: every folder looked in with what it
/// lacks, and what the player can do about it (#419).
pub fn not_found(version: &str, checked: &[(PathBuf, String)]) -> String {
let mut text = format!("Minecraft {version} was not found. Horizon looked in:");
for (dir, missing) in checked {
text += &format!("\n {} ({missing})", dir.display());
}
text += &format!(
"\nTo fix it:\n \
• Play {version} once in the official Minecraft launcher, or in Prism Launcher, MultiMC, \
the Modrinth App, ATLauncher or GDLauncher, then prepare again.\n \
• Or choose the folder where your launcher keeps Minecraft {version} (Minecraft folder › \
Choose… in the launcher, --minecraft on the command line)."
);
text
}
/// Fetches a URL's body.
pub type Fetch<'a> = &'a dyn Fn(&str) -> Result<Vec<u8>, String>;
/// A Minecraft folder in the official launcher's layout holding the pinned version: the
/// chosen folder when it is one, else the files found in the chosen folder (or a folder above
/// it: a launcher's instance folder may be chosen) or any launcher's default folder, linked into
/// `linked`.
pub fn resolve(
chosen: &Path,
pins: &Pins,
known: &[(&'static str, PathBuf)],
linked: &Path,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<PathBuf, String> {
let mut checked = Vec::new();
let mut found = None;
for dir in chosen.ancestors().take(4) {
match find(dir, pins) {
Ok(f) => {
found = Some(("the chosen folder", f));
break;
}
Err(missing) if dir == chosen => checked.push((dir.to_path_buf(), missing)),
Err(_) => {}
}
}
let same = |a: &Path, b: &Path| a == b || fs::canonicalize(a).ok() == fs::canonicalize(b).ok();
for (name, dir) in known.iter().filter(|(_, d)| d.is_dir() && !same(d, chosen)) {
if found.is_some() {
break;
}
match find(dir, pins) {
Ok(f) => found = Some((name, f)),
Err(missing) => checked.push((dir.clone(), format!("{name}: {missing}"))),
}
}
let Some((name, found)) = found else {
return Err(not_found(&pins.version, &checked));
};
log(format!(
"Using Minecraft {} from {name} ({})",
pins.version,
found.base.display()
));
if found.official_layout(&pins.version) {
return Ok(found.base);
}
link_official_layout(&found, pins, linked, fetch, log)?;
Ok(linked.to_path_buf())
}
/// Links a launcher's files into the official layout in `linked`: the client jar as
/// `versions/<v>/<v>.jar`, its `libraries` and `assets`, and the pinned version JSON, the
/// launcher's own when it keeps it, else Mojang's.
fn link_official_layout(
found: &Found,
pins: &Pins,
linked: &Path,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
let v = &pins.version;
let versions = linked.join("versions").join(v);
fs::create_dir_all(&versions).map_err(|e| format!("{}: {e}", versions.display()))?;
let manifest = versions.join(format!("{v}.json"));
if let Some(source) = &found.manifest {
fs::copy(source, &manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
} else if !pins.manifest_accepted(&manifest) {
let sha1 = &pins.manifests[0];
log(format!("Downloading the {v} version file from Mojang"));
let body = fetch(&format!(
"https://piston-meta.mojang.com/v1/packages/{sha1}/{v}.json"
))?;
let actual: String = Sha1::digest(&body)
.iter()
.map(|b| format!("{b:02x}"))
.collect();
if &actual != sha1 {
return Err(format!(
"Mojang's {v} version file is not the one Horizon pins (sha1 {actual})"
));
}
fs::write(&manifest, body).map_err(|e| format!("{}: {e}", manifest.display()))?;
}
link(&found.client, &versions.join(format!("{v}.jar")))?;
for dir in ["libraries", "assets"] {
let source = found.base.join(dir);
let target = linked.join(dir);
if source.is_dir() {
link(&source, &target)?;
} else {
unlink(&target)?;
}
}
Ok(())
}
/// Removes a link left by an earlier preparation; never a real folder's contents.
fn unlink(path: &Path) -> Result<(), String> {
if fs::symlink_metadata(path).is_err() {
return Ok(());
}
// A Windows junction, or a directory symlink, is removed as a directory.
fs::remove_file(path)
.or_else(|_| fs::remove_dir(path))
.map_err(|e| format!("{}: {e}", path.display()))
}
/// `link` pointing at `target`, replacing an earlier one.
fn link(target: &Path, link: &Path) -> Result<(), String> {
unlink(link)?;
make_link(target, link).map_err(|e| format!("{} → {}: {e}", link.display(), target.display()))
}
#[cfg(unix)]
fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(target, link)
}
/// Symlinks need developer mode on Windows: a junction for a folder, a hard link for a file.
#[cfg(windows)]
fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
if !target.is_dir() {
return fs::hard_link(target, link).or_else(|_| fs::copy(target, link).map(|_| ()));
}
let status = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(link)
.arg(target)
.stdout(std::process::Stdio::null())
.status()?;
match status.success() {
true => Ok(()),
false => Err(std::io::Error::other("mklink /J failed")),
}
}
#[cfg(test)]
#[path = "sources_tests.rs"]
mod tests;
+409
View File
@@ -0,0 +1,409 @@
//! Each launcher's layout, rebuilt with small fake files (never Mojang's).
use super::*;
use std::cell::RefCell;
const CLIENT: &[u8] = b"fake 26.3 client jar";
const MANIFEST: &[u8] = br#"{"id": "26.3", "fake": true}"#;
fn sha1_hex(data: &[u8]) -> String {
Sha1::digest(data)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn pins() -> Pins {
Pins::read(&serde_json::json!({ "minecraft": {
"version": "26.3",
"client_sha1": sha1_hex(CLIENT),
"manifest_sha1": sha1_hex(MANIFEST),
"accepted_manifest_sha1": [sha1_hex(b"an earlier one")],
}}))
.unwrap()
}
/// A scratch folder, removed at the end.
struct Scratch(PathBuf);
impl Scratch {
fn new(name: &str) -> Scratch {
let dir =
std::env::temp_dir().join(format!("horizon-sources-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Scratch(dir)
}
fn write(&self, path: &str, data: &[u8]) -> PathBuf {
let path = self.0.join(path);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, data).unwrap();
path
}
/// A launcher folder: the client jar at `jar`, a library and a sound under `base`.
fn launcher(&self, root: &str, base: &str, jar: &str) -> PathBuf {
let base = if base.is_empty() {
root.to_string()
} else {
format!("{root}/{base}")
};
self.write(&format!("{base}/{jar}"), CLIENT);
self.write(&format!("{base}/libraries/org/lib/1/lib-1.jar"), b"lib");
self.write(&format!("{base}/assets/indexes/30.json"), b"{}");
self.0.join(root)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Mojang's piston-meta, serving `body` and counting the requests.
struct Mojang {
body: Vec<u8>,
urls: RefCell<Vec<String>>,
}
impl Mojang {
fn new(body: &[u8]) -> Mojang {
Mojang {
body: body.to_vec(),
urls: RefCell::new(Vec::new()),
}
}
fn fetch(&self, url: &str) -> Result<Vec<u8>, String> {
self.urls.borrow_mut().push(url.to_string());
Ok(self.body.clone())
}
}
fn resolve_with(
chosen: &Path,
known: &[(&'static str, PathBuf)],
linked: &Path,
mojang: &Mojang,
) -> Result<PathBuf, String> {
resolve(
chosen,
&pins(),
known,
linked,
&|url| mojang.fetch(url),
&|_| {},
)
}
/// The linked folder is the official layout, pointing at the launcher's files.
fn assert_linked(linked: &Path, base: &Path, jar: &str) {
let v = linked.join("versions/26.3");
assert_eq!(fs::read(v.join("26.3.jar")).unwrap(), CLIENT);
assert_eq!(fs::read(v.join("26.3.json")).unwrap(), MANIFEST);
assert_eq!(
fs::canonicalize(v.join("26.3.jar")).unwrap(),
fs::canonicalize(base.join(jar)).unwrap()
);
assert_eq!(
fs::read(linked.join("libraries/org/lib/1/lib-1.jar")).unwrap(),
b"lib"
);
assert!(linked.join("assets/indexes/30.json").is_file());
}
#[test]
fn maven_names_become_repository_paths() {
assert_eq!(
maven_path("com.mojang:minecraft:26.3:client").as_deref(),
Some("com/mojang/minecraft/26.3/minecraft-26.3-client.jar")
);
assert_eq!(
maven_path("org.lwjgl:lwjgl:3.3.3").as_deref(),
Some("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar")
);
assert_eq!(
maven_path("net.example:thing:1.0@zip").as_deref(),
Some("net/example/thing/1.0/thing-1.0.zip")
);
for bad in ["minecraft", "a:b", "a:b:c:d:e", "a:..:1", "a:b/c:1", "a::1"] {
assert_eq!(maven_path(bad), None, "{bad}");
}
}
#[test]
fn the_official_layout_is_used_as_it_is() {
let s = Scratch::new("official");
let dir = s.launcher(".minecraft", "", "versions/26.3/26.3.jar");
s.write(".minecraft/versions/26.3/26.3.json", MANIFEST);
let mojang = Mojang::new(b"");
let got = resolve_with(&dir, &[], &s.0.join("linked"), &mojang).unwrap();
assert_eq!(got, dir);
assert!(mojang.urls.borrow().is_empty());
assert!(!s.0.join("linked").exists());
}
#[test]
fn an_official_folder_with_an_unknown_version_file_gets_the_pinned_one() {
let s = Scratch::new("republished");
let dir = s.launcher(".minecraft", "", "versions/26.3/26.3.jar");
s.write(".minecraft/versions/26.3/26.3.json", b"{\"id\": \"26.3\"}");
let linked = s.0.join("linked");
let mojang = Mojang::new(MANIFEST);
assert_eq!(resolve_with(&dir, &[], &linked, &mojang).unwrap(), linked);
assert_linked(&linked, &dir, "versions/26.3/26.3.jar");
}
#[test]
fn prism_launcher_and_multimc_are_read_through_their_metadata() {
let s = Scratch::new("prism");
let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let dir = s.launcher("PrismLauncher", "", jar);
// Prism's own version format: no `downloads.server`, the client a Maven name.
s.write(
"PrismLauncher/meta/net.minecraft/26.3.json",
br#"{"formatVersion": 1, "uid": "net.minecraft", "version": "26.3",
"mainJar": {"name": "com.mojang:minecraft:26.3:client",
"downloads": {"artifact": {"sha1": "x", "size": 20}}}}"#,
);
let linked = s.0.join("linked");
let mojang = Mojang::new(MANIFEST);
assert_eq!(resolve_with(&dir, &[], &linked, &mojang).unwrap(), linked);
assert_linked(&linked, &dir, jar);
assert_eq!(
*mojang.urls.borrow(),
[format!(
"https://piston-meta.mojang.com/v1/packages/{}/26.3.json",
sha1_hex(MANIFEST)
)]
);
// A second preparation keeps the version file it has.
resolve_with(&dir, &[], &linked, &mojang).unwrap();
assert_eq!(mojang.urls.borrow().len(), 1);
}
#[test]
fn a_main_jar_elsewhere_is_found_from_the_metadata() {
let s = Scratch::new("meta-jar");
let dir = s.launcher(
"multimc",
"",
"libraries/com/mojang/minecraft/26.3/minecraft-26.3-x.jar",
);
s.write(
"multimc/meta/net.minecraft/26.3.json",
br#"{"mainJar": {"name": "com.mojang:minecraft:26.3:x"}}"#,
);
let found = find(&dir, &pins()).unwrap();
assert_eq!(
found.client,
dir.join("libraries/com/mojang/minecraft/26.3/minecraft-26.3-x.jar")
);
}
#[test]
fn the_modrinth_app_atlauncher_and_gdlauncher_are_found() {
for (root, base, jar) in [
("ModrinthApp", "meta", "versions/26.3/26.3.jar"),
(
"atlauncher",
"",
"libraries/net/minecraft/client/26.3/client-26.3.jar",
),
(
"gdlauncher_carbon",
"data",
"libraries/net/minecraft/client/26.3/client-26.3.jar",
),
(
"gdlauncher_next",
"datastore",
"libraries/net/minecraft/client/26.3/client-26.3.jar",
),
] {
let s = Scratch::new(root);
let dir = s.launcher(root, base, jar);
// The Modrinth App rewrites the version file: not the pinned one, so Mojang's is used.
s.write(
&format!("{root}/meta/versions/26.3/26.3.json"),
b"{\"id\":\"26.3\"}",
);
let linked = s.0.join("linked");
let mojang = Mojang::new(MANIFEST);
assert_eq!(
resolve_with(&dir, &[], &linked, &mojang).unwrap(),
linked,
"{root}"
);
assert_linked(&linked, &dir.join(base), jar);
}
}
#[test]
fn an_instance_folder_may_be_chosen() {
let s = Scratch::new("instance");
let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let dir = s.launcher("PrismLauncher", "", jar);
let instance = dir.join("instances/26.3/minecraft");
fs::create_dir_all(&instance).unwrap();
let linked = s.0.join("linked");
let got = resolve_with(&instance, &[], &linked, &Mojang::new(MANIFEST)).unwrap();
assert_eq!(got, linked);
assert_linked(&linked, &dir, jar);
}
#[test]
fn the_known_folders_are_searched_after_the_chosen_one() {
let s = Scratch::new("known");
let empty = s.0.join(".minecraft");
fs::create_dir_all(empty.join("versions")).unwrap();
let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let prism = s.launcher("PrismLauncher", "", jar);
let known = [
(OFFICIAL, empty.clone()),
("Modrinth App", s.0.join("ModrinthApp")),
("Prism Launcher", prism.clone()),
];
let linked = s.0.join("linked");
let logged = RefCell::new(Vec::new());
let mojang = Mojang::new(MANIFEST);
let got = resolve(
&empty,
&pins(),
&known,
&linked,
&|url| mojang.fetch(url),
&|line| logged.borrow_mut().push(line),
);
assert_eq!(got.unwrap(), linked);
assert_linked(&linked, &prism, jar);
assert_eq!(
logged.borrow()[0],
format!(
"Using Minecraft 26.3 from Prism Launcher ({})",
prism.display()
)
);
}
#[test]
fn relinking_follows_the_launcher_the_files_now_come_from() {
let s = Scratch::new("relink");
let prism_jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let prism = s.launcher("PrismLauncher", "", prism_jar);
let linked = s.0.join("linked");
let mojang = Mojang::new(MANIFEST);
resolve_with(&prism, &[], &linked, &mojang).unwrap();
let modrinth = s.0.join("ModrinthApp");
s.write("ModrinthApp/meta/versions/26.3/26.3.jar", CLIENT);
resolve_with(&modrinth, &[], &linked, &mojang).unwrap();
assert_eq!(
fs::canonicalize(linked.join("versions/26.3/26.3.jar")).unwrap(),
fs::canonicalize(modrinth.join("meta/versions/26.3/26.3.jar")).unwrap()
);
// The Modrinth App folder has no libraries or assets: the old links are gone, and the
// folders they pointed at are untouched.
assert!(fs::symlink_metadata(linked.join("libraries")).is_err());
assert!(prism.join("libraries/org/lib/1/lib-1.jar").is_file());
}
#[test]
fn nothing_found_lists_every_folder_and_what_it_lacks() {
let s = Scratch::new("nothing");
let chosen = s.0.join("chosen");
let wrong = s.0.join("PrismLauncher");
s.write(
"PrismLauncher/libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar",
b"another release",
);
let empty = s.0.join("ModrinthApp");
fs::create_dir_all(&empty).unwrap();
let known = [
("Prism Launcher", wrong.clone()),
("Modrinth App", empty.clone()),
("ATLauncher", s.0.join("atlauncher")),
];
let mojang = Mojang::new(MANIFEST);
let error = resolve_with(&chosen, &known, &s.0.join("linked"), &mojang).unwrap_err();
let expected = format!(
"Minecraft 26.3 was not found. Horizon looked in:\n \
{} (the folder doesn't exist)\n \
{} (Prism Launcher: libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar is \
not the 26.3 release Horizon was made for)\n \
{} (Modrinth App: no Minecraft 26.3 client jar)\nTo fix it:\n",
chosen.display(),
wrong.display(),
empty.display()
);
assert!(error.starts_with(&expected), "{error}");
assert!(error.contains("Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher"));
// A launcher that isn't installed isn't listed.
assert!(!error.contains("atlauncher"));
assert!(mojang.urls.borrow().is_empty());
}
#[test]
fn a_version_file_that_is_not_the_pinned_one_is_refused() {
let s = Scratch::new("bad-download");
let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
let dir = s.launcher("PrismLauncher", "", jar);
let linked = s.0.join("linked");
let error = resolve_with(&dir, &[], &linked, &Mojang::new(b"{}")).unwrap_err();
assert!(error.contains("not the one Horizon pins"), "{error}");
assert!(!linked.join("versions/26.3/26.3.json").exists());
}
#[test]
fn each_system_has_its_launcher_folders() {
let linux = Folders {
home: "/home/r".into(),
data: "/home/r/.local/share".into(),
config: "/home/r/.config".into(),
};
let folders = |os, f: &Folders| -> Vec<String> {
known_folders(os, f)
.into_iter()
.map(|(name, dir)| format!("{name}: {}", dir.display()).replace('\\', "/"))
.collect()
};
let got = folders(Os::Linux, &linux);
for expected in [
"the official launcher: /home/r/.minecraft",
"Prism Launcher: /home/r/.local/share/PrismLauncher",
"Prism Launcher: /home/r/.var/app/org.prismlauncher.PrismLauncher/data/PrismLauncher",
"MultiMC: /home/r/.local/share/multimc",
"Modrinth App: /home/r/.local/share/ModrinthApp",
"Modrinth App: /home/r/.var/app/com.modrinth.ModrinthApp/data/ModrinthApp",
"ATLauncher: /home/r/.local/share/atlauncher",
"GDLauncher: /home/r/.local/share/gdlauncher_carbon",
"GDLauncher: /home/r/.config/gdlauncher_next",
] {
assert!(got.iter().any(|g| g == expected), "{expected} in {got:#?}");
}
assert!(got[0].starts_with("the official launcher"));
let mac = Folders {
home: "/Users/r".into(),
data: "/Users/r/Library/Application Support".into(),
config: "/Users/r/Library/Application Support".into(),
};
let got = folders(Os::MacOs, &mac);
assert_eq!(
got[0],
"the official launcher: /Users/r/Library/Application Support/minecraft"
);
assert!(
got.contains(&"Prism Launcher: /Users/r/Library/Application Support/PrismLauncher".into())
);
let windows = Folders {
home: "C:/Users/r".into(),
data: "C:/Users/r/AppData/Roaming".into(),
config: "C:/Users/r/AppData/Roaming".into(),
};
let got = folders(Os::Windows, &windows);
assert_eq!(
got[0],
"the official launcher: C:/Users/r/AppData/Roaming/.minecraft"
);
assert!(got.contains(&"ATLauncher: C:/Users/r/AppData/Roaming/ATLauncher".into()));
}