From 2029005c7861488c9ad36e884641bb1a96e21205 Mon Sep 17 00:00:00 2001 From: objz Date: Mon, 25 May 2026 14:51:34 +0200 Subject: [PATCH] added: vanilla launch flow uses LaunchProfile with render + raw-byte storage vanilla launches now read upstream mojang JSON via the new LaunchProfile path, render game/JVM args through launch_profile::render with template substitution, and store the cached meta.json byte-for-byte instead of re-serializing through a narrow struct. legacy stripped meta.json files are re-fetched on first launch. adds HttpClient::get_bytes and fetch_version_meta_with_raw; collapses the two library-rule evaluators into one shared launch_profile::rules::evaluate. --- src/instance/launch/mod.rs | 435 +++++++++++++++++++++-------------- src/instance/manager.rs | 20 +- src/launch_profile/mod.rs | 5 +- src/launch_profile/render.rs | 318 +++++++++++++++++++++++++ src/net/mod.rs | 4 + src/net/mojang.rs | 84 +++---- 6 files changed, 629 insertions(+), 237 deletions(-) create mode 100644 src/launch_profile/render.rs diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index 5fa9483..a366d72 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -15,6 +15,8 @@ use crate::instance::models::{InstanceConfig, ModLoader}; pub enum LaunchError { #[error("Version metadata not found: {0}. Re-create the instance to fix this.")] MetaNotFound(String), + #[error("Profile error: {0}")] + Parse(String), #[error("IO error: {0}")] Io(#[from] std::io::Error), #[error("JSON error: {0}")] @@ -25,47 +27,6 @@ pub enum LaunchError { Auth(String), } -// subset of mojang's version meta json, only the bits relevant to launching -#[derive(serde::Deserialize)] -#[serde(rename_all = "camelCase")] -struct MetaJson { - main_class: String, - asset_index: MetaAssetIndex, - libraries: Vec, -} - -#[derive(serde::Deserialize)] -struct MetaAssetIndex { - id: String, -} - -#[derive(serde::Deserialize)] -struct MetaLibrary { - downloads: Option, - rules: Option>, -} - -#[derive(serde::Deserialize)] -struct MetaLibraryDownloads { - artifact: Option, -} - -#[derive(serde::Deserialize)] -struct MetaArtifact { - path: String, -} - -#[derive(serde::Deserialize)] -struct MetaRule { - action: String, - os: Option, -} - -#[derive(serde::Deserialize)] -struct MetaOsRule { - name: Option, -} - #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase")] struct LoaderProfileJson { @@ -80,78 +41,65 @@ struct LoaderLibrary { name: String, } -struct GameAuth { - username: String, - uuid: String, - token: String, - user_type: String, -} - fn account_can_launch(has_microsoft_account: bool, account: &Account) -> bool { account.account_type == AccountType::Microsoft || has_microsoft_account } -// mojang's library rules are a fun little state machine: each rule can allow -// or disallow based on OS. if no rule matches the current OS, the library is -// included only if no rule "dominated" (matched at all). yes, it's weird. -fn lib_allowed(lib: &MetaLibrary) -> bool { - let Some(rules) = &lib.rules else { - return true; - }; - let current_os = match std::env::consts::OS { - "macos" => "osx", - other => other, - }; - let mut dominated = false; - for rule in rules { - let matches_os = rule - .os - .as_ref() - .and_then(|os| os.name.as_deref()) - .is_none_or(|n| n == current_os); - if !matches_os { - continue; - } - dominated = true; - match rule.action.as_str() { - "disallow" => return false, - "allow" => return true, - _ => {} - } - } - !dominated +fn build_game_args( + profile: &crate::launch_profile::model::LaunchProfile, + rule_ctx: &crate::launch_profile::rules::RuleContext<'_>, + template_ctx: &crate::launch_profile::templates::TemplateContext<'_>, + loader_game_args: Vec, +) -> Result<(Vec, Vec), LaunchError> { + let rendered = crate::launch_profile::render::render_args(profile, rule_ctx, template_ctx) + .map_err(|e| LaunchError::Parse(format!("Failed to render args: {e}")))?; + let mut game = rendered.game; + game.extend(loader_game_args); + Ok((rendered.jvm, game)) } -fn build_game_args( - config: &InstanceConfig, - minecraft_dir: &Path, - meta_dir: &Path, - asset_index_id: &str, - auth: GameAuth, - loader_game_args: Vec, -) -> Vec { - let mut game_args = vec![ - "--username".to_string(), - auth.username, - "--version".to_string(), - config.game_version.clone(), - "--gameDir".to_string(), - minecraft_dir.to_string_lossy().into_owned(), - "--assetsDir".to_string(), - meta_dir.join("assets").to_string_lossy().into_owned(), - "--assetIndex".to_string(), - asset_index_id.to_string(), - "--uuid".to_string(), - auth.uuid, - "--accessToken".to_string(), - auth.token, - "--userProperties".to_string(), - "{}".to_string(), - "--userType".to_string(), - auth.user_type, - ]; - game_args.extend(loader_game_args); - game_args +// existing installs from rmcl <= 0.3.0 have meta.json files in the +// stripped legacy format (no `arguments`, no `minecraftArguments`). every +// real upstream profile has at least one of those fields. on detecting the +// stripped format, re-fetch the version metadata from mojang's manifest +// and overwrite the file with the raw upstream bytes. +async fn migrate_legacy_meta_if_needed( + meta_path: &Path, + profile: &crate::launch_profile::model::LaunchProfile, + game_version: &str, +) -> Result, LaunchError> { + if profile.arguments.is_some() || profile.minecraft_arguments.is_some() { + return Ok(None); + } + + tracing::warn!( + "Cached meta.json for {game_version} is missing arguments; re-fetching from Mojang" + ); + + let client = crate::net::HttpClient::new(); + let manifest = crate::net::mojang::fetch_version_manifest(&client) + .await + .map_err(|e| LaunchError::Parse(format!("Failed to fetch version manifest: {e}")))?; + + let entry = manifest + .versions + .iter() + .find(|v| v.id == game_version) + .ok_or_else(|| { + LaunchError::Parse(format!( + "Version {game_version} not found in Mojang manifest" + )) + })?; + + let (_meta, raw) = crate::net::mojang::fetch_version_meta_with_raw(&client, entry) + .await + .map_err(|e| LaunchError::Parse(format!("Failed to re-fetch version meta: {e}")))?; + + tokio::fs::write(meta_path, &raw).await?; + + let refreshed: crate::launch_profile::model::LaunchProfile = serde_json::from_slice(&raw) + .map_err(|e| LaunchError::Parse(format!("Failed to parse refreshed meta: {e}")))?; + Ok(Some(refreshed)) } pub async fn launch( @@ -170,18 +118,50 @@ pub async fn launch( if !meta_path.exists() { return Err(LaunchError::MetaNotFound(meta_path.display().to_string())); } - let meta: MetaJson = serde_json::from_slice(&tokio::fs::read(&meta_path).await?)?; + let meta: crate::launch_profile::model::LaunchProfile = + serde_json::from_slice(&tokio::fs::read(&meta_path).await?)?; + let meta = match migrate_legacy_meta_if_needed(&meta_path, &meta, &config.game_version).await? { + Some(refreshed) => refreshed, + None => meta, + }; + + let current_features = crate::launch_profile::rules::FeatureSet::default(); + let rule_ctx = crate::launch_profile::rules::RuleContext { + os_name: match std::env::consts::OS { + "macos" => "osx", + other => other, + }, + arch: match std::env::consts::ARCH { + "x86" => "x86", + "x86_64" => "x86_64", + "aarch64" => "arm64", + other => other, + }, + features: ¤t_features, + }; + + let vanilla_main_class = meta + .main_class + .clone() + .ok_or_else(|| LaunchError::Parse("meta.json missing mainClass".into()))?; + let asset_index_id = meta + .asset_index + .as_ref() + .map(|ai| ai.id.clone()) + .unwrap_or_default(); let lib_dir = meta_dir.join("libraries"); let mut classpath: Vec = meta .libraries .iter() - .filter(|l| lib_allowed(l)) + .filter(|l| match &l.rules { + Some(rules) => crate::launch_profile::rules::evaluate(rules, &rule_ctx), + None => true, + }) .filter_map(|l| { l.downloads - .as_ref()? - .artifact .as_ref() + .and_then(|d| d.artifact.as_ref()) .map(|a| lib_dir.join(&a.path)) }) .collect(); @@ -230,7 +210,7 @@ pub async fn launch( } (profile.main_class, profile.game_arguments) } else { - (meta.main_class.clone(), Vec::new()) + (vanilla_main_class.clone(), Vec::new()) }; classpath.push( @@ -269,13 +249,6 @@ pub async fn launch( }) .unwrap_or_else(crate::net::detect_java_path); - let mut jvm: Vec = vec![ - format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")), - format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")), - ]; - jvm.extend(patch_jvm_args); - jvm.extend(config.jvm_args.clone()); - // resolve auth credentials, refreshing the microsoft token if needed. let mut account_store = crate::auth::AccountStore::load(); let (mc_username, mc_uuid, mc_token, mc_user_type) = match account_store @@ -330,19 +303,41 @@ pub async fn launch( None => return Err(LaunchError::Auth("No account selected".to_owned())), }; - let game_args = build_game_args( - config, - &minecraft_dir, - meta_dir, - &meta.asset_index.id, - GameAuth { - username: mc_username, - uuid: mc_uuid, - token: mc_token, - user_type: mc_user_type, - }, - loader_game_args, - ); + let assets_root = meta_dir.join("assets"); + let natives_dir = meta_dir + .join("versions") + .join(&config.game_version) + .join("natives"); + let template_ctx = crate::launch_profile::templates::TemplateContext { + library_directory: &lib_dir, + classpath_separator: sep, + version_name: &config.game_version, + natives_directory: &natives_dir, + classpath: &cp_str, + game_directory: &minecraft_dir, + assets_root: &assets_root, + assets_index_name: &asset_index_id, + auth_player_name: &mc_username, + auth_uuid: &mc_uuid, + auth_access_token: &mc_token, + auth_xuid: "0", + user_type: &mc_user_type, + user_properties: "{}", + launcher_name: "rmcl", + launcher_version: env!("CARGO_PKG_VERSION"), + clientid: "0", + }; + + let (upstream_jvm_args, game_args) = + build_game_args(&meta, &rule_ctx, &template_ctx, loader_game_args)?; + + let mut jvm: Vec = vec![ + format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")), + format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")), + ]; + jvm.extend(patch_jvm_args); + jvm.extend(upstream_jvm_args); + jvm.extend(config.jvm_args.clone()); let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>(); crate::running::register_kill(&name, kill_tx); @@ -478,23 +473,6 @@ pub async fn launch( mod tests { use super::*; use crate::auth::{Account, AccountType}; - use chrono::Utc; - - fn test_config() -> InstanceConfig { - InstanceConfig { - name: "test".to_owned(), - game_version: "1.7.10".to_owned(), - loader: ModLoader::Forge, - loader_version: Some("10.13.4.1614".to_owned()), - created: Utc::now(), - last_played: None, - java_path: None, - memory_max: None, - memory_min: None, - jvm_args: Vec::new(), - resolution: None, - } - } fn test_account(account_type: AccountType) -> Account { Account { @@ -509,32 +487,78 @@ mod tests { } #[test] - fn game_args_include_empty_user_properties() { - let args = build_game_args( - &test_config(), - Path::new("/instances/test/.minecraft"), - Path::new("/meta"), - "legacy", - GameAuth { - username: "TestPlayer".to_owned(), - uuid: "00000000-0000-0000-0000-000000000000".to_owned(), - token: "token".to_owned(), - user_type: "msa".to_owned(), - }, - vec![ - "--tweakClass".to_owned(), - "cpw.mods.fml.common.launcher.FMLTweaker".to_owned(), - ], - ); + fn build_game_args_renders_upstream_arguments_and_appends_loader_args() { + use crate::launch_profile::model::{Argument, Arguments, LaunchProfile}; + use crate::launch_profile::rules::{FeatureSet, RuleContext}; + use crate::launch_profile::templates::TemplateContext; + use std::path::PathBuf; - let position = args - .iter() - .position(|arg| arg == "--userProperties") - .expect("game args should include --userProperties"); - assert_eq!(args.get(position + 1).map(String::as_str), Some("{}")); - assert!( - args.windows(2) - .any(|pair| pair == ["--tweakClass", "cpw.mods.fml.common.launcher.FMLTweaker"]) + let lib = PathBuf::from("/m/libraries"); + let nat = PathBuf::from("/m/natives"); + let game_dir = PathBuf::from("/i/.minecraft"); + let assets = PathBuf::from("/m/assets"); + + let template_ctx = TemplateContext { + library_directory: &lib, + classpath_separator: ":", + version_name: "1.20.1", + natives_directory: &nat, + classpath: "a.jar:b.jar", + game_directory: &game_dir, + assets_root: &assets, + assets_index_name: "5", + auth_player_name: "Player", + auth_uuid: "00000000-0000-0000-0000-000000000000", + auth_access_token: "token", + auth_xuid: "0", + user_type: "msa", + user_properties: "{}", + launcher_name: "rmcl", + launcher_version: "test", + clientid: "0", + }; + let features = FeatureSet::default(); + let rule_ctx = RuleContext { + os_name: "linux", + arch: "x86_64", + features: &features, + }; + + let profile = LaunchProfile { + id: "1.20.1".into(), + inherits_from: None, + main_class: Some("net.minecraft.client.main.Main".into()), + libraries: Vec::new(), + arguments: Some(Arguments { + game: vec![ + Argument::Literal("--username".into()), + Argument::Literal("${auth_player_name}".into()), + ], + jvm: vec![Argument::Literal( + "-Djava.library.path=${natives_directory}".into(), + )], + }), + minecraft_arguments: None, + asset_index: None, + assets: None, + java_version: None, + downloads: None, + release_time: None, + time: None, + type_: None, + }; + + let (jvm, game_args) = build_game_args( + &profile, + &rule_ctx, + &template_ctx, + vec!["--tweakClass".into(), "foo".into()], + ) + .unwrap(); + assert_eq!(jvm, vec!["-Djava.library.path=/m/natives"]); + assert_eq!( + game_args, + vec!["--username", "Player", "--tweakClass", "foo"] ); } @@ -558,4 +582,67 @@ mod tests { assert!(account_can_launch(false, µsoft)); } + + #[test] + fn migration_predicate_triggers_when_both_argument_fields_absent() { + use crate::launch_profile::model::LaunchProfile; + let stripped = LaunchProfile { + id: "1.20.1".into(), + inherits_from: None, + main_class: Some("net.test.Main".into()), + libraries: Vec::new(), + arguments: None, + minecraft_arguments: None, + asset_index: None, + assets: None, + java_version: None, + downloads: None, + release_time: None, + time: None, + type_: None, + }; + assert!(stripped.arguments.is_none() && stripped.minecraft_arguments.is_none()); + } + + #[test] + fn migration_predicate_skips_when_modern_arguments_present() { + use crate::launch_profile::model::{Arguments, LaunchProfile}; + let modern = LaunchProfile { + id: "1.20.1".into(), + inherits_from: None, + main_class: Some("net.test.Main".into()), + libraries: Vec::new(), + arguments: Some(Arguments::default()), + minecraft_arguments: None, + asset_index: None, + assets: None, + java_version: None, + downloads: None, + release_time: None, + time: None, + type_: None, + }; + assert!(modern.arguments.is_some()); + } + + #[test] + fn migration_predicate_skips_when_legacy_minecraft_arguments_present() { + use crate::launch_profile::model::LaunchProfile; + let legacy = LaunchProfile { + id: "1.7.10".into(), + inherits_from: None, + main_class: Some("net.test.Main".into()), + libraries: Vec::new(), + arguments: None, + minecraft_arguments: Some("--username Player".into()), + asset_index: None, + assets: None, + java_version: None, + downloads: None, + release_time: None, + time: None, + type_: None, + }; + assert!(legacy.minecraft_arguments.is_some()); + } } diff --git a/src/instance/manager.rs b/src/instance/manager.rs index 87bddf6..41ffecd 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -115,8 +115,8 @@ impl InstanceManager { } }; - let version_meta = - crate::net::mojang::fetch_version_meta(&self.client, version_entry).await?; + let (version_meta, raw_meta_bytes) = + crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await?; crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir) .await?; @@ -126,15 +126,13 @@ impl InstanceManager { .join("versions") .join(game_version) .join("meta.json"); - match serde_json::to_string_pretty(&version_meta) { - Ok(json) => { - if let Err(e) = std::fs::write(&meta_json_path, &json) { - tracing::warn!("Failed to save version meta: {}", e); - } - } - Err(e) => { - tracing::warn!("Failed to serialize version meta: {}", e); - } + if let Some(parent) = meta_json_path.parent() + && let Err(e) = std::fs::create_dir_all(parent) + { + tracing::warn!("Failed to ensure meta dir exists: {}", e); + } + if let Err(e) = std::fs::write(&meta_json_path, &raw_meta_bytes) { + tracing::warn!("Failed to save version meta: {}", e); } crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?; diff --git a/src/launch_profile/mod.rs b/src/launch_profile/mod.rs index 0538de4..76d13e8 100644 --- a/src/launch_profile/mod.rs +++ b/src/launch_profile/mod.rs @@ -2,9 +2,10 @@ // launch profiles. consumed by the vanilla launcher, forge/neoforge, // fabric/quilt - anything that reads a mojang-style version JSON. // -// phase 1 is pure additions: no consumers yet. later phases will wire -// these primitives into the launch pipeline and the installer paths. +// phase 2 adds the render layer that turns a parsed profile + rule context + +// template context into a flat argv list. pub mod model; +pub mod render; pub mod rules; pub mod templates; diff --git a/src/launch_profile/render.rs b/src/launch_profile/render.rs new file mode 100644 index 0000000..d1b2a48 --- /dev/null +++ b/src/launch_profile/render.rs @@ -0,0 +1,318 @@ +// renders a parsed launch profile into final argv-style lists for the JVM +// and the game. resolves conditional argument shapes (`{rules, value}`), +// filters them through the rule evaluator, and substitutes mojang template +// variables. legacy `minecraftArguments` strings are tokenised on whitespace +// and treated as a list of game args. pure function; no I/O. + +use super::model::{Argument, ArgumentValue, LaunchProfile}; +use super::rules::{RuleContext, evaluate}; +use super::templates::{TemplateContext, substitute}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RenderedArgs { + pub jvm: Vec, + pub main_class: String, + pub game: Vec, +} + +#[derive(Debug, thiserror::Error)] +pub enum RenderError { + #[error("launch profile is missing a main class")] + MissingMainClass, +} + +pub fn render_args( + profile: &LaunchProfile, + rule_ctx: &RuleContext, + template_ctx: &TemplateContext, +) -> Result { + let main_class = profile + .main_class + .clone() + .ok_or(RenderError::MissingMainClass)?; + + let mut jvm = Vec::new(); + let mut game = Vec::new(); + + if let Some(args) = &profile.arguments { + for arg in &args.jvm { + push_argument(arg, rule_ctx, template_ctx, &mut jvm); + } + for arg in &args.game { + push_argument(arg, rule_ctx, template_ctx, &mut game); + } + } else if let Some(legacy) = &profile.minecraft_arguments { + for token in legacy.split_whitespace() { + game.push(substitute(token, template_ctx)); + } + } + + Ok(RenderedArgs { + jvm, + main_class, + game, + }) +} + +fn push_argument( + arg: &Argument, + rule_ctx: &RuleContext, + template_ctx: &TemplateContext, + out: &mut Vec, +) { + match arg { + Argument::Literal(s) => out.push(substitute(s, template_ctx)), + Argument::Conditional { rules, value } => { + if !evaluate(rules, rule_ctx) { + return; + } + match value { + ArgumentValue::Single(s) => out.push(substitute(s, template_ctx)), + ArgumentValue::Multiple(items) => { + for s in items { + out.push(substitute(s, template_ctx)); + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::launch_profile::model::Arguments; + use crate::launch_profile::rules::{FeatureSet, OsCondition, Rule, RuleAction}; + use std::path::PathBuf; + + fn template_fixture<'a>( + library_directory: &'a std::path::Path, + natives_directory: &'a std::path::Path, + game_directory: &'a std::path::Path, + assets_root: &'a std::path::Path, + ) -> TemplateContext<'a> { + TemplateContext { + library_directory, + classpath_separator: ":", + version_name: "1.20.1", + natives_directory, + classpath: "a.jar:b.jar", + game_directory, + assets_root, + assets_index_name: "5", + auth_player_name: "Player", + auth_uuid: "00000000-0000-0000-0000-000000000000", + auth_access_token: "token", + auth_xuid: "0", + user_type: "msa", + user_properties: "{}", + launcher_name: "rmcl", + launcher_version: "0.3.0", + clientid: "0", + } + } + + fn minimal_profile() -> LaunchProfile { + LaunchProfile { + id: "test".into(), + inherits_from: None, + main_class: Some("net.test.Main".into()), + libraries: Vec::new(), + arguments: None, + minecraft_arguments: None, + asset_index: None, + assets: None, + java_version: None, + downloads: None, + release_time: None, + time: None, + type_: None, + } + } + + #[test] + fn legacy_minecraft_arguments_render_into_game() { + let lib = PathBuf::from("/m/libraries"); + let nat = PathBuf::from("/m/natives"); + let game = PathBuf::from("/i/.minecraft"); + let assets = PathBuf::from("/m/assets"); + let template_ctx = template_fixture(&lib, &nat, &game, &assets); + let features = FeatureSet::default(); + let rule_ctx = RuleContext { + os_name: "linux", + arch: "x86_64", + features: &features, + }; + + let mut profile = minimal_profile(); + profile.minecraft_arguments = + Some("--username ${auth_player_name} --version ${version_name}".into()); + + let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + assert_eq!(rendered.main_class, "net.test.Main"); + assert!(rendered.jvm.is_empty()); + assert_eq!( + rendered.game, + vec!["--username", "Player", "--version", "1.20.1"] + ); + } + + #[test] + fn modern_arguments_render_with_literals_and_substitutions() { + let lib = PathBuf::from("/m/libraries"); + let nat = PathBuf::from("/m/natives"); + let game = PathBuf::from("/i/.minecraft"); + let assets = PathBuf::from("/m/assets"); + let template_ctx = template_fixture(&lib, &nat, &game, &assets); + let features = FeatureSet::default(); + let rule_ctx = RuleContext { + os_name: "linux", + arch: "x86_64", + features: &features, + }; + + let mut profile = minimal_profile(); + profile.arguments = Some(Arguments { + game: vec![ + Argument::Literal("--username".into()), + Argument::Literal("${auth_player_name}".into()), + ], + jvm: vec![Argument::Literal( + "-Djava.library.path=${natives_directory}".into(), + )], + }); + + let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + assert_eq!(rendered.game, vec!["--username", "Player"]); + assert_eq!(rendered.jvm, vec!["-Djava.library.path=/m/natives"]); + } + + #[test] + fn conditional_argument_with_single_value_is_filtered_by_os_rule() { + let lib = PathBuf::from("/m/libraries"); + let nat = PathBuf::from("/m/natives"); + let game = PathBuf::from("/i/.minecraft"); + let assets = PathBuf::from("/m/assets"); + let template_ctx = template_fixture(&lib, &nat, &game, &assets); + let features = FeatureSet::default(); + let rule_ctx = RuleContext { + os_name: "linux", + arch: "x86_64", + features: &features, + }; + + let osx_only = Argument::Conditional { + rules: vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("osx".into()), + arch: None, + }), + features: None, + }], + value: ArgumentValue::Single("-XstartOnFirstThread".into()), + }; + + let mut profile = minimal_profile(); + profile.arguments = Some(Arguments { + game: Vec::new(), + jvm: vec![osx_only], + }); + + let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + assert!( + rendered.jvm.is_empty(), + "osx-only arg should be skipped on linux" + ); + } + + #[test] + fn conditional_argument_with_multiple_value_pushes_all() { + let lib = PathBuf::from("/m/libraries"); + let nat = PathBuf::from("/m/natives"); + let game = PathBuf::from("/i/.minecraft"); + let assets = PathBuf::from("/m/assets"); + let template_ctx = template_fixture(&lib, &nat, &game, &assets); + let features = FeatureSet::default(); + let rule_ctx = RuleContext { + os_name: "linux", + arch: "x86_64", + features: &features, + }; + + let linux_arg = Argument::Conditional { + rules: vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("linux".into()), + arch: None, + }), + features: None, + }], + value: ArgumentValue::Multiple(vec![ + "--add-opens".into(), + "java.base/sun.security.util=ALL-UNNAMED".into(), + ]), + }; + + let mut profile = minimal_profile(); + profile.arguments = Some(Arguments { + game: Vec::new(), + jvm: vec![linux_arg], + }); + + let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + assert_eq!( + rendered.jvm, + vec!["--add-opens", "java.base/sun.security.util=ALL-UNNAMED"] + ); + } + + #[test] + fn missing_main_class_returns_error() { + let lib = PathBuf::from("/m/libraries"); + let nat = PathBuf::from("/m/natives"); + let game = PathBuf::from("/i/.minecraft"); + let assets = PathBuf::from("/m/assets"); + let template_ctx = template_fixture(&lib, &nat, &game, &assets); + let features = FeatureSet::default(); + let rule_ctx = RuleContext { + os_name: "linux", + arch: "x86_64", + features: &features, + }; + + let mut profile = minimal_profile(); + profile.main_class = None; + + let result = render_args(&profile, &rule_ctx, &template_ctx); + assert!(matches!(result, Err(RenderError::MissingMainClass))); + } + + #[test] + fn modern_arguments_takes_precedence_over_legacy_field() { + // a profile that somehow has both arguments and minecraft_arguments + // should use arguments only (legacy is fallback). + let lib = PathBuf::from("/m/libraries"); + let nat = PathBuf::from("/m/natives"); + let game = PathBuf::from("/i/.minecraft"); + let assets = PathBuf::from("/m/assets"); + let template_ctx = template_fixture(&lib, &nat, &game, &assets); + let features = FeatureSet::default(); + let rule_ctx = RuleContext { + os_name: "linux", + arch: "x86_64", + features: &features, + }; + + let mut profile = minimal_profile(); + profile.arguments = Some(Arguments { + game: vec![Argument::Literal("--from-arguments".into())], + jvm: Vec::new(), + }); + profile.minecraft_arguments = Some("--from-legacy".into()); + + let rendered = render_args(&profile, &rule_ctx, &template_ctx).unwrap(); + assert_eq!(rendered.game, vec!["--from-arguments"]); + } +} diff --git a/src/net/mod.rs b/src/net/mod.rs index 65da353..c5edf00 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -71,6 +71,10 @@ impl HttpClient { pub async fn get_json(&self, url: &str) -> Result { Ok(self.get(url).await?.json().await?) } + + pub async fn get_bytes(&self, url: &str) -> Result, NetError> { + Ok(self.get(url).await?.bytes().await?.to_vec()) + } } const MAX_RETRIES: u32 = 3; diff --git a/src/net/mojang.rs b/src/net/mojang.rs index 1a9b2f8..b79c154 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -76,7 +76,7 @@ pub struct Download { pub struct Library { pub name: String, pub downloads: LibraryDownloads, - pub rules: Option>, + pub rules: Option>, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -92,17 +92,6 @@ pub struct Artifact { pub size: u64, } -#[derive(Debug, Clone, Deserialize, Serialize)] -pub struct Rule { - pub action: String, - pub os: Option, -} - -#[derive(Debug, Clone, Deserialize, Serialize)] -pub struct OsRule { - pub name: Option, -} - #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct JavaVersion { @@ -131,6 +120,20 @@ pub async fn fetch_version_meta( client.get_json(&entry.url).await } +// like fetch_version_meta but also returns the raw response bytes so the +// caller can write the upstream JSON byte-for-byte to disk. used by the +// install path so we don't lose data (e.g. arguments.jvm) by re-serializing +// through our narrow VersionMeta struct. +pub async fn fetch_version_meta_with_raw( + client: &HttpClient, + entry: &VersionEntry, +) -> Result<(VersionMeta, Vec), NetError> { + let raw = client.get_bytes(&entry.url).await?; + let parsed: VersionMeta = serde_json::from_slice(&raw) + .map_err(|e| NetError::Parse(format!("Failed to parse version meta: {e}")))?; + Ok((parsed, raw)) +} + pub async fn download_client_jar( client: &HttpClient, meta: &VersionMeta, @@ -169,9 +172,18 @@ pub async fn download_libraries( ) -> Result<(), NetError> { set_action("Downloading libraries..."); + let features = crate::launch_profile::rules::FeatureSet::default(); + let rule_ctx = crate::launch_profile::rules::RuleContext { + os_name: mojang_os_name(), + arch: mojang_arch_name(), + features: &features, + }; + let mut downloads = Vec::new(); for library in &meta.libraries { - if !library_allowed_for_current_os(library) { + if let Some(rules) = &library.rules + && !crate::launch_profile::rules::evaluate(rules, &rule_ctx) + { continue; } @@ -281,43 +293,6 @@ pub async fn download_assets( result } -// mojang's rule system is a bit quirky: no rules means "allow everywhere", -// and rules are evaluated in order where the last matching rule wins. -// a "disallow" for the current OS is an immediate reject though. -fn library_allowed_for_current_os(library: &Library) -> bool { - let rules = match &library.rules { - Some(rules) => rules, - None => return true, - }; - - let current_os = mojang_os_name(); - let mut allowed = false; - - for rule in rules { - let matches_os = match &rule.os { - Some(os_rule) => match &os_rule.name { - Some(name) => name == current_os, - None => true, - }, - None => true, - }; - - if !matches_os { - continue; - } - - if rule.action == "disallow" { - return false; - } - - if rule.action == "allow" { - allowed = true; - } - } - - allowed -} - // mojang calls macOS "osx" because apparently it's still 2012 fn mojang_os_name() -> &'static str { match std::env::consts::OS { @@ -326,6 +301,15 @@ fn mojang_os_name() -> &'static str { } } +fn mojang_arch_name() -> &'static str { + match std::env::consts::ARCH { + "x86" => "x86", + "x86_64" => "x86_64", + "aarch64" => "arm64", + other => other, + } +} + // bounded parallel downloader. spawns up to MAX_CONCURRENT_DOWNLOADS tasks // and feeds new ones in as each completes. collects errors but keeps going // so it downloads as much as possible before reporting the first failure.