refactored: review findings - style and abstraction cleanup
- drop stale phase planning comments from launch_profile module headers. - simplify merge_libraries to HashSet<&str> (no string clones). - rewrite coord_key with match_indices (clearer intent). - read /proc/sys/kernel/osrelease on linux for mojang_os_version instead of shelling out to uname; return empty elsewhere. - add comment explaining why is_retryable excludes Parse. - shorten the launch_profile::... paths in launch/mod.rs with top-level use statements. - derive Default on LaunchProfile + nested types so test fixtures use ..Default::default() instead of listing every None field. - inline account_can_launch at its single call site, delete the helper and three tests that exercised trivially-correct one-line logic. - extract get_json_with_raw on HttpClient and save_profile_bytes in instance::loader; collapses three near-identical fetch_X_profile_with_raw helpers and three near-identical 'create dir + write bytes' blocks.
This commit is contained in:
1 parent
412e6ff91a
commit
363ada8211
15 files changed
+155
-292
No files matched your search
+73
-173
@@ -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<String>, Vec<String>), 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<Option<crate::launch_profile::model::LaunchProfile>, LaunchError> {
|
||||
) -> Result<Option<LaunchProfile>, 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<Option<crate::launch_profile::model::LaunchProfile>, LaunchError> {
|
||||
) -> Result<Option<LaunchProfile>, 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<PathBuf> = 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 {
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,20 @@ pub trait ModLoaderInstaller: Send + Sync {
|
||||
) -> Result<(), NetError>;
|
||||
}
|
||||
|
||||
// writes raw profile JSON bytes to meta_dir/loader-profiles/<filename>.
|
||||
// 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 -
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct Library {
|
||||
pub name: String,
|
||||
pub downloads: Option<LibraryDownloads>,
|
||||
@@ -73,12 +69,12 @@ pub struct Library {
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct LibraryDownloads {
|
||||
pub artifact: Option<Artifact>,
|
||||
}
|
||||
|
||||
#[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<u64>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
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,
|
||||
|
||||
@@ -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,
|
||||
}],
|
||||
|
||||
@@ -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<crate::launch_profile::model::Library>,
|
||||
) -> Vec<crate::launch_profile::model::Library> {
|
||||
use std::collections::HashSet;
|
||||
let child_keys: HashSet<String> = 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<crate::launch_profile::model::Library> = 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,
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
+1
-4
@@ -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.
|
||||
|
||||
+1
-5
@@ -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(())
|
||||
}
|
||||
|
||||
|
||||
+19
-1
@@ -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<T: DeserializeOwned>(
|
||||
&self,
|
||||
url: &str,
|
||||
label: &str,
|
||||
) -> Result<(T, Vec<u8>), 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(),
|
||||
|
||||
+1
-4
@@ -121,10 +121,7 @@ pub async fn fetch_version_meta_with_raw(
|
||||
client: &HttpClient,
|
||||
entry: &VersionEntry,
|
||||
) -> Result<(VersionMeta, Vec<u8>), 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(
|
||||
|
||||
+1
-4
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user