diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index 5d9152d..ecf6356 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -8,8 +8,12 @@ use std::path::{Path, PathBuf}; use thiserror::Error; -use crate::auth::{Account, AccountType}; +use crate::auth::AccountType; use crate::instance::models::{InstanceConfig, ModLoader}; +use crate::launch_profile::model::LaunchProfile; +use crate::launch_profile::rules::{self, FeatureSet, RuleContext}; +use crate::launch_profile::templates::TemplateContext; +use crate::launch_profile::{render, resolve, system}; #[derive(Debug, Error)] pub enum LaunchError { @@ -27,16 +31,12 @@ pub enum LaunchError { Auth(String), } -fn account_can_launch(has_microsoft_account: bool, account: &Account) -> bool { - account.account_type == AccountType::Microsoft || has_microsoft_account -} - fn build_game_args( - profile: &crate::launch_profile::model::LaunchProfile, - rule_ctx: &crate::launch_profile::rules::RuleContext<'_>, - template_ctx: &crate::launch_profile::templates::TemplateContext<'_>, + profile: &LaunchProfile, + rule_ctx: &RuleContext<'_>, + template_ctx: &TemplateContext<'_>, ) -> Result<(Vec, Vec), LaunchError> { - let rendered = crate::launch_profile::render::render_args(profile, rule_ctx, template_ctx) + let rendered = render::render_args(profile, rule_ctx, template_ctx) .map_err(|e| LaunchError::Parse(format!("Failed to render args: {e}")))?; Ok((rendered.jvm, rendered.game)) } @@ -48,9 +48,9 @@ fn build_game_args( // 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, + profile: &LaunchProfile, game_version: &str, -) -> Result, LaunchError> { +) -> Result, LaunchError> { if profile.arguments.is_some() || profile.minecraft_arguments.is_some() { return Ok(None); } @@ -93,7 +93,7 @@ async fn migrate_legacy_meta_if_needed( tokio::fs::write(meta_path, &raw).await?; - let refreshed: crate::launch_profile::model::LaunchProfile = serde_json::from_slice(&raw) + let refreshed: LaunchProfile = serde_json::from_slice(&raw) .map_err(|e| LaunchError::Parse(format!("Failed to parse refreshed meta: {e}")))?; Ok(Some(refreshed)) } @@ -121,10 +121,10 @@ fn installer_version_dir_name( // rebuild from the installer's original JSON if it's still on disk. async fn migrate_legacy_loader_profile_if_needed( profile_path: &Path, - profile: &crate::launch_profile::model::LaunchProfile, + profile: &LaunchProfile, config: &InstanceConfig, instance_dir: &Path, -) -> Result, LaunchError> { +) -> Result, LaunchError> { // Fabric and Quilt fetch their profiles from a network endpoint at // install time; there's no installer-written JSON on disk to recover // from. their upstream profiles also happen to match the "legacy @@ -196,10 +196,9 @@ async fn migrate_legacy_loader_profile_if_needed( let raw = tokio::fs::read(&installer_json_path).await?; tokio::fs::write(profile_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 loader profile: {e}")) - })?; + let refreshed: LaunchProfile = serde_json::from_slice(&raw).map_err(|e| { + LaunchError::Parse(format!("Failed to parse refreshed loader profile: {e}")) + })?; Ok(Some(refreshed)) } @@ -219,19 +218,18 @@ pub async fn launch( if !meta_path.exists() { return Err(LaunchError::MetaNotFound(meta_path.display().to_string())); } - let meta: crate::launch_profile::model::LaunchProfile = - serde_json::from_slice(&tokio::fs::read(&meta_path).await?)?; + let meta: 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 host_os_version = crate::launch_profile::system::mojang_os_version(); - let rule_ctx = crate::launch_profile::rules::RuleContext { - os_name: crate::launch_profile::system::mojang_os_name(), + let current_features = FeatureSet::default(); + let host_os_version = system::mojang_os_version(); + let rule_ctx = RuleContext { + os_name: system::mojang_os_name(), os_version: &host_os_version, - arch: crate::launch_profile::system::mojang_arch_name(), + arch: system::mojang_arch_name(), features: ¤t_features, }; @@ -256,41 +254,40 @@ pub async fn launch( // if needed, and resolve `inheritsFrom` against the vanilla parent (which // the vanilla meta migration above ensured is fresh on disk). when no // loader is configured we use the already-loaded vanilla meta directly. - let merged_profile: crate::launch_profile::model::LaunchProfile = - if let Some(filename) = &profile_filename { - let profile_path = meta_dir.join("loader-profiles").join(filename); - if !profile_path.exists() { - return Err(LaunchError::MetaNotFound( - profile_path.display().to_string(), - )); - } - let mut loader_profile: crate::launch_profile::model::LaunchProfile = - serde_json::from_slice(&tokio::fs::read(&profile_path).await?)?; + let merged_profile: LaunchProfile = if let Some(filename) = &profile_filename { + let profile_path = meta_dir.join("loader-profiles").join(filename); + if !profile_path.exists() { + return Err(LaunchError::MetaNotFound( + profile_path.display().to_string(), + )); + } + let mut loader_profile: LaunchProfile = + serde_json::from_slice(&tokio::fs::read(&profile_path).await?)?; - if let Some(refreshed) = migrate_legacy_loader_profile_if_needed( - &profile_path, - &loader_profile, - config, - &instance_dir, - ) - .await? - { - loader_profile = refreshed; - } + if let Some(refreshed) = migrate_legacy_loader_profile_if_needed( + &profile_path, + &loader_profile, + config, + &instance_dir, + ) + .await? + { + loader_profile = refreshed; + } - // legacy installer-written profiles (and any loader profile that - // omits inheritsFrom) still need to be layered over vanilla. set - // the inherit explicitly so resolve() walks the chain. - if loader_profile.inherits_from.is_none() { - loader_profile.inherits_from = Some(config.game_version.clone()); - } + // legacy installer-written profiles (and any loader profile that + // omits inheritsFrom) still need to be layered over vanilla. set + // the inherit explicitly so resolve() walks the chain. + if loader_profile.inherits_from.is_none() { + loader_profile.inherits_from = Some(config.game_version.clone()); + } - crate::launch_profile::resolve::resolve(loader_profile, meta_dir) - .await - .map_err(|e| LaunchError::Parse(format!("Failed to resolve loader profile: {e}")))? - } else { - meta.clone() - }; + resolve::resolve(loader_profile, meta_dir) + .await + .map_err(|e| LaunchError::Parse(format!("Failed to resolve loader profile: {e}")))? + } else { + meta.clone() + }; let main_class = merged_profile .main_class @@ -308,7 +305,7 @@ pub async fn launch( let mut classpath: Vec = Vec::new(); for lib in &merged_profile.libraries { if let Some(rules) = &lib.rules - && !crate::launch_profile::rules::evaluate(rules, &rule_ctx) + && !rules::evaluate(rules, &rule_ctx) { continue; } @@ -373,7 +370,10 @@ pub async fn launch( .cloned() { Some(acc) => { - if !account_can_launch(account_store.has_microsoft_account(), &acc) { + // offline accounts can only launch if a microsoft account exists + // (proves the user owns minecraft). + if acc.account_type != AccountType::Microsoft && !account_store.has_microsoft_account() + { return Err(LaunchError::Auth( "Offline accounts require a Microsoft account that owns Minecraft".to_owned(), )); @@ -425,7 +425,7 @@ pub async fn launch( .join("versions") .join(&config.game_version) .join("natives"); - let template_ctx = crate::launch_profile::templates::TemplateContext { + let template_ctx = TemplateContext { library_directory: &lib_dir, classpath_separator: sep, version_name: &config.game_version, @@ -589,25 +589,12 @@ pub async fn launch( #[cfg(test)] mod tests { use super::*; - use crate::auth::{Account, AccountType}; - - fn test_account(account_type: AccountType) -> Account { - Account { - uuid: "00000000-0000-0000-0000-000000000001".to_owned(), - username: "TestPlayer".to_owned(), - account_type, - active: true, - refresh_token: Some("refresh".to_owned()), - cached_mc_token: None, - cached_mc_token_expires_at: None, - } - } #[test] 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 TemplateContext; use std::path::PathBuf; let lib = PathBuf::from("/m/libraries"); @@ -656,16 +643,7 @@ mod tests { "-Djava.library.path=${natives_directory}".into(), )], }), - minecraft_arguments: None, - asset_index: None, - assets: None, - java_version: None, - downloads: None, - release_time: None, - time: None, - game_arguments: None, - - type_: None, + ..Default::default() }; let (jvm, game_args) = build_game_args(&profile, &rule_ctx, &template_ctx).unwrap(); @@ -673,46 +651,15 @@ mod tests { assert_eq!(game_args, vec!["--username", "Player"]); } - #[test] - fn offline_account_cannot_launch_without_microsoft_account() { - let offline = test_account(AccountType::Offline); - - assert!(!account_can_launch(false, &offline)); - } - - #[test] - fn offline_account_can_launch_with_microsoft_account() { - let offline = test_account(AccountType::Offline); - - assert!(account_can_launch(true, &offline)); - } - - #[test] - fn microsoft_account_can_launch_without_offline_gate() { - let microsoft = test_account(AccountType::Microsoft); - - assert!(account_can_launch(false, µsoft)); - } - #[test] fn migration_predicate_triggers_when_both_argument_fields_absent() { - use crate::launch_profile::model::LaunchProfile; + use 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, - game_arguments: None, - - type_: None, + ..Default::default() }; assert!(stripped.arguments.is_none() && stripped.minecraft_arguments.is_none()); } @@ -726,23 +673,14 @@ mod tests { 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, - game_arguments: None, - - type_: None, + ..Default::default() }; assert!(modern.arguments.is_some()); } #[test] fn migration_predicate_skips_when_legacy_minecraft_arguments_present() { - use crate::launch_profile::model::LaunchProfile; + use LaunchProfile; let legacy = LaunchProfile { id: "1.7.10".into(), inherits_from: None, @@ -750,15 +688,7 @@ mod tests { 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, - game_arguments: None, - - type_: None, + ..Default::default() }; assert!(legacy.minecraft_arguments.is_some()); } @@ -788,23 +718,13 @@ mod tests { #[test] fn loader_profile_legacy_predicate_triggers_when_all_three_absent() { - use crate::launch_profile::model::LaunchProfile; + use LaunchProfile; let legacy = LaunchProfile { id: "1.20.1-forge-47.2.0".into(), inherits_from: None, main_class: Some("cpw.mods.bootstraplauncher.BootstrapLauncher".into()), libraries: Vec::new(), - arguments: None, - minecraft_arguments: None, - asset_index: None, - assets: None, - java_version: None, - downloads: None, - release_time: None, - time: None, - game_arguments: None, - - type_: None, + ..Default::default() }; let is_legacy = legacy.inherits_from.is_none() && legacy.arguments.is_none() @@ -814,23 +734,13 @@ mod tests { #[test] fn loader_profile_legacy_predicate_skips_modern_profile_with_inherits_from() { - use crate::launch_profile::model::LaunchProfile; + use LaunchProfile; let modern = LaunchProfile { id: "1.20.1-forge-47.2.0".into(), inherits_from: Some("1.20.1".into()), main_class: Some("cpw.mods.bootstraplauncher.BootstrapLauncher".into()), libraries: Vec::new(), - arguments: None, - minecraft_arguments: None, - asset_index: None, - assets: None, - java_version: None, - downloads: None, - release_time: None, - time: None, - game_arguments: None, - - type_: None, + ..Default::default() }; let is_legacy = modern.inherits_from.is_none() && modern.arguments.is_none() @@ -844,7 +754,7 @@ mod tests { // shape (no inheritsFrom, no arguments, no minecraftArguments). // make sure the migration helper recognises this is Fabric and // returns Ok(None) instead of erroring with "reinstall Fabric". - use crate::launch_profile::model::LaunchProfile; + use LaunchProfile; use chrono::Utc; use tempfile::TempDir; @@ -859,17 +769,7 @@ mod tests { inherits_from: None, main_class: Some("net.fabricmc.loader.impl.launch.knot.KnotClient".into()), libraries: Vec::new(), - arguments: None, - minecraft_arguments: None, - asset_index: None, - assets: None, - java_version: None, - downloads: None, - release_time: None, - time: None, - game_arguments: None, - - type_: None, + ..Default::default() }; let config = InstanceConfig { diff --git a/src/instance/loader/fabric.rs b/src/instance/loader/fabric.rs index ae658cf..ae69dcb 100644 --- a/src/instance/loader/fabric.rs +++ b/src/instance/loader/fabric.rs @@ -44,13 +44,11 @@ impl ModLoaderInstaller for FabricInstaller { let (profile, raw_bytes) = fabric_api::fetch_fabric_profile_with_raw(client, game_version, loader_version).await?; fabric_api::download_fabric_libraries(client, &profile, meta_dir).await?; - - let profiles_dir = meta_dir.join("loader-profiles"); - std::fs::create_dir_all(&profiles_dir)?; - let profile_path = - profiles_dir.join(format!("fabric-{game_version}-{loader_version}.json")); - std::fs::write(&profile_path, &raw_bytes)?; - + super::save_profile_bytes( + meta_dir, + &format!("fabric-{game_version}-{loader_version}.json"), + &raw_bytes, + )?; Ok(()) } } diff --git a/src/instance/loader/mod.rs b/src/instance/loader/mod.rs index 7a91f14..e670341 100644 --- a/src/instance/loader/mod.rs +++ b/src/instance/loader/mod.rs @@ -46,6 +46,20 @@ pub trait ModLoaderInstaller: Send + Sync { ) -> Result<(), NetError>; } +// writes raw profile JSON bytes to meta_dir/loader-profiles/. +// callers that already have the upstream bytes (fabric/quilt http fetch, +// legacy forge versionInfo extract) use this directly to keep the on-disk +// file byte-for-byte identical to the source. +pub(crate) fn save_profile_bytes( + meta_dir: &Path, + filename: &str, + bytes: &[u8], +) -> std::io::Result<()> { + let profiles_dir = meta_dir.join("loader-profiles"); + std::fs::create_dir_all(&profiles_dir)?; + std::fs::write(profiles_dir.join(filename), bytes) +} + // used by forge/neoforge. their java installer drops a version json into // .minecraft/versions/. we copy that file byte-for-byte to our loader // profile cache so launch-time code sees the full upstream JSON - diff --git a/src/instance/loader/quilt.rs b/src/instance/loader/quilt.rs index 3e208c7..8ad4b8b 100644 --- a/src/instance/loader/quilt.rs +++ b/src/instance/loader/quilt.rs @@ -44,12 +44,11 @@ impl ModLoaderInstaller for QuiltInstaller { let (profile, raw_bytes) = quilt_api::fetch_quilt_profile_with_raw(client, game_version, loader_version).await?; quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?; - - let profiles_dir = meta_dir.join("loader-profiles"); - std::fs::create_dir_all(&profiles_dir)?; - let profile_path = profiles_dir.join(format!("quilt-{game_version}-{loader_version}.json")); - std::fs::write(&profile_path, &raw_bytes)?; - + super::save_profile_bytes( + meta_dir, + &format!("quilt-{game_version}-{loader_version}.json"), + &raw_bytes, + )?; Ok(()) } } diff --git a/src/launch_profile/mod.rs b/src/launch_profile/mod.rs index 40a2283..3e5cbde 100644 --- a/src/launch_profile/mod.rs +++ b/src/launch_profile/mod.rs @@ -1,8 +1,7 @@ -// foundation primitives for parsing, merging, and rendering mojang-format -// launch profiles. consumed by the vanilla launcher, forge/neoforge, -// fabric/quilt - anything that reads a mojang-style version JSON. -// -// phase 3 adds the `resolve` module that walks `inheritsFrom` chains. +// primitives for parsing, merging, and rendering mojang-format launch +// profiles. consumed by the vanilla launcher and the loader install paths +// (forge/neoforge/fabric/quilt) - anything that reads a mojang-style +// version JSON. pub mod model; pub mod render; diff --git a/src/launch_profile/model.rs b/src/launch_profile/model.rs index aabfa5f..127c3ed 100644 --- a/src/launch_profile/model.rs +++ b/src/launch_profile/model.rs @@ -4,16 +4,12 @@ // the fields we care about; unknown fields are silently dropped (serde // default behavior) - which is fine because we write upstream JSON // byte-for-byte on the install side. -// -// no consumers yet. phase 2 wires this into the vanilla launch path; -// phase 3 adds inheritsFrom resolution; phase 4 swaps the forge/neoforge -// installer profile writer over to use this shape. use serde::{Deserialize, Serialize}; use super::rules::Rule; -#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct LaunchProfile { pub id: String, @@ -65,7 +61,7 @@ pub enum ArgumentValue { Multiple(Vec), } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct Library { pub name: String, pub downloads: Option, @@ -73,12 +69,12 @@ pub struct Library { pub url: Option, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct LibraryDownloads { pub artifact: Option, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct Artifact { pub url: String, pub path: String, @@ -86,7 +82,7 @@ pub struct Artifact { pub size: u64, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct AssetIndex { pub id: String, pub url: String, @@ -95,19 +91,19 @@ pub struct AssetIndex { pub total_size: Option, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct JavaVersion { pub component: Option, pub major_version: u32, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct VersionDownloads { pub client: Download, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct Download { pub url: String, pub sha1: String, diff --git a/src/launch_profile/render.rs b/src/launch_profile/render.rs index 8351f95..f156b09 100644 --- a/src/launch_profile/render.rs +++ b/src/launch_profile/render.rs @@ -115,19 +115,8 @@ mod tests { 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, - game_arguments: None, - type_: None, + ..Default::default() } } @@ -211,7 +200,7 @@ mod tests { os: Some(OsCondition { name: Some("osx".into()), arch: None, - version: None, + ..Default::default() }), features: None, }], @@ -252,7 +241,7 @@ mod tests { os: Some(OsCondition { name: Some("linux".into()), arch: None, - version: None, + ..Default::default() }), features: None, }], diff --git a/src/launch_profile/resolve.rs b/src/launch_profile/resolve.rs index c61158a..fe1b50e 100644 --- a/src/launch_profile/resolve.rs +++ b/src/launch_profile/resolve.rs @@ -67,16 +67,9 @@ pub fn merge_into(child: LaunchProfile, parent: LaunchProfile) -> LaunchProfile fn coord_key(name: &str) -> &str { // mojang maven coords are `group:artifact:version[:classifier]`. take // everything up to the second colon. - let mut count = 0; - for (i, b) in name.bytes().enumerate() { - if b == b':' { - count += 1; - if count == 2 { - return &name[..i]; - } - } - } - name + let mut it = name.match_indices(':').map(|(i, _)| i); + it.next(); + it.next().map_or(name, |i| &name[..i]) } // child entries take precedence over parent entries with the same @@ -89,10 +82,7 @@ fn merge_libraries( parent: Vec, ) -> Vec { use std::collections::HashSet; - let child_keys: HashSet = child - .iter() - .map(|l| coord_key(&l.name).to_string()) - .collect(); + let child_keys: HashSet<&str> = child.iter().map(|l| coord_key(&l.name)).collect(); let mut out: Vec = parent .into_iter() @@ -164,28 +154,14 @@ mod tests { fn empty_profile(id: &str) -> LaunchProfile { LaunchProfile { id: id.into(), - inherits_from: None, - main_class: None, - libraries: Vec::new(), - arguments: None, - minecraft_arguments: None, - asset_index: None, - assets: None, - java_version: None, - downloads: None, - release_time: None, - time: None, - game_arguments: None, - type_: None, + ..Default::default() } } fn lib(name: &str) -> Library { Library { name: name.into(), - downloads: None, - rules: None, - url: None, + ..Default::default() } } @@ -194,8 +170,7 @@ mod tests { action: RuleAction::Allow, os: Some(crate::launch_profile::rules::OsCondition { name: Some("linux".into()), - arch: None, - version: None, + ..Default::default() }), features: None, } diff --git a/src/launch_profile/rules.rs b/src/launch_profile/rules.rs index e38bbda..cccfe67 100644 --- a/src/launch_profile/rules.rs +++ b/src/launch_profile/rules.rs @@ -142,7 +142,7 @@ mod tests { os: Some(OsCondition { name: Some("linux".into()), arch: None, - version: None, + ..Default::default() }), features: None, }]; @@ -158,7 +158,7 @@ mod tests { os: Some(OsCondition { name: Some("linux".into()), arch: None, - version: None, + ..Default::default() }), features: None, }]; @@ -176,7 +176,7 @@ mod tests { os: Some(OsCondition { name: Some("windows".into()), arch: None, - version: None, + ..Default::default() }), features: None, }]; @@ -198,7 +198,7 @@ mod tests { os: Some(OsCondition { name: Some("osx".into()), arch: None, - version: None, + ..Default::default() }), features: None, }, @@ -229,7 +229,7 @@ mod tests { os: Some(OsCondition { name: Some("linux".into()), arch: None, - version: None, + ..Default::default() }), features: None, }, diff --git a/src/launch_profile/system.rs b/src/launch_profile/system.rs index 037745d..f41da61 100644 --- a/src/launch_profile/system.rs +++ b/src/launch_profile/system.rs @@ -21,29 +21,17 @@ pub fn mojang_arch_name() -> &'static str { // the host OS version string. mojang rules occasionally constrain natives // selection on os.version with a regex (e.g. macOS 10.x-only natives). -// rust's stdlib doesn't expose this directly, so we synthesise something -// useful per-platform. on linux we read the kernel version; on macOS the -// product version is more useful but reading it requires shelling out so -// we fall back to the kernel version. on windows we use a similar -// approach. real-world profiles using os.version are rare; if this helper -// returns an empty string the rule evaluator treats version constraints -// as non-matching (defensive default). +// rust's stdlib doesn't expose this, so we read it where it's cheap and +// reliable: linux via /proc/sys/kernel/osrelease, other platforms return +// empty. when the host string is empty, version-gated rules don't match +// (conservative default in the rule evaluator) - which is fine because +// real-world profiles using os.version are vanishingly rare. pub fn mojang_os_version() -> String { - #[cfg(unix)] + #[cfg(target_os = "linux")] { - use std::process::Command; - if let Ok(out) = Command::new("uname").arg("-r").output() - && out.status.success() - { - return String::from_utf8_lossy(&out.stdout).trim().to_string(); + if let Ok(s) = std::fs::read_to_string("/proc/sys/kernel/osrelease") { + return s.trim().to_string(); } } - #[cfg(windows)] - { - // crude - sufficient for the rare profile that needs windows version - // gating. real launchers use GetVersionEx via winapi; we can add - // that later if needed. - return std::env::var("OS").unwrap_or_default(); - } String::new() } diff --git a/src/net/fabric.rs b/src/net/fabric.rs index 3587520..aea2644 100644 --- a/src/net/fabric.rs +++ b/src/net/fabric.rs @@ -90,10 +90,7 @@ pub async fn fetch_fabric_profile_with_raw( "{}/versions/loader/{}/{}/profile/json", FABRIC_META_BASE, game_version, loader_version ); - let raw = client.get_bytes(&url).await?; - let parsed: FabricProfile = serde_json::from_slice(&raw) - .map_err(|e| NetError::Parse(format!("Failed to parse Fabric profile: {e}")))?; - Ok((parsed, raw)) + client.get_json_with_raw(&url, "Fabric profile").await } // each fabric library entry has a maven coordinate and a base url. diff --git a/src/net/forge.rs b/src/net/forge.rs index 04b0516..ba11279 100644 --- a/src/net/forge.rs +++ b/src/net/forge.rs @@ -279,13 +279,9 @@ pub(crate) async fn install_forge_from_profile( // and whitespace may differ from the original installer JSON because // the source is a serde_json::Value (which doesn't preserve order), // but no field is silently dropped. - let profiles_dir = meta_dir.join("loader-profiles"); - std::fs::create_dir_all(&profiles_dir)?; - let profile_path = profiles_dir.join(profile_filename); let serialized = serde_json::to_vec(version_info) .map_err(|e| NetError::Parse(format!("Failed to serialize Forge profile: {e}")))?; - std::fs::write(&profile_path, &serialized)?; - + crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)?; Ok(()) } diff --git a/src/net/mod.rs b/src/net/mod.rs index 09b6be3..cdd05cb 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -80,6 +80,21 @@ impl HttpClient { ) .await } + + // fetch JSON and also keep the raw bytes. used by install paths that + // want both the parsed shape (for downloading libraries from it) and + // the original bytes (to write byte-for-byte to the loader-profiles + // cache, so any field we don't know about survives). + pub async fn get_json_with_raw( + &self, + url: &str, + label: &str, + ) -> Result<(T, Vec), NetError> { + let raw = self.get_bytes(url).await?; + let parsed: T = serde_json::from_slice(&raw) + .map_err(|e| NetError::Parse(format!("Failed to parse {label}: {e}")))?; + Ok((parsed, raw)) + } } // shared retry envelope around `client.get(url).await? -> decode`. retries @@ -183,7 +198,10 @@ async fn download_file_once( Ok(()) } -// body decode errors and timeouts are worth retrying, but a 404 or disk error isn't +// body decode errors and timeouts are worth retrying, but a 404 or disk +// error isn't. Parse errors stay non-retryable: by the time we hit one +// the response body has fully arrived, so the failure means the upstream +// returned malformed JSON - retrying won't fix that. fn is_retryable(err: &NetError) -> bool { match err { NetError::Http(e) => e.is_timeout() || e.is_body() || e.is_connect(), diff --git a/src/net/mojang.rs b/src/net/mojang.rs index c92105a..d8b0dcc 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -121,10 +121,7 @@ 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)) + client.get_json_with_raw(&entry.url, "version meta").await } pub async fn download_client_jar( diff --git a/src/net/quilt.rs b/src/net/quilt.rs index fef5d59..eb9ceec 100644 --- a/src/net/quilt.rs +++ b/src/net/quilt.rs @@ -87,10 +87,7 @@ pub async fn fetch_quilt_profile_with_raw( "{}/versions/loader/{}/{}/profile/json", QUILT_META_BASE, game_version, loader_version ); - let raw = client.get_bytes(&url).await?; - let parsed: QuiltProfile = serde_json::from_slice(&raw) - .map_err(|e| NetError::Parse(format!("Failed to parse Quilt profile: {e}")))?; - Ok((parsed, raw)) + client.get_json_with_raw(&url, "Quilt profile").await } pub async fn download_quilt_libraries(