20 Commits
Author SHA1 Message Date
objz 8f16931502 chore: v0.3.2 2026-06-16 15:17:55 +02:00
objz a95250cf9a Merge pull request #21 from objz/fix/adding-neoforge-instance-fails
Fix/adding neoforge instance fails
2026-06-16 15:13:30 +02:00
objz 2adfd0afbd Merge pull request #20 from objz/fix/sun-misc-unsafe-memory-accessallow
Fix/sun misc unsafe memory accessallow
2026-06-16 15:13:15 +02:00
objz 3ab6adf700 Merge pull request #22 from objz/fix/aur-failed-to-install
fix(pkg): isolate cargo target and config for AUR builds
2026-06-16 15:12:31 +02:00
objz 7c59758f5f fix(pkg): isolate cargo target and config for AUR builds 2026-06-16 15:08:14 +02:00
objz 63d7ef0fa1 fix: lib directory should point to the local libs preffered, only shared libs as backup to prevent corruption neoforge installation 2026-06-16 14:13:57 +02:00
objz 68d2f45236 fix: point -Duser to the right directory to prevent crashes 2026-06-16 14:13:57 +02:00
objz 3dd384c5c6 fixed clippy fail on windows caused by dead code that is only needed on unix 2026-06-16 14:01:32 +02:00
objz c5da2c7c99 fixed duplicate error messages on installer failure and added new error type 2026-06-16 13:25:28 +02:00
objz 1fd1b4e09d fix(launch): validate required Java version before launch 2026-06-16 12:32:37 +02:00
objz 0d9cd9c6b8 fixed duplicate logs 2026-06-16 12:26:18 +02:00
objz 09f403aa07 fixed noisy log 2026-06-16 12:07:31 +02:00
objz 3d7f233e27 fixed clippy issues 2026-06-16 10:35:34 +02:00
objz db23b86dca fix: flush downloaded files before returning 2026-06-16 10:27:21 +02:00
objz 09bc8f26fb chore: improve rmcl diagnostic logging 2026-06-16 10:22:51 +02:00
objz a58e6fb76d style: apply rustfmt 2026-06-16 09:58:34 +02:00
objz 7723716e18 Merge pull request #12 from objz/stout/sterr-parse-tui
added minecraft log parser
2026-06-13 16:53:21 +02:00
objz 29280e9f8d added minecraft log parser 2026-06-13 16:27:05 +02:00
objz e7e033715e fixed shocase gif 2026-06-12 11:36:19 +02:00
objz 4c22381675 added showcase.gif to the readme 2026-06-12 09:58:18 +02:00
51 changed files with 2137 additions and 332 deletions

No files matched your search

Generated
+61 -1
View File
@@ -1053,6 +1053,15 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd2e7510819d6fbf51a5545c8f922716ecfb14df168a3242f7d33e0239efe6a1"
[[package]]
name = "fast-strip-ansi"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3086ffd0a7160f58f988c74173a002e255da505a114e2f5425acb1eaab2b8ac"
dependencies = [
"vt-push-parser",
]
[[package]]
name = "fastrand"
version = "2.4.1"
@@ -1244,6 +1253,16 @@ dependencies = [
"slab",
]
[[package]]
name = "gdb-command"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73b2762e2f2c0768e1137b33e9f7cf31599994e96496f4e020cc16e0d4e66319"
dependencies = [
"regex",
"wait-timeout",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -1927,6 +1946,12 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "kodama"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f868feceed4703c842925c14232667c5f29c8059d0354154b2d06ec3bf9daf82"
[[package]]
name = "kqueue"
version = "1.1.1"
@@ -1977,6 +2002,19 @@ version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "libcasr"
version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "159cff1fadbb464709c30306774c57171e98cc1ea41e7767df5c63819743a453"
dependencies = [
"chrono",
"gdb-command",
"kodama",
"regex",
"thiserror 2.0.18",
]
[[package]]
name = "libm"
version = "0.2.16"
@@ -3157,7 +3195,7 @@ dependencies = [
[[package]]
name = "rmcl"
version = "0.3.1"
version = "0.3.2"
dependencies = [
"async-trait",
"chrono",
@@ -3167,8 +3205,10 @@ dependencies = [
"crossterm 0.29.0",
"dirs",
"dirs-next",
"fast-strip-ansi",
"image",
"insta",
"libcasr",
"log",
"minecraft-msa-auth",
"notify",
@@ -3178,6 +3218,7 @@ dependencies = [
"ratatui-image",
"ratatui-textarea",
"ratatui-themekit",
"regex",
"reqwest",
"rstest",
"serde",
@@ -4331,6 +4372,16 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
[[package]]
name = "vt-push-parser"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdbf39d53c5a50cad8119d9cde929ecd208764e8d8d1626486b8929cbcd5f0e7"
dependencies = [
"hex",
"smallvec",
]
[[package]]
name = "vtparse"
version = "0.6.2"
@@ -4340,6 +4391,15 @@ dependencies = [
"utf8parse",
]
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "walkdir"
version = "2.5.0"
+4 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rmcl"
version = "0.3.1"
version = "0.3.2"
authors = ["objz"]
edition = "2024"
description = "A fully featured Minecraft TUI launcher"
@@ -58,6 +58,9 @@ open = "5"
which = "8.0.2"
dirs = "6.0.0"
notify = "8"
regex = "1"
fast-strip-ansi = "0.13"
libcasr = "2.13"
[profile.release]
+3 -2
View File
@@ -24,6 +24,8 @@ we all love TUIs. and we all know the official Minecraft launcher is not exactly
it does everything you'd expect from a launcher. multiple instances, mod loaders, modpack imports, Microsoft auth, content management, launching. all from a TUI or from the command line. the TUI is the main thing though, the CLI is there for scripting and automation.
![shocase](assets/showcase.gif)
## features
| | |
@@ -31,10 +33,9 @@ it does everything you'd expect from a launcher. multiple instances, mod loaders
| **instances** | create and manage multiple instances, each with their own version, loader, mods, and settings |
| **mod loaders** | vanilla, Fabric, Quilt, Forge, NeoForge. more might show up later |
| **content** | browse and toggle mods, shaders, resource packs. view worlds, screenshots, and logs |
| **modpack import** | import from Modrinth via `.mrpack` file, URL, or slug |
| **modpack import** | import from Modrinth or MultiMC or GTNH via file, URL, or slug |
| **accounts** | multiple Microsoft accounts and offline players, switch between them |
| **launching** | launch directly from the TUI or generate a desktop shortcut for any instance |
| **desktop shortcuts** | click it and Minecraft starts, no need to open rmcl or type anything |
| **CLI** | every feature the TUI has is also available as a subcommand |
| **theming** | 10 built-in themes, custom themes, color overrides |
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 MiB

+5
View File
@@ -20,11 +20,16 @@ pkgver() {
}
build() {
export CARGO_TARGET_DIR="$srcdir/target"
rm -rf "$CARGO_TARGET_DIR"
cd "$srcdir/rmcl"
cargo build --release --locked
}
check() {
export CARGO_TARGET_DIR="$srcdir/target"
export XDG_CONFIG_HOME="$srcdir/xdg-config"
mkdir -p "$XDG_CONFIG_HOME"
cd "$srcdir/rmcl"
cargo test --release --locked
}
+5
View File
@@ -15,11 +15,16 @@ source=("${url}/archive/v${pkgver}.tar.gz")
sha256sums=('SKIP')
build() {
export CARGO_TARGET_DIR="$srcdir/target"
rm -rf "$CARGO_TARGET_DIR"
cd "$srcdir/rmcl-${pkgver}"
cargo build --release --locked
}
check() {
export CARGO_TARGET_DIR="$srcdir/target"
export XDG_CONFIG_HOME="$srcdir/xdg-config"
mkdir -p "$XDG_CONFIG_HOME"
cd "$srcdir/rmcl-${pkgver}"
cargo test --release --locked
}
+56 -3
View File
@@ -39,9 +39,27 @@ impl AccountStore {
pub fn load() -> Self {
let path = account_store_path();
let accounts = match std::fs::read_to_string(&path) {
Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
Err(_) => Vec::new(),
Ok(content) => match serde_json::from_str(&content) {
Ok(accounts) => accounts,
Err(e) => {
tracing::warn!("Failed to parse accounts file {}: {}", path.display(), e);
Vec::new()
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::debug!("No accounts file at {}", path.display());
Vec::new()
}
Err(e) => {
tracing::warn!("Failed to read accounts file {}: {}", path.display(), e);
Vec::new()
}
};
tracing::debug!(
"Loaded {} account(s) from {}",
accounts.len(),
path.display()
);
Self { accounts, path }
}
@@ -55,7 +73,17 @@ impl AccountStore {
match serde_json::to_string_pretty(&self.accounts) {
Ok(json) => {
if let Err(e) = std::fs::write(&self.path, json) {
tracing::error!("Failed to write accounts file: {}", e);
tracing::error!(
"Failed to write accounts file {}: {}",
self.path.display(),
e
);
} else {
tracing::debug!(
"Saved {} account(s) to {}",
self.accounts.len(),
self.path.display()
);
}
}
Err(e) => tracing::error!("Failed to serialize accounts: {}", e),
@@ -73,9 +101,18 @@ impl AccountStore {
}
pub fn set_active(&mut self, index: usize) {
let username = self
.accounts
.get(index)
.map(|account| account.username.clone());
for (i, acc) in self.accounts.iter_mut().enumerate() {
acc.active = i == index;
}
if let Some(username) = username {
tracing::info!("Selected account '{}'", username);
} else {
tracing::warn!("Tried to select missing account index {}", index);
}
self.save();
}
@@ -83,22 +120,38 @@ impl AccountStore {
// first account added auto-becomes active so there's always a selection.
pub fn add(&mut self, account: Account) {
let uuid = &account.uuid;
let replaced = self.accounts.iter().any(|a| a.uuid == *uuid);
let account_type = account.account_type.clone();
let username = account.username.clone();
self.accounts.retain(|a| a.uuid != *uuid);
let mut account = account;
if self.accounts.is_empty() {
account.active = true;
}
self.accounts.push(account);
tracing::info!(
"{} {:?} account '{}'",
if replaced { "Updated" } else { "Added" },
account_type,
username
);
self.save();
}
pub fn remove(&mut self, index: usize) {
if index >= self.accounts.len() {
tracing::warn!("Tried to remove missing account index {}", index);
return;
}
let account = self.accounts.remove(index);
tracing::info!(
"Removed {:?} account '{}'",
account.account_type,
account.username
);
if account.active && !self.accounts.is_empty() {
self.accounts[0].active = true;
tracing::debug!("Activated fallback account '{}'", self.accounts[0].username);
}
self.save();
}
+18 -3
View File
@@ -22,15 +22,30 @@ pub fn get_config_path() -> PathBuf {
fn ensure_config_exists() -> PathBuf {
let config_path = get_config_path().join("config.toml");
if !config_path.exists() {
if let Some(parent) = config_path.parent() {
let _ = fs::create_dir_all(parent);
if let Some(parent) = config_path.parent()
&& let Err(e) = fs::create_dir_all(parent) {
tracing::warn!(
"Failed to create config directory {}: {}",
parent.display(),
e
);
}
match fs::write(&config_path, include_str!("../../assets/config.toml")) {
Ok(()) => tracing::debug!("Wrote default config to {}", config_path.display()),
Err(e) => tracing::warn!(
"Failed to write default config to {}: {}",
config_path.display(),
e
),
}
let _ = fs::write(&config_path, include_str!("../../assets/config.toml"));
} else {
tracing::trace!("Using existing config at {}", config_path.display());
}
config_path
}
pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError> {
tracing::debug!("Loading config from {}", config_path.display());
ConfigLoader::builder()
.add_source(File::from(config_path).required(false))
.build()?
+4 -4
View File
@@ -6,11 +6,11 @@ pub mod resource_packs;
pub mod shaders;
pub mod worlds;
pub use mods::{ContentEntry, scan_mods, toggle_entry};
pub use mods::scan_one_mod;
pub use resource_packs::{scan_resource_packs, scan_one_resource_pack};
pub use shaders::{scan_shaders, scan_one_shader};
pub use worlds::{scan_worlds, scan_one_world};
pub use mods::{ContentEntry, scan_mods, toggle_entry};
pub use resource_packs::{scan_one_resource_pack, scan_resource_packs};
pub use shaders::{scan_one_shader, scan_shaders};
pub use worlds::{scan_one_world, scan_worlds};
use std::io::Read;
+25 -3
View File
@@ -153,12 +153,22 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
let file = match std::fs::File::open(jar_path) {
Ok(file) => file,
Err(_) => return (String::new(), String::new(), None),
Err(e) => {
tracing::trace!("Failed to open mod JAR {}: {}", jar_path.display(), e);
return (String::new(), String::new(), None);
}
};
let mut archive = match zip::ZipArchive::new(file) {
Ok(archive) => archive,
Err(_) => return (String::new(), String::new(), None),
Err(e) => {
tracing::trace!(
"Failed to read mod JAR as ZIP {}: {}",
jar_path.display(),
e
);
return (String::new(), String::new(), None);
}
};
// try each loader's metadata in order. if we get metadata but the
@@ -180,12 +190,23 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
read_zip_bytes(&mut archive, icon_path)
}
.or_else(|| try_fallback_icons(&mut archive));
tracing::trace!(
"Read mod metadata from {}: name='{}' icon_declared={}",
jar_path.display(),
name,
!icon_path.is_empty()
);
return (name, description, icon);
}
}
// no recognized metadata at all, try common icon paths
let icon_bytes = try_fallback_icons(&mut archive);
tracing::trace!(
"No recognized mod metadata in {}; fallback_icon={}",
jar_path.display(),
icon_bytes.is_some()
);
(String::new(), String::new(), icon_bytes)
}
@@ -742,7 +763,8 @@ description = "A neoforge mod"
fn scan_mods_prefers_neoforge_toml_over_forge_toml() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let neoforge = "[[mods]]\ndisplayName = \"NeoForge Name\"\ndescription = \"neoforge desc\"\n";
let neoforge =
"[[mods]]\ndisplayName = \"NeoForge Name\"\ndescription = \"neoforge desc\"\n";
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
make_jar(
&dir,
-1
View File
@@ -89,4 +89,3 @@ fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option<Vec<u8>>) {
(description, icon_bytes)
}
-1
View File
@@ -134,4 +134,3 @@ fn format_size(bytes: u64) -> String {
format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
}
}
+48
View File
@@ -51,6 +51,11 @@ impl MmcPack {
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let pack = parse_mmc_pack(path)?;
tracing::debug!(
"Parsed MultiMC pack {} with {} component(s)",
path.display(),
pack.components.len()
);
let game_version = pack
.game_version()
@@ -62,6 +67,15 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let name = instance_name_from_cfg(path).unwrap_or_else(|| "Imported Pack".to_string());
let (mod_count, override_count) = count_content_files(path)?;
tracing::trace!(
"MultiMC summary: name='{}' game_version={} loader={:?} loader_version={:?} mods={} overrides={}",
name,
game_version,
loader,
loader_version,
mod_count,
override_count
);
Ok(ImportSummary {
name,
@@ -81,6 +95,11 @@ pub async fn execute_import(
manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
tracing::info!(
"Importing MultiMC/Prism pack '{}' as instance '{}'",
summary.name,
name
);
progress::set_action(format!("Importing '{name}'..."));
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
@@ -99,6 +118,11 @@ pub async fn execute_import(
extract_mmc_archive(&summary.archive_path, &minecraft_dir)?;
progress::clear();
tracing::info!(
"Imported MultiMC/Prism pack '{}' as '{}'",
summary.name,
name
);
Ok(config)
}
@@ -117,8 +141,16 @@ fn extract_mmc_archive(
let prefix = find_archive_prefix(&archive);
let minecraft_prefix = format!("{prefix}.minecraft/");
tracing::debug!(
"Extracting MultiMC archive {} with prefix '{}' into {}",
archive_path.display(),
prefix,
minecraft_dir.display()
);
let total = archive.len();
let mut extracted = 0usize;
let mut dirs = 0usize;
for i in 0..total {
let mut entry = archive.by_index(i)?;
let entry_name = entry.name().to_string();
@@ -129,6 +161,7 @@ fn extract_mmc_archive(
if relative.is_empty() || entry_name.ends_with('/') {
std::fs::create_dir_all(minecraft_dir.join(relative))?;
dirs += 1;
continue;
}
@@ -142,9 +175,22 @@ fn extract_mmc_archive(
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
tracing::trace!(
"Extracting MultiMC entry {} to {} ({} bytes)",
entry_name,
dest.display(),
buf.len()
);
std::fs::write(&dest, &buf)?;
extracted += 1;
}
tracing::debug!(
"Extracted {} files and {} directories from MultiMC archive {}",
extracted,
dirs,
archive_path.display()
);
Ok(())
}
@@ -167,6 +213,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
let mut archive = zip::ZipArchive::new(file).ok()?;
let entry_name = find_entry(&archive, "instance.cfg")?;
tracing::trace!("Reading instance name from {}", entry_name);
let entry = archive.by_name(&entry_name).ok()?;
let reader = std::io::BufRead::lines(std::io::BufReader::new(entry));
@@ -174,6 +221,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
if let Some(value) = line.strip_prefix("name=") {
let name = value.trim().to_string();
if !name.is_empty() {
tracing::debug!("Read MultiMC instance name '{}' from instance.cfg", name);
return Some(name);
}
}
+43 -17
View File
@@ -33,6 +33,7 @@ pub fn parse_import_input(input: &str) -> ImportInput {
|| input.starts_with('/')
|| input.starts_with("~/")
{
tracing::debug!("Import input resolved as local file: {}", input);
return ImportInput::LocalFile(input.to_string());
}
@@ -41,7 +42,7 @@ pub fn parse_import_input(input: &str) -> ImportInput {
.or_else(|| input.strip_prefix("http://modrinth.com/modpack/"))
{
let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
return match parts.as_slice() {
let parsed = match parts.as_slice() {
[slug, "version", version_id, ..] => ImportInput::VersionId {
slug: slug.to_string(),
version_id: version_id.to_string(),
@@ -49,8 +50,11 @@ pub fn parse_import_input(input: &str) -> ImportInput {
[slug, ..] => ImportInput::ProjectSlug(slug.to_string()),
[] => ImportInput::ProjectSlug(String::new()),
};
tracing::debug!("Import input resolved as Modrinth URL: {:?}", parsed);
return parsed;
}
tracing::debug!("Import input resolved as Modrinth project slug: {}", input);
ImportInput::ProjectSlug(input.to_string())
}
@@ -70,12 +74,14 @@ pub struct ImportSummary {
// peeks inside a zip to figure out what format it is.
// checks for modrinth.index.json first, then mmc-pack.json.
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
tracing::debug!("Detecting modpack format for {}", path.display());
let file =
std::fs::File::open(path).map_err(|e| format!("Cannot open '{}': {e}", path.display()))?;
let archive =
zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP '{}': {e}", path.display()))?;
if archive.file_names().any(|n| n == "modrinth.index.json") {
tracing::debug!("Detected Modrinth .mrpack archive: {}", path.display());
return Ok(PackFormat::Mrpack);
}
@@ -84,21 +90,36 @@ pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
.file_names()
.any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json"))
{
tracing::debug!("Detected MultiMC/Prism archive: {}", path.display());
return Ok(PackFormat::Mmc);
}
tracing::warn!("Unknown modpack archive format: {}", path.display());
Err("Unknown pack format: no modrinth.index.json or mmc-pack.json found".to_string())
}
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
if !path.exists() {
tracing::warn!("Cannot import missing file {}", path.display());
return Err(format!("File not found: {}", path.display()));
}
let format = detect_format(path)?;
match format {
let summary = match format {
PackFormat::Mrpack => mrpack::build_summary(path),
PackFormat::Mmc => mmc::build_summary(path),
}
}?;
tracing::debug!(
"Built import summary for {}: name='{}' format={:?} mc={} loader={} loader_version={:?} mods={} overrides={}",
path.display(),
summary.name,
summary.format,
summary.game_version,
summary.loader,
summary.loader_version,
summary.mod_count,
summary.override_count
);
Ok(summary)
}
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
@@ -108,6 +129,7 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
.join("instance.json")
.exists()
{
tracing::trace!("Import instance name '{}' is available", candidate);
return candidate;
}
for n in 2..100 {
@@ -117,9 +139,18 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
.join("instance.json")
.exists()
{
tracing::debug!(
"Import instance name '{}' collided; using '{}'",
base,
candidate
);
return candidate;
}
}
tracing::warn!(
"Import instance name '{}' had many collisions; using fallback suffix",
base
);
format!("{base} (import)")
}
@@ -127,6 +158,12 @@ pub async fn execute_import(
summary: &ImportSummary,
manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
tracing::info!(
"Executing {:?} import '{}' from {}",
summary.format,
summary.name,
summary.archive_path.display()
);
match summary.format {
PackFormat::Mrpack => mrpack::execute_import(summary, manager).await,
PackFormat::Mmc => mmc::execute_import(summary, manager).await,
@@ -154,11 +191,7 @@ mod tests {
#[test]
fn detect_format_recognises_mrpack() {
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(
tmp.path(),
"pack.mrpack",
&[("modrinth.index.json", b"{}")],
);
let path = make_pack_zip(tmp.path(), "pack.mrpack", &[("modrinth.index.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
}
@@ -176,11 +209,7 @@ mod tests {
// mmc-pack.json one directory deep - the more common layout where
// the archive wraps everything in a named directory.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(
tmp.path(),
"pack.zip",
&[("MyPack/mmc-pack.json", b"{}")],
);
let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
}
@@ -192,10 +221,7 @@ mod tests {
let path = make_pack_zip(
tmp.path(),
"weird.zip",
&[
("modrinth.index.json", b"{}"),
("mmc-pack.json", b"{}"),
],
&[("modrinth.index.json", b"{}"), ("mmc-pack.json", b"{}")],
);
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
}
+66 -6
View File
@@ -12,6 +12,13 @@ use super::{ImportSummary, PackFormat};
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let index = crate::net::modrinth::parse_mrpack(path)?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
index.version_id,
index.files.len(),
index.dependencies.len()
);
let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies)
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
@@ -21,6 +28,13 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
let override_count = count_overrides(path).unwrap_or(0);
tracing::trace!(
".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}",
game_version,
loader,
loader_version,
override_count
);
Ok(ImportSummary {
name: index.name.clone(),
@@ -54,6 +68,11 @@ pub async fn execute_import(
manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
tracing::info!(
"Importing Modrinth pack '{}' as instance '{}'",
summary.name,
name
);
progress::set_action(format!("Importing '{name}'..."));
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
@@ -78,6 +97,7 @@ pub async fn execute_import(
extract_overrides(&summary.archive_path, &minecraft_dir)?;
progress::clear();
tracing::info!("Imported Modrinth pack '{}' as '{}'", summary.name, name);
Ok(config)
}
@@ -93,6 +113,12 @@ async fn download_mod_files(
let client = crate::net::HttpClient::new();
let total = index.files.len();
let completed = Arc::new(AtomicUsize::new(0));
tracing::debug!(
"Downloading {} file(s) from .mrpack '{}' into {}",
total,
index.name,
minecraft_dir.display()
);
progress::set_action(format!("Downloading mods... 0/{total}"));
@@ -107,6 +133,9 @@ async fn download_mod_files(
let client = client.clone();
let dest = minecraft_dir.join(&file.path);
let url = file.downloads.first().cloned().unwrap_or_default();
if url.is_empty() {
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
}
let filename = file
.path
.rsplit('/')
@@ -115,10 +144,16 @@ async fn download_mod_files(
.to_string();
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
}
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await {
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {done}/{total}"));
@@ -136,6 +171,9 @@ async fn download_mod_files(
let client = client.clone();
let dest = minecraft_dir.join(&file.path);
let url = file.downloads.first().cloned().unwrap_or_default();
if url.is_empty() {
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
}
let filename = file
.path
.rsplit('/')
@@ -144,10 +182,16 @@ async fn download_mod_files(
.to_string();
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
}
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await {
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {done}/{total}"));
@@ -175,6 +219,8 @@ fn extract_overrides(
let file = std::fs::File::open(mrpack_path)?;
let mut archive = zip::ZipArchive::new(file)?;
let mut extracted = 0usize;
let mut dirs = 0usize;
for i in 0..archive.len() {
let mut entry = archive.by_index(i)?;
@@ -191,6 +237,7 @@ fn extract_overrides(
if relative.is_empty() || entry_name.ends_with('/') {
let dir = minecraft_dir.join(relative);
std::fs::create_dir_all(dir)?;
dirs += 1;
continue;
}
@@ -201,8 +248,21 @@ fn extract_overrides(
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
tracing::trace!(
"Extracting .mrpack override {} to {} ({} bytes)",
entry_name,
dest.display(),
buf.len()
);
std::fs::write(&dest, &buf)?;
extracted += 1;
}
tracing::debug!(
"Extracted {} override files and {} directories from {}",
extracted,
dirs,
mrpack_path.display()
);
Ok(())
}
+219 -13
View File
@@ -2,6 +2,7 @@
// handles classpath assembly, auth token injection, and log capture.
// loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify).
pub(crate) mod parser;
mod patches;
use std::path::{Path, PathBuf};
@@ -27,6 +28,22 @@ pub enum LaunchError {
Json(#[from] serde_json::Error),
#[error("{0} launch is not yet supported")]
NotSupported(String),
#[error(
"This instance requires Java {required}, but rmcl is using Java {detected}: {java}"
)]
JavaTooOld {
java: String,
required: u32,
detected: u32,
},
#[error(
"This instance requires Java {required}, but rmcl could not check {java}: {reason}"
)]
JavaCheckFailed {
java: String,
required: u32,
reason: String,
},
#[error("{0}")]
Auth(String),
}
@@ -41,6 +58,68 @@ fn build_game_args(
Ok((rendered.jvm, rendered.game))
}
fn parse_java_major_version(text: &str) -> Option<u32> {
let quoted = text
.split_once('"')
.and_then(|(_, rest)| rest.split_once('"').map(|(version, _)| version));
let token = quoted.or_else(|| {
let start = text.find(|c: char| c.is_ascii_digit())?;
Some(&text[start..])
})?;
let parts: Vec<u32> = token
.split(|c: char| !c.is_ascii_digit())
.filter(|part| !part.is_empty())
.filter_map(|part| part.parse::<u32>().ok())
.collect();
match parts.as_slice() {
[1, legacy_major, ..] => Some(*legacy_major),
[major, ..] => Some(*major),
[] => None,
}
}
async fn check_java_version(java: &str, required: Option<u32>) -> Result<(), LaunchError> {
let Some(required) = required.filter(|major| *major > 0) else {
return Ok(());
};
let output = tokio::process::Command::new(java)
.arg("-version")
.output()
.await
.map_err(|e| LaunchError::JavaCheckFailed {
java: java.to_owned(),
required,
reason: e.to_string(),
})?;
let version_text = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let detected =
parse_java_major_version(&version_text).ok_or_else(|| LaunchError::JavaCheckFailed {
java: java.to_owned(),
required,
reason: format!("could not parse `java -version` output: {version_text:?}"),
})?;
if detected < required {
return Err(LaunchError::JavaTooOld {
java: java.to_owned(),
required,
detected,
});
}
Ok(())
}
// 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
@@ -333,6 +412,7 @@ pub async fn build_launch_invocation(
// so we check there first.
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
let local_lib_dir = minecraft_dir.join("libraries");
let library_directory = if has_local_libs { &local_lib_dir } else { &lib_dir };
let mut classpath: Vec<PathBuf> = Vec::new();
for lib in &merged_profile.libraries {
@@ -406,6 +486,15 @@ pub async fn build_launch_invocation(
})
.unwrap_or_else(crate::net::detect_java_path);
check_java_version(
&java,
merged_profile
.java_version
.as_ref()
.map(|version| version.major_version),
)
.await?;
let assets_root = meta_dir.join("assets");
let natives_dir = meta_dir
.join("versions")
@@ -413,7 +502,7 @@ pub async fn build_launch_invocation(
.join("natives");
let version_type = merged_profile.type_.as_deref().unwrap_or("release");
let template_ctx = TemplateContext {
library_directory: &lib_dir,
library_directory,
classpath_separator: sep,
version_name: &config.game_version,
version_type,
@@ -522,6 +611,16 @@ pub async fn launch(
};
let invocation = build_launch_invocation(config, instances_dir, meta_dir, &auth).await?;
tracing::debug!(
"[{}] Prepared launch invocation: working_dir={} classpath_entries={} jvm_args={} extra_args={} game_args={} main_class={}",
name,
invocation.working_dir.display(),
invocation.classpath.len(),
invocation.jvm_args.len(),
invocation.extra_args.len(),
invocation.game_args.len(),
invocation.main_class
);
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
crate::running::register_kill(&name, kill_tx);
@@ -562,13 +661,23 @@ pub async fn launch(
Err(e) => {
crate::running::cleanup_kill_sender(&name);
crate::running::remove(&name);
tracing::error!("[{}] Failed to spawn Minecraft process: {}", name, e);
return Err(LaunchError::Io(e));
}
};
tracing::debug!("[{}] Spawned Minecraft process", name);
crate::running::set_state(&name, crate::running::RunState::Running);
let log_file_path = crate::instance::log_files::create_log_file(instances_dir, &name);
match &log_file_path {
Some(path) => tracing::debug!(
"[{}] Writing Minecraft process log to {}",
name,
path.display()
),
None => tracing::warn!("[{}] Could not create Minecraft process log file", name),
}
let name_for_task = name.clone();
let instances_dir_owned = instances_dir.to_path_buf();
@@ -580,63 +689,120 @@ pub async fn launch(
use std::io::Write;
use std::sync::{Arc, Mutex};
use tokio::io::AsyncBufReadExt;
use tokio::sync::mpsc;
use tokio::time::{Duration, sleep};
use crate::instance::launch::parser::{LogStream, MinecraftLogParser};
let log_writer: Arc<Mutex<Option<std::fs::File>>> = Arc::new(Mutex::new(
log_file_path.and_then(|p| std::fs::File::create(p).ok()),
));
let (log_tx, mut log_rx) = mpsc::channel::<(LogStream, String)>(1024);
let parser_name = name_for_task.clone();
let parser_task = tokio::spawn(async move {
let mut parser = MinecraftLogParser::new();
let idle_flush = Duration::from_millis(150);
loop {
tokio::select! {
maybe_line = log_rx.recv() => {
match maybe_line {
Some((stream, line)) => {
for event in parser.push_line(stream, line) {
emit_parsed_instance_log(&parser_name, event);
}
}
None => break,
}
}
_ = sleep(idle_flush), if parser.has_pending() => {
if let Some(event) = parser.flush() {
emit_parsed_instance_log(&parser_name, event);
}
}
}
}
if let Some(event) = parser.flush() {
emit_parsed_instance_log(&parser_name, event);
}
});
if let Some(stdout) = child.stdout.take() {
let n = name_for_task.clone();
let w = log_writer.clone();
let tx = log_tx.clone();
let mut lines = tokio::io::BufReader::new(stdout).lines();
tokio::spawn(async move {
while let Ok(Some(line)) = lines.next_line().await {
tracing::info!(target: "mc_instance", "[{}] {}", n, line);
crate::instance_logs::push(&n, &line);
if let Ok(mut f) = w.lock()
&& let Some(f) = f.as_mut()
{
let _ = writeln!(f, "{}", line);
}
if tx.send((LogStream::Stdout, line)).await.is_err() {
break;
}
}
tracing::trace!("Minecraft stdout capture task ended");
});
}
if let Some(stderr) = child.stderr.take() {
let n = name_for_task.clone();
let w = log_writer.clone();
let tx = log_tx.clone();
let mut lines = tokio::io::BufReader::new(stderr).lines();
tokio::spawn(async move {
while let Ok(Some(line)) = lines.next_line().await {
tracing::warn!(target: "mc_instance", "[{}] {}", n, line);
crate::instance_logs::push(&n, &line);
if let Ok(mut f) = w.lock()
&& let Some(f) = f.as_mut()
{
let _ = writeln!(f, "[STDERR] {}", line);
let _ = writeln!(f, "{}", line);
}
if tx.send((LogStream::Stderr, line)).await.is_err() {
break;
}
}
tracing::trace!("Minecraft stderr capture task ended");
});
}
drop(log_tx);
// wait for either the process to exit naturally or a kill signal from the TUI
let code = tokio::select! {
let (code, killed_by_user) = tokio::select! {
_ = kill_rx => {
tracing::info!("[{}] Kill requested, terminating process", name_for_task);
let _ = child.kill().await;
let _ = child.wait().await;
None
(None, true)
}
result = child.wait() => {
result.ok().and_then(|s| s.code())
(result.ok().and_then(|s| s.code()), false)
}
};
let _ = parser_task.await;
tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
if code == Some(0) {
if code == Some(0) || killed_by_user {
crate::running::remove(&name_for_task);
tracing::debug!(
"[{}] Cleared running state after normal exit (killed_by_user={})",
name_for_task,
killed_by_user
);
} else {
crate::running::set_state(&name_for_task, crate::running::RunState::Crashed(code));
crate::tui::error_buffer::push_error(crate::tui::error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: match code {
Some(code) => {
format!("Minecraft '{name_for_task}' crashed with exit code {code}")
}
None => format!("Minecraft '{name_for_task}' crashed without an exit code"),
},
pushed_at: std::time::Instant::now(),
});
}
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
@@ -654,10 +820,47 @@ pub async fn launch(
Ok(())
}
fn emit_parsed_instance_log(
instance_name: &str,
event: crate::instance::launch::parser::ParsedLogEvent,
) {
let text = event.lines.join("\n");
match event.level {
crate::instance::launch::parser::LogLevel::Error => {
tracing::error!(target: "mc_instance", "[{}] {}", instance_name, text);
}
crate::instance::launch::parser::LogLevel::Warn => {
tracing::warn!(target: "mc_instance", "[{}] {}", instance_name, text);
}
crate::instance::launch::parser::LogLevel::Info => {
tracing::info!(target: "mc_instance", "[{}] {}", instance_name, text);
}
crate::instance::launch::parser::LogLevel::Debug => {
tracing::debug!(target: "mc_instance", "[{}] {}", instance_name, text);
}
crate::instance::launch::parser::LogLevel::Trace => {
tracing::trace!(target: "mc_instance", "[{}] {}", instance_name, text);
}
}
crate::instance_logs::push_event(instance_name, event);
}
#[cfg(test)]
mod tests {
use super::*;
#[rstest::rstest]
#[case("openjdk version \"25.0.3\" 2026-04-21", Some(25))]
#[case("openjdk version \"21.0.11\" 2026-04-21", Some(21))]
#[case("java version \"1.8.0_402\"", Some(8))]
#[case("garbage", None)]
fn parse_java_major_version_handles_common_outputs(
#[case] output: &str,
#[case] expected: Option<u32>,
) {
assert_eq!(parse_java_major_version(output), expected);
}
#[test]
fn build_game_args_renders_upstream_arguments() {
use crate::launch_profile::model::{Argument, Arguments, LaunchProfile};
@@ -817,7 +1020,10 @@ mod tests {
let result =
migrate_legacy_loader_profile_if_needed(&profile_path, &modern, &config, &instance_dir)
.await;
assert!(matches!(result, Ok(None)), "expected Ok(None), got {result:?}");
assert!(
matches!(result, Ok(None)),
"expected Ok(None), got {result:?}"
);
}
#[tokio::test]
+425
View File
@@ -0,0 +1,425 @@
// live minecraft process log parser.
//
// disk launch logs stay raw, but the tui needs enough structure to color and
// group output sanely. this parser keeps stdout/stderr as a hint, frames
// multiline java/jvm/native bursts into events, then assigns a semantic level.
use libcasr::exception::Exception;
use libcasr::java::{JavaException, JavaStacktrace};
use libcasr::stacktrace::ParseStacktrace;
use regex::Regex;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogStream {
Stdout,
Stderr,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JavaParse {
pub has_exception: bool,
pub has_stacktrace: bool,
pub stacktrace_frames: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedLogEvent {
pub level: LogLevel,
pub primary_stream: LogStream,
pub lines: Vec<String>,
pub java: Option<JavaParse>,
}
#[derive(Debug, Clone)]
struct PendingEvent {
level: LogLevel,
primary_stream: LogStream,
lines: Vec<String>,
normalized_lines: Vec<String>,
kind: EventKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EventKind {
Header,
Java,
JvmBurst,
Native,
Plain,
}
#[derive(Debug)]
pub struct MinecraftLogParser {
current: Option<PendingEvent>,
minecraft_header_re: Regex,
plain_level_re: Regex,
java_exception_re: Regex,
java_continuation_re: Regex,
jvm_burst_re: Regex,
native_header_re: Regex,
}
impl Default for MinecraftLogParser {
fn default() -> Self {
Self::new()
}
}
impl MinecraftLogParser {
pub fn new() -> Self {
Self {
// header matching stays local because this parser is in the live
// path; pulling in heavier pattern machinery would not help with
// the multiline framing problem.
minecraft_header_re: Regex::new(
r"(?i)^\s*(?:\[[^\]]+\]\s*)*\[[^/\]]+/(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\]\s*:",
)
.expect("valid minecraft header regex"),
plain_level_re: Regex::new(
r"(?i)^\s*(?:\[[^\]]+\]\s*)*(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\b\s*(?:[:\]\-])?",
)
.expect("valid plain level regex"),
java_exception_re: Regex::new(
r"(?i)^\s*(?:Exception in thread .+|Caused by: |Suppressed: )?(?:[a-z_$][\w$]*\.)+(?:[A-Z][\w$]*(?:Exception|Error)|Throwable)(?::|\b)",
)
.expect("valid java exception regex"),
java_continuation_re: Regex::new(
r"^(?:\s+at\s+.+|\s*\.\.\.\s+\d+\s+more|Caused by:\s+.+|Suppressed:\s+.+)$",
)
.expect("valid java continuation regex"),
jvm_burst_re: Regex::new(
r"(?i)^\s*(?:Error:\s+.+|Unrecognized option:\s+.+|Could not create the Java Virtual Machine\.|A fatal exception has occurred\. Program will exit\.|Invalid maximum heap size:.+)$",
)
.expect("valid jvm burst regex"),
native_header_re: Regex::new(r"^\[[A-Z]\]\s+\[[0-9:.]+\]\s+[^:]+:")
.expect("valid native header regex"),
current: None,
}
}
pub fn push_line(&mut self, stream: LogStream, line: impl Into<String>) -> Vec<ParsedLogEvent> {
let line = line.into();
// classify against ansi-stripped text, but keep the original line for
// display so the live log remains faithful to the child process.
let normalized = fast_strip_ansi::strip_ansi_string(&line).into_owned();
let analysis = self.analyze_line(stream, &normalized);
let Some(current) = &mut self.current else {
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
return Vec::new();
};
// only hard starts split events. this keeps stacktraces and native
// loader bursts together even when they arrive one line at a time.
if should_split(current.kind, analysis.kind) {
let finished = self.current.take().map(finish_event);
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
finished.into_iter().collect()
} else {
if analysis.level_priority() > current.level_priority() {
current.level = analysis.level;
}
if matches!(current.kind, EventKind::Plain)
&& !matches!(analysis.kind, EventKind::Plain)
{
current.kind = analysis.kind;
}
current.lines.push(line);
current.normalized_lines.push(normalized);
Vec::new()
}
}
pub fn flush(&mut self) -> Option<ParsedLogEvent> {
self.current.take().map(finish_event)
}
pub fn has_pending(&self) -> bool {
self.current.is_some()
}
fn analyze_line(&self, stream: LogStream, normalized: &str) -> LineAnalysis {
if let Some(level) = self.header_level(normalized) {
return LineAnalysis {
level,
kind: EventKind::Header,
};
}
if self.java_exception_re.is_match(normalized) {
return LineAnalysis {
level: LogLevel::Error,
kind: EventKind::Java,
};
}
if self.java_continuation_re.is_match(normalized) {
return LineAnalysis {
level: LogLevel::Error,
kind: EventKind::Java,
};
}
if self.jvm_burst_re.is_match(normalized) {
return LineAnalysis {
level: LogLevel::Error,
kind: EventKind::JvmBurst,
};
}
if self.native_header_re.is_match(normalized) {
return LineAnalysis {
level: native_level(normalized).unwrap_or(LogLevel::Warn),
kind: EventKind::Native,
};
}
LineAnalysis {
level: match stream {
LogStream::Stdout => LogLevel::Info,
LogStream::Stderr => LogLevel::Error,
},
kind: EventKind::Plain,
}
}
fn header_level(&self, normalized: &str) -> Option<LogLevel> {
self.minecraft_header_re
.captures(normalized)
.and_then(|caps| caps.name("level"))
.or_else(|| {
self.plain_level_re
.captures(normalized)
.and_then(|caps| caps.name("level"))
})
.and_then(|m| parse_level(m.as_str()))
}
}
#[derive(Debug, Clone, Copy)]
struct LineAnalysis {
level: LogLevel,
kind: EventKind,
}
impl LineAnalysis {
fn level_priority(self) -> u8 {
level_priority(self.level)
}
}
impl PendingEvent {
fn new(stream: LogStream, line: String, normalized: String, analysis: LineAnalysis) -> Self {
Self {
level: analysis.level,
primary_stream: stream,
lines: vec![line],
normalized_lines: vec![normalized],
kind: analysis.kind,
}
}
fn level_priority(&self) -> u8 {
level_priority(self.level)
}
}
fn should_split(current: EventKind, next: EventKind) -> bool {
match next {
EventKind::Header => true,
EventKind::Native => !matches!(current, EventKind::Native),
EventKind::JvmBurst => !matches!(current, EventKind::JvmBurst),
EventKind::Java => !matches!(current, EventKind::Java | EventKind::Header),
EventKind::Plain => false,
}
}
fn finish_event(mut event: PendingEvent) -> ParsedLogEvent {
let normalized_body = event.normalized_lines.join("\n");
// libcasr is intentionally second-stage here: first frame the multiline
// event ourselves, then ask libcasr whether the block is a java failure.
let java = parse_java(&normalized_body);
if java
.as_ref()
.is_some_and(|java| java.has_exception || java.has_stacktrace)
{
event.level = LogLevel::Error;
}
ParsedLogEvent {
level: event.level,
primary_stream: event.primary_stream,
lines: event.lines,
java,
}
}
fn parse_java(body: &str) -> Option<JavaParse> {
let stacktrace_entries = JavaStacktrace::extract_stacktrace(body).unwrap_or_default();
let parsed_stacktrace = if stacktrace_entries.is_empty() {
None
} else {
JavaStacktrace::parse_stacktrace(&stacktrace_entries).ok()
};
let has_exception = JavaException::parse_exception(body).is_some();
let has_stacktrace = parsed_stacktrace
.as_ref()
.is_some_and(|stacktrace| !stacktrace.is_empty());
if has_exception || has_stacktrace {
Some(JavaParse {
has_exception,
has_stacktrace,
stacktrace_frames: parsed_stacktrace.map_or(0, |stacktrace| stacktrace.len()),
})
} else {
None
}
}
fn parse_level(level: &str) -> Option<LogLevel> {
match level.to_ascii_uppercase().as_str() {
"TRACE" => Some(LogLevel::Trace),
"DEBUG" => Some(LogLevel::Debug),
"INFO" => Some(LogLevel::Info),
"WARN" => Some(LogLevel::Warn),
"ERROR" | "FATAL" => Some(LogLevel::Error),
_ => None,
}
}
fn native_level(line: &str) -> Option<LogLevel> {
match line.chars().nth(1)? {
'E' | 'F' => Some(LogLevel::Error),
'W' => Some(LogLevel::Warn),
'I' => Some(LogLevel::Info),
'D' => Some(LogLevel::Debug),
_ => None,
}
}
fn level_priority(level: LogLevel) -> u8 {
match level {
LogLevel::Trace => 0,
LogLevel::Debug => 1,
LogLevel::Info => 2,
LogLevel::Warn => 3,
LogLevel::Error => 4,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_all(lines: &[(LogStream, &str)]) -> Vec<ParsedLogEvent> {
let mut parser = MinecraftLogParser::new();
let mut events = Vec::new();
for (stream, line) in lines {
events.extend(parser.push_line(*stream, *line));
}
events.extend(parser.flush());
events
}
#[test]
fn classifies_minecraft_headers() {
let events = parse_all(&[
(LogStream::Stdout, "[Render thread/INFO]: hello"),
(LogStream::Stdout, "[Render thread/WARN]: careful"),
(LogStream::Stdout, "[Render thread/ERROR]: broken"),
(LogStream::Stdout, "[Render thread/DEBUG]: noisy"),
(LogStream::Stdout, "[Render thread/TRACE]: tiny"),
]);
assert_eq!(events.len(), 5);
assert_eq!(events[0].level, LogLevel::Info);
assert_eq!(events[1].level, LogLevel::Warn);
assert_eq!(events[2].level, LogLevel::Error);
assert_eq!(events[3].level, LogLevel::Debug);
assert_eq!(events[4].level, LogLevel::Trace);
}
#[test]
fn explicit_stderr_info_stays_info() {
let events = parse_all(&[(LogStream::Stderr, "[Render thread/INFO]: hello")]);
assert_eq!(events[0].level, LogLevel::Info);
}
#[test]
fn unstructured_stderr_falls_back_to_error() {
let events = parse_all(&[(LogStream::Stderr, "native library failed")]);
assert_eq!(events[0].level, LogLevel::Error);
}
#[test]
fn groups_java_stacktrace() {
let events = parse_all(&[
(
LogStream::Stderr,
"Exception in thread \"main\" java.lang.RuntimeException: boom",
),
(
LogStream::Stderr,
"\tat net.minecraft.client.Main.main(Main.java:42)",
),
(
LogStream::Stderr,
"Caused by: java.lang.IllegalStateException: bad",
),
(LogStream::Stderr, "\tat example.Mod.load(Mod.java:7)"),
(LogStream::Stdout, "[Render thread/INFO]: after"),
]);
assert_eq!(events.len(), 2);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines.len(), 4);
assert!(
events[0]
.java
.as_ref()
.is_some_and(|java| java.has_stacktrace)
);
assert_eq!(events[1].level, LogLevel::Info);
}
#[test]
fn groups_jvm_startup_failure_burst() {
let events = parse_all(&[
(LogStream::Stderr, "Unrecognized option: --bad"),
(
LogStream::Stderr,
"Could not create the Java Virtual Machine.",
),
(
LogStream::Stderr,
"A fatal exception has occurred. Program will exit.",
),
]);
assert_eq!(events.len(), 1);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines.len(), 3);
}
#[test]
fn colored_header_classifies_but_keeps_original_text() {
let line = "\u{1b}[31m[Render thread/ERROR]: red\u{1b}[0m";
let events = parse_all(&[(LogStream::Stdout, line)]);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines[0], line);
}
}
+7 -2
View File
@@ -383,8 +383,13 @@ mod tests {
#[test]
fn parse_add_opens_extracts_module_args() {
let tmp = tempfile::tempdir().unwrap();
let manifest = b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n";
let zip_path = make_zip(tmp.path(), "patches.zip", &[("META-INF/MANIFEST.MF", manifest)]);
let manifest =
b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n";
let zip_path = make_zip(
tmp.path(),
"patches.zip",
&[("META-INF/MANIFEST.MF", manifest)],
);
let args = parse_add_opens(&zip_path).expect("parsed");
assert_eq!(
args,
+28 -3
View File
@@ -5,7 +5,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, fabric as fabric_api};
@@ -26,7 +26,16 @@ impl ModLoaderInstaller for FabricInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
tracing::debug!(
"Fetching Fabric loader versions for Minecraft {}",
game_version
);
let loader_versions = fabric_api::fetch_fabric_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} Fabric loader version(s) for Minecraft {}",
loader_versions.len(),
game_version
);
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
@@ -40,15 +49,31 @@ impl ModLoaderInstaller for FabricInstaller {
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
tracing::info!(
"Installing Fabric {} for Minecraft {}",
loader_version,
game_version
);
let (profile, raw_bytes) =
fabric_api::fetch_fabric_profile_with_raw(client, game_version, loader_version).await?;
tracing::debug!(
"Fetched Fabric profile {} with {} libraries",
profile.id,
profile.libraries.len()
);
fabric_api::download_fabric_libraries(client, &profile, meta_dir).await?;
super::save_profile_bytes(
meta_dir,
&format!("fabric-{game_version}-{loader_version}.json"),
&raw_bytes,
)?;
)
.map_err(InstallerError::from)?;
tracing::debug!(
"Saved Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
Ok(())
}
}
+27 -6
View File
@@ -6,7 +6,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, forge as forge_api};
@@ -27,7 +27,14 @@ impl ModLoaderInstaller for ForgeInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
forge_api::fetch_forge_versions(client, game_version).await
tracing::debug!("Fetching Forge versions for Minecraft {}", game_version);
let versions = forge_api::fetch_forge_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} Forge version(s) for Minecraft {}",
versions.len(),
game_version
);
Ok(versions)
}
async fn install(
@@ -37,8 +44,14 @@ impl ModLoaderInstaller for ForgeInstaller {
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar");
tracing::info!(
"Installing Forge {} for Minecraft {}",
loader_version,
game_version
);
tracing::debug!("Forge installer path: {}", installer_jar.display());
forge_api::download_forge_installer(client, game_version, loader_version, &installer_jar)
.await?;
@@ -47,6 +60,7 @@ impl ModLoaderInstaller for ForgeInstaller {
if forge_api::has_legacy_install_profile(&installer_jar) {
// old forge: no --installClient support, extract directly from jar
tracing::debug!("Forge installer uses legacy install_profile.json path");
if let Err(e) = forge_api::install_forge_from_profile(
client,
&installer_jar,
@@ -65,21 +79,28 @@ impl ModLoaderInstaller for ForgeInstaller {
.effective_java_path()
.map(str::to_owned)
.unwrap_or_else(crate::net::detect_java_path);
tracing::debug!("Running Forge installer with Java {}", java_path);
if let Err(e) =
forge_api::run_forge_installer(&installer_jar, instance_dir, &java_path).await
{
let _ = tokio::fs::remove_file(&installer_jar).await;
return Err(e);
return Err(InstallError::Installer(e));
}
// extract the profile from what the installer just wrote to disk
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)?;
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)
.map_err(InstallError::Installer)?;
}
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
tracing::warn!("Failed to remove Forge installer JAR: {}", e);
}
tracing::debug!(
"Installed Forge {} for Minecraft {}",
loader_version,
game_version
);
Ok(())
}
}
@@ -89,7 +110,7 @@ fn save_forge_profile(
meta_dir: &Path,
game_version: &str,
loader_version: &str,
) -> Result<(), NetError> {
) -> Result<(), super::InstallerError> {
let version_dir_name = format!("{game_version}-forge-{loader_version}");
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
+36 -3
View File
@@ -12,10 +12,29 @@ mod vanilla;
use std::path::Path;
use async_trait::async_trait;
use thiserror::Error;
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError};
#[derive(Debug, Error)]
pub enum InstallerError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Process failed: {0}")]
ProcessFailed(String),
#[error("Profile error: {0}")]
Profile(String),
}
#[derive(Debug, Error)]
pub enum InstallError {
#[error("Download error: {0}")]
Download(#[from] NetError),
#[error("Installer error: {0}")]
Installer(#[from] InstallerError),
}
pub use vanilla::VanillaInstaller;
#[derive(Debug, Clone)]
@@ -43,7 +62,7 @@ pub trait ModLoaderInstaller: Send + Sync {
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError>;
) -> Result<(), InstallError>;
}
// writes raw profile JSON bytes to meta_dir/loader-profiles/<filename>.
@@ -71,7 +90,7 @@ pub(crate) fn save_installer_profile(
meta_dir: &Path,
version_dir_name: &str,
profile_filename: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallerError> {
let ver_json_path = instance_dir
.join(".minecraft")
.join("versions")
@@ -79,18 +98,32 @@ pub(crate) fn save_installer_profile(
.join(format!("{version_dir_name}.json"));
if !ver_json_path.exists() {
return Err(NetError::Parse(format!(
tracing::debug!(
"Installer profile JSON missing: {}",
ver_json_path.display()
);
return Err(InstallerError::Profile(format!(
"Version JSON not found at {}",
ver_json_path.display()
)));
}
tracing::debug!(
"Saving installer profile {} from {}",
profile_filename,
ver_json_path.display()
);
let raw = std::fs::read(&ver_json_path)?;
let profiles_dir = meta_dir.join("loader-profiles");
std::fs::create_dir_all(&profiles_dir)?;
let profile_path = profiles_dir.join(profile_filename);
std::fs::write(&profile_path, &raw)?;
tracing::debug!(
"Saved installer profile to {} ({} bytes)",
profile_path.display(),
raw.len()
);
Ok(())
}
+18 -6
View File
@@ -5,7 +5,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, neoforge as neoforge_api};
@@ -26,7 +26,14 @@ impl ModLoaderInstaller for NeoForgeInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
neoforge_api::fetch_neoforge_versions(client, game_version).await
tracing::debug!("Fetching NeoForge versions for Minecraft {}", game_version);
let versions = neoforge_api::fetch_neoforge_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} NeoForge version(s) for Minecraft {}",
versions.len(),
game_version
);
Ok(versions)
}
async fn install(
@@ -36,10 +43,12 @@ impl ModLoaderInstaller for NeoForgeInstaller {
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
let installer_jar = instance_dir
.join(".minecraft")
.join("neoforge-installer.jar");
tracing::info!("Installing NeoForge {}", loader_version);
tracing::debug!("NeoForge installer path: {}", installer_jar.display());
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
@@ -48,19 +57,22 @@ impl ModLoaderInstaller for NeoForgeInstaller {
.effective_java_path()
.map(str::to_owned)
.unwrap_or_else(crate::net::detect_java_path);
tracing::debug!("Running NeoForge installer with Java {}", java_path);
if let Err(e) =
neoforge_api::run_neoforge_installer(&installer_jar, instance_dir, &java_path).await
{
let _ = tokio::fs::remove_file(&installer_jar).await;
return Err(e);
return Err(InstallError::Installer(e));
}
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
tracing::warn!("Failed to remove NeoForge installer JAR: {}", e);
}
save_neoforge_profile(instance_dir, meta_dir, loader_version)?;
save_neoforge_profile(instance_dir, meta_dir, loader_version)
.map_err(InstallError::Installer)?;
tracing::debug!("Installed NeoForge {}", loader_version);
Ok(())
}
}
@@ -69,7 +81,7 @@ fn save_neoforge_profile(
instance_dir: &Path,
meta_dir: &Path,
loader_version: &str,
) -> Result<(), NetError> {
) -> Result<(), super::InstallerError> {
let version_dir_name = format!("neoforge-{loader_version}");
let profile_filename = format!("neoforge-{loader_version}.json");
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
+28 -3
View File
@@ -5,7 +5,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, quilt as quilt_api};
@@ -26,7 +26,16 @@ impl ModLoaderInstaller for QuiltInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
tracing::debug!(
"Fetching Quilt loader versions for Minecraft {}",
game_version
);
let loader_versions = quilt_api::fetch_quilt_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} Quilt loader version(s) for Minecraft {}",
loader_versions.len(),
game_version
);
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
@@ -40,15 +49,31 @@ impl ModLoaderInstaller for QuiltInstaller {
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
tracing::info!(
"Installing Quilt {} for Minecraft {}",
loader_version,
game_version
);
let (profile, raw_bytes) =
quilt_api::fetch_quilt_profile_with_raw(client, game_version, loader_version).await?;
tracing::debug!(
"Fetched Quilt profile {} with {} libraries",
profile.id,
profile.libraries.len()
);
quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?;
super::save_profile_bytes(
meta_dir,
&format!("quilt-{game_version}-{loader_version}.json"),
&raw_bytes,
)?;
)
.map_err(InstallerError::from)?;
tracing::debug!(
"Saved Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
Ok(())
}
}
+2 -2
View File
@@ -6,7 +6,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, mojang};
@@ -45,7 +45,7 @@ impl ModLoaderInstaller for VanillaInstaller {
_loader_version: &str,
_instance_dir: &Path,
_meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
Ok(())
}
}
+197 -16
View File
@@ -6,6 +6,8 @@ use std::path::PathBuf;
use chrono::Utc;
use thiserror::Error;
use crate::instance::loader::InstallError;
use crate::instance::loader::InstallerError;
use crate::instance::models::{InstanceConfig, ModLoader};
#[derive(Debug, Error)]
@@ -20,6 +22,8 @@ pub enum InstanceError {
Json(#[from] serde_json::Error),
#[error("Download error: {0}")]
Download(#[from] crate::net::NetError),
#[error("Installer error: {0}")]
InstallerError(#[from] InstallerError),
#[error("Invalid instance name: {0}")]
InvalidName(String),
}
@@ -33,11 +37,17 @@ pub struct InstanceManager {
impl InstanceManager {
pub fn new(instances_dir: impl Into<PathBuf>, meta_dir: impl Into<PathBuf>) -> Self {
InstanceManager {
let manager = InstanceManager {
instances_dir: instances_dir.into(),
meta_dir: meta_dir.into(),
client: crate::net::HttpClient::new(),
}
};
tracing::trace!(
"Created InstanceManager with instances_dir={} meta_dir={}",
manager.instances_dir.display(),
manager.meta_dir.display()
);
manager
}
pub async fn create(
@@ -51,13 +61,31 @@ impl InstanceManager {
let instance_dir = self.instances_dir.join(name);
let instance_json = instance_dir.join("instance.json");
tracing::info!(
"Creating instance '{}' (Minecraft {}, loader {}, loader_version={})",
name,
game_version,
loader,
loader_version.unwrap_or("<none>")
);
tracing::debug!("Instance directory: {}", instance_dir.display());
if instance_json.exists() {
tracing::warn!(
"Cannot create instance '{}': {} already exists",
name,
instance_json.display()
);
return Err(InstanceError::AlreadyExists(name.to_string()));
}
// leftover directory without config = botched previous creation, nuke it
if instance_dir.exists() && !instance_json.exists() {
tracing::warn!(
"Removing incomplete instance directory before recreating '{}': {}",
name,
instance_dir.display()
);
std::fs::remove_dir_all(&instance_dir)?;
}
@@ -69,7 +97,22 @@ impl InstanceManager {
// clean up on failure so there's no half-baked instance left around
if result.is_err() {
let _ = std::fs::remove_dir_all(&instance_dir);
tracing::debug!(
"Cleaning up incomplete instance '{}' after creation failed",
name
);
if let Err(cleanup_error) = std::fs::remove_dir_all(&instance_dir) {
tracing::warn!(
"Failed to clean up incomplete instance directory {}: {}",
instance_dir.display(),
cleanup_error
);
} else {
tracing::debug!(
"Cleaned up incomplete instance directory {}",
instance_dir.display()
);
}
}
result
@@ -84,14 +127,26 @@ impl InstanceManager {
instance_dir: &std::path::Path,
) -> Result<InstanceConfig, InstanceError> {
let minecraft_dir = instance_dir.join(".minecraft");
tracing::debug!(
"Preparing Minecraft directory for '{}': {}",
name,
minecraft_dir.display()
);
for subdir in &["mods", "config", "resourcepacks", "shaderpacks", "saves"] {
std::fs::create_dir_all(minecraft_dir.join(subdir))?;
let path = minecraft_dir.join(subdir);
std::fs::create_dir_all(&path)?;
tracing::trace!("Ensured instance subdirectory {}", path.display());
}
// forge insists on this file existing, even if it's empty json. thanks forge.
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
if !launcher_profiles_path.exists() {
std::fs::write(&launcher_profiles_path, "{}")?;
tracing::debug!(
"Created launcher_profiles.json for '{}': {}",
name,
launcher_profiles_path.display()
);
}
for meta_subdir in &[
@@ -101,22 +156,44 @@ impl InstanceManager {
self.meta_dir.join("assets").join("indexes"),
] {
std::fs::create_dir_all(meta_subdir)?;
tracing::trace!("Ensured metadata directory {}", meta_subdir.display());
}
tracing::debug!("Fetching Mojang version manifest for '{}'", name);
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
tracing::debug!(
"Loaded Mojang manifest with {} version(s); latest release={} snapshot={}",
manifest.versions.len(),
manifest.latest.release,
manifest.latest.snapshot
);
let version_entry = match manifest.versions.iter().find(|v| v.id == game_version) {
Some(v) => v,
Some(v) => {
tracing::debug!(
"Resolved Minecraft version '{}' as {} entry",
game_version,
v.version_type
);
v
}
None => {
return Err(InstanceError::InvalidName(format!(
"Minecraft version '{}' not found in manifest",
game_version
"Minecraft version '{}' not found in manifest with {} entries",
game_version,
manifest.versions.len()
)));
}
};
let (version_meta, raw_meta_bytes) =
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await?;
tracing::debug!(
"Fetched version meta '{}' with {} libraries and asset index {}",
version_meta.id,
version_meta.libraries.len(),
version_meta.asset_index.id
);
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
.await?;
@@ -129,10 +206,20 @@ impl InstanceManager {
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);
tracing::warn!(
"Failed to ensure meta dir {} exists: {}",
parent.display(),
e
);
}
if let Err(e) = std::fs::write(&meta_json_path, &raw_meta_bytes) {
tracing::warn!("Failed to save version meta: {}", e);
tracing::warn!(
"Failed to save version meta {}: {}",
meta_json_path.display(),
e
);
} else {
tracing::debug!("Saved version meta to {}", meta_json_path.display());
}
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
@@ -150,6 +237,12 @@ impl InstanceManager {
)));
}
};
tracing::debug!(
"Installing loader {} {} for instance '{}'",
loader,
effective_loader_version,
name
);
installer
.install(
&self.client,
@@ -158,7 +251,11 @@ impl InstanceManager {
instance_dir,
&self.meta_dir,
)
.await?;
.await
.map_err(|e| match e {
InstallError::Download(net_error) => InstanceError::Download(net_error),
InstallError::Installer(installer_error) => InstanceError::InstallerError(installer_error),
})?;
let config = InstanceConfig {
name: name.to_string(),
@@ -175,6 +272,7 @@ impl InstanceManager {
};
self.save(&config)?;
tracing::info!("Created instance '{}'", name);
crate::tui::progress::clear();
Ok(config)
@@ -183,9 +281,22 @@ impl InstanceManager {
pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
let instance_dir = self.instances_dir.join(name);
if !instance_dir.exists() {
tracing::warn!(
"Cannot delete missing instance '{}': {}",
name,
instance_dir.display()
);
return Err(InstanceError::NotFound(name.to_string()));
}
std::fs::remove_dir_all(&instance_dir)?;
tracing::info!("Deleting instance '{}' at {}", name, instance_dir.display());
if let Err(e) = std::fs::remove_dir_all(&instance_dir) {
tracing::error!(
"Failed to delete instance directory {}: {}",
instance_dir.display(),
e
);
return Err(e.into());
}
if let Err(e) = crate::instance::desktop::remove(name) {
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
}
@@ -195,22 +306,44 @@ impl InstanceManager {
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
let new_name = new_name.trim();
if new_name.is_empty() {
tracing::warn!("Cannot rename instance '{}': new name is empty", old_name);
return Err(InstanceError::InvalidName(
"Name cannot be empty".to_string(),
));
}
if old_name == new_name {
tracing::debug!("Ignoring no-op instance rename '{}'", old_name);
return Ok(());
}
let old_dir = self.instances_dir.join(old_name);
let new_dir = self.instances_dir.join(new_name);
if !old_dir.exists() {
tracing::warn!(
"Cannot rename missing instance '{}': {}",
old_name,
old_dir.display()
);
return Err(InstanceError::NotFound(old_name.to_string()));
}
if new_dir.exists() {
tracing::warn!(
"Cannot rename instance '{}' to '{}': destination exists at {}",
old_name,
new_name,
new_dir.display()
);
return Err(InstanceError::AlreadyExists(new_name.to_string()));
}
std::fs::rename(&old_dir, &new_dir)?;
tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name);
if let Err(e) = std::fs::rename(&old_dir, &new_dir) {
tracing::error!(
"Failed to rename instance directory {} to {}: {}",
old_dir.display(),
new_dir.display(),
e
);
return Err(e.into());
}
let config_path = new_dir.join("instance.json");
if let Ok(data) = std::fs::read_to_string(&config_path)
@@ -223,6 +356,11 @@ impl InstanceManager {
if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
tracing::warn!("Failed to rename desktop shortcut: {}", e);
}
} else {
tracing::warn!(
"Renamed instance directory but could not update config at {}",
config_path.display()
);
}
Ok(())
@@ -230,10 +368,15 @@ impl InstanceManager {
pub fn load_all(&self) -> Vec<InstanceConfig> {
let mut instances = vec![];
tracing::debug!("Loading instances from {}", self.instances_dir.display());
let read_dir = match std::fs::read_dir(&self.instances_dir) {
Ok(rd) => rd,
Err(e) => {
tracing::error!("Failed to read instances directory: {}", e);
tracing::error!(
"Failed to read instances directory {}: {}",
self.instances_dir.display(),
e
);
return instances;
}
};
@@ -247,6 +390,7 @@ impl InstanceManager {
};
let config_path = entry.path().join("instance.json");
if !config_path.exists() {
tracing::trace!("Skipping non-instance directory {}", entry.path().display());
continue;
}
let contents = match std::fs::read_to_string(&config_path) {
@@ -263,6 +407,7 @@ impl InstanceManager {
}
}
}
tracing::debug!("Loaded {} instance(s)", instances.len());
instances
}
@@ -271,11 +416,39 @@ impl InstanceManager {
let config_path = self.instances_dir.join(name).join("instance.json");
if !config_path.exists() {
tracing::warn!(
"Instance '{}' config is missing at {}",
name,
config_path.display()
);
return Err(InstanceError::NotFound(name.to_string()));
}
let contents = std::fs::read_to_string(&config_path)?;
Ok(serde_json::from_str::<InstanceConfig>(&contents)?)
tracing::debug!("Loading instance '{}' from {}", name, config_path.display());
let contents = match std::fs::read_to_string(&config_path) {
Ok(contents) => contents,
Err(e) => {
tracing::error!(
"Failed to read instance '{}' config {}: {}",
name,
config_path.display(),
e
);
return Err(e.into());
}
};
match serde_json::from_str::<InstanceConfig>(&contents) {
Ok(config) => Ok(config),
Err(e) => {
tracing::error!(
"Failed to parse instance '{}' config {}: {}",
name,
config_path.display(),
e
);
Err(e.into())
}
}
}
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
@@ -283,12 +456,18 @@ impl InstanceManager {
let config_path = instance_dir.join("instance.json");
let json = serde_json::to_string_pretty(instance)?;
std::fs::write(&config_path, &json)?;
tracing::debug!(
"Saved instance '{}' config to {}",
instance.name,
config_path.display()
);
Ok(())
}
pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> {
let mut config = self.load_one(name)?;
config.last_played = Some(chrono::Utc::now());
tracing::debug!("Updating last_played for '{}'", name);
self.save(&config)
}
}
@@ -468,7 +647,9 @@ mod tests {
manager.touch_last_played("ticker").expect("touch");
let reloaded = manager.load_one("ticker").unwrap();
let stamp = reloaded.last_played.expect("last_played should be Some now");
let stamp = reloaded
.last_played
.expect("last_played should be Some now");
let age = chrono::Utc::now() - stamp;
assert!(
age.num_seconds().abs() < 5,
+2 -5
View File
@@ -11,11 +11,8 @@ pub mod models;
pub mod screenshots;
pub use content::{
ContentEntry, toggle_entry,
scan_mods, scan_one_mod,
scan_resource_packs, scan_one_resource_pack,
scan_shaders, scan_one_shader,
scan_worlds, scan_one_world,
ContentEntry, scan_mods, scan_one_mod, scan_one_resource_pack, scan_one_shader, scan_one_world,
scan_resource_packs, scan_shaders, scan_worlds, toggle_entry,
};
pub use launch::LaunchError;
pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
-1
View File
@@ -45,4 +45,3 @@ pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<Screen
entries.sort_by(|a, b| b.name.cmp(&a.name));
entries
}
+36 -3
View File
@@ -6,28 +6,61 @@ use std::collections::{HashMap, VecDeque};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use crate::instance::launch::parser::{LogLevel, LogStream, ParsedLogEvent};
const MAX_LINES: usize = 2000;
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<String>>>>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiveLogLine {
pub level: LogLevel,
pub stream: LogStream,
pub text: String,
}
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<LiveLogLine>>>>;
pub static LOGS: LazyLock<LogsMap> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
pub fn push(name: &str, line: impl Into<String>) {
push_line(name, LogLevel::Info, LogStream::Stdout, line);
}
pub fn push_event(name: &str, event: ParsedLogEvent) {
for line in event.lines {
push_line(name, event.level, event.primary_stream, line);
}
}
pub fn push_line(name: &str, level: LogLevel, stream: LogStream, line: impl Into<String>) {
if let Ok(mut logs) = LOGS.lock() {
let buf = logs.entry(name.to_string()).or_insert_with(VecDeque::new);
buf.push_back(line.into());
buf.push_back(LiveLogLine {
level,
stream,
text: line.into(),
});
while buf.len() > MAX_LINES {
buf.pop_front();
}
}
}
pub fn get_all(name: &str) -> Vec<String> {
pub fn get_entries(name: &str) -> Vec<LiveLogLine> {
LOGS.lock()
.ok()
.and_then(|logs| logs.get(name).map(|buf| buf.iter().cloned().collect()))
.unwrap_or_default()
}
pub fn get_all(name: &str) -> Vec<String> {
LOGS.lock()
.ok()
.and_then(|logs| {
logs.get(name)
.map(|buf| buf.iter().map(|line| line.text.clone()).collect())
})
.unwrap_or_default()
}
pub fn clear(name: &str) {
if let Ok(mut logs) = LOGS.lock() {
logs.remove(name);
+4 -1
View File
@@ -113,7 +113,10 @@ fn os_version_matches(pattern: &str, host_version: &str) -> bool {
fn features_match(required: &FeatureSet, current: &FeatureSet) -> bool {
let pairs = [
(required.is_demo_user, current.is_demo_user),
(required.has_custom_resolution, current.has_custom_resolution),
(
required.has_custom_resolution,
current.has_custom_resolution,
),
(
required.has_quick_plays_support,
current.has_quick_plays_support,
+8 -2
View File
@@ -165,7 +165,10 @@ mod tests {
#[case::unclosed_placeholder("--prefix ${unclosed", "--prefix ${unclosed")]
#[case::dollar_without_brace("$$ literal $5 $", "$$ literal $5 $")]
#[case::multiple("${version_name}-${auth_player_name}", "1.20.1-Player")]
#[case::path("-DlibraryDirectory=${library_directory}", "-DlibraryDirectory=/m/libraries")]
#[case::path(
"-DlibraryDirectory=${library_directory}",
"-DlibraryDirectory=/m/libraries"
)]
#[case::empty_input("", "")]
fn substitute_handles(#[case] input: &str, #[case] expected: &str) {
let fx = Fixture::unix();
@@ -178,7 +181,10 @@ mod tests {
// pattern. it should NOT trigger another substitution pass.
let mut fx = Fixture::unix();
fx.user_properties = "${version_name}".to_string();
assert_eq!(substitute("${user_properties}", &fx.ctx()), "${version_name}");
assert_eq!(
substitute("${user_properties}", &fx.ctx()),
"${version_name}"
);
}
#[test]
+2
View File
@@ -4,8 +4,10 @@ async fn main() {
// Guard must stay in scope to keep the log file writer alive
let _guard = rmcl::tui::logging::init();
tracing::info!("Starting rmcl {}", env!("CARGO_PKG_VERSION"));
if let Err(e) = color_eyre::install() {
eprintln!("Failed to install color-eyre: {}", e);
tracing::warn!("Failed to install color-eyre handler: {}", e);
}
rmcl::cli_init().await
+5 -1
View File
@@ -39,7 +39,11 @@ fn rename_top_level(old: &Path, new: &Path) {
return;
}
match fs::rename(old, new) {
Ok(_) => eprintln!("rmcl migration: moved {} -> {}", old.display(), new.display()),
Ok(_) => eprintln!(
"rmcl migration: moved {} -> {}",
old.display(),
new.display()
),
Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
if let Err(e2) = copy_dir_recursive(old, new) {
eprintln!(
+28 -3
View File
@@ -56,7 +56,9 @@ pub async fn fetch_fabric_game_versions_from(
meta_base: &str,
) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", meta_base);
tracing::debug!("Fetching Fabric game versions from {}", url);
let versions: Vec<FabricGameVersion> = client.get_json(&url).await?;
tracing::debug!("Fetched {} Fabric game version(s)", versions.len());
Ok(versions
.into_iter()
@@ -80,7 +82,14 @@ pub async fn fetch_fabric_versions_from(
game_version: &str,
) -> Result<Vec<FabricLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", meta_base, game_version);
client.get_json(&url).await
tracing::debug!("Fetching Fabric loader versions for {}", game_version);
let versions: Vec<FabricLoaderVersion> = client.get_json(&url).await?;
tracing::debug!(
"Fetched {} Fabric loader version(s) for {}",
versions.len(),
game_version
);
Ok(versions)
}
pub async fn fetch_fabric_profile(
@@ -101,6 +110,11 @@ pub async fn fetch_fabric_profile_from(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json(&url).await
}
@@ -113,8 +127,7 @@ pub async fn fetch_fabric_profile_with_raw(
game_version: &str,
loader_version: &str,
) -> Result<(FabricProfile, Vec<u8>), NetError> {
fetch_fabric_profile_with_raw_from(client, FABRIC_META_BASE, game_version, loader_version)
.await
fetch_fabric_profile_with_raw_from(client, FABRIC_META_BASE, game_version, loader_version).await
}
pub async fn fetch_fabric_profile_with_raw_from(
@@ -127,6 +140,11 @@ pub async fn fetch_fabric_profile_with_raw_from(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching raw Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json_with_raw(&url, "Fabric profile").await
}
@@ -138,6 +156,11 @@ pub async fn download_fabric_libraries(
meta_dir: &Path,
) -> Result<(), NetError> {
let libraries_dir = meta_dir.join("libraries");
tracing::debug!(
"Resolving {} Fabric libraries into {}",
profile.libraries.len(),
libraries_dir.display()
);
for lib in &profile.libraries {
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
@@ -162,10 +185,12 @@ pub async fn download_fabric_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Fabric library: {}", lib.name);
tracing::trace!("Fabric library destination: {}", dest.display());
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
tracing::debug!("Fabric library resolution complete for {}", profile.id);
Ok(())
}
+74 -27
View File
@@ -7,7 +7,7 @@ use std::path::Path;
use serde::Deserialize;
use crate::instance::loader::GameVersion;
use crate::instance::loader::{GameVersion, InstallError, InstallerError};
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::{set_action, set_sub_action};
@@ -47,6 +47,11 @@ pub async fn fetch_forge_versions_from(
versions.sort();
versions.dedup();
tracing::debug!(
"Resolved {} Forge version(s) for Minecraft {} from promotions",
versions.len(),
game_version
);
Ok(versions)
}
@@ -70,6 +75,10 @@ pub async fn fetch_forge_game_versions_from(
game_versions.sort();
game_versions.dedup();
game_versions.reverse();
tracing::debug!(
"Resolved {} Forge game version(s) from promotions",
game_versions.len()
);
Ok(game_versions
.into_iter()
@@ -104,13 +113,20 @@ pub async fn download_forge_installer(
let mut last_err = None;
for slug in &slugs {
let url = format!("{}/{slug}/forge-{slug}-installer.jar", FORGE_MAVEN_BASE,);
tracing::debug!("Trying Forge installer slug '{}'", slug);
match download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
})
.await
{
Ok(()) => return Ok(()),
Err(e) => last_err = Some(e),
Ok(()) => {
tracing::debug!("Downloaded Forge installer using slug '{}'", slug);
return Ok(());
}
Err(e) => {
tracing::debug!("Forge installer slug '{}' failed: {}", slug, e);
last_err = Some(e);
}
}
}
@@ -125,7 +141,7 @@ pub async fn run_forge_installer(
installer_path: &Path,
instance_dir: &Path,
java_path: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallerError> {
use tokio::process::Command;
set_action("Running Forge installer...");
@@ -140,7 +156,13 @@ pub async fn run_forge_installer(
{
Ok(o) => o,
Err(e) => {
return Err(NetError::Io(e));
tracing::debug!(
"Failed to spawn Forge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(InstallerError::Io(e));
}
};
@@ -151,9 +173,16 @@ pub async fn run_forge_installer(
} else {
stderr.lines().last().unwrap_or("unknown error").to_string()
};
return Err(NetError::InstallerFailed(detail));
tracing::debug!(
"Forge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(InstallerError::ProcessFailed(detail));
}
tracing::debug!("Forge installer completed successfully");
Ok(())
}
@@ -186,68 +215,83 @@ pub(crate) async fn install_forge_from_profile(
installer_path: &Path,
meta_dir: &Path,
profile_filename: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
use std::io::Read;
set_action("Installing legacy Forge from profile...");
tracing::debug!(
"Installing legacy Forge from {} into {}",
installer_path.display(),
meta_dir.display()
);
let file = std::fs::File::open(installer_path)?;
let file = std::fs::File::open(installer_path)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
let mut archive = zip::ZipArchive::new(file)
.map_err(|e| NetError::Parse(format!("Failed to open installer as ZIP: {e}")))?;
.map_err(|e| InstallError::Installer(InstallerError::Profile(format!("Failed to open installer as ZIP: {e}"))))?;
let profile_data: serde_json::Value = {
let entry = archive.by_name("install_profile.json").map_err(|e| {
NetError::Parse(format!("install_profile.json not found in installer: {e}"))
InstallError::Installer(InstallerError::Profile(format!("install_profile.json not found in installer: {e}")))
})?;
serde_json::from_reader(entry)
.map_err(|e| NetError::Parse(format!("Failed to parse install_profile.json: {e}")))?
.map_err(|e| InstallError::Installer(InstallerError::Profile(format!("Failed to parse install_profile.json: {e}"))))?
};
let version_info = profile_data
.get("versionInfo")
.ok_or_else(|| NetError::Parse("install_profile.json missing versionInfo".into()))?;
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("install_profile.json missing versionInfo".into())))?;
let install_info = profile_data
.get("install")
.ok_or_else(|| NetError::Parse("install_profile.json missing install section".into()))?;
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("install_profile.json missing install section".into())))?;
let libraries = version_info
.get("libraries")
.and_then(|v| v.as_array())
.ok_or_else(|| NetError::Parse("missing versionInfo.libraries".into()))?;
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("missing versionInfo.libraries".into())))?;
let file_path = install_info
.get("filePath")
.and_then(|v| v.as_str())
.ok_or_else(|| NetError::Parse("missing install.filePath".into()))?;
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("missing install.filePath".into())))?;
let install_path_coord = install_info
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| NetError::Parse("missing install.path".into()))?;
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("missing install.path".into())))?;
// extract the universal jar to the correct maven location
let universal_maven_path =
crate::net::maven_coord_to_path(install_path_coord).ok_or_else(|| {
NetError::Parse(format!(
InstallError::Installer(InstallerError::Profile(format!(
"Invalid maven coord in install.path: {install_path_coord}"
))
)))
})?;
set_sub_action("Extracting universal JAR...");
let universal_dest = meta_dir.join("libraries").join(&universal_maven_path);
if let Some(parent) = universal_dest.parent() {
std::fs::create_dir_all(parent)?;
std::fs::create_dir_all(parent)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
}
{
let mut entry = archive.by_name(file_path).map_err(|e| {
NetError::Parse(format!(
InstallError::Installer(InstallerError::Profile(format!(
"Universal JAR '{file_path}' not found in installer: {e}"
))
)))
})?;
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
std::fs::write(&universal_dest, &buf)?;
entry
.read_to_end(&mut buf)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
std::fs::write(&universal_dest, &buf)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
tracing::debug!(
"Extracted legacy Forge universal JAR to {} ({} bytes)",
universal_dest.display(),
buf.len()
);
}
// download libraries needed by this forge version. libs with a url field
@@ -256,17 +300,18 @@ pub(crate) async fn install_forge_from_profile(
// in mojang's modern version metadata, so we fetch those too.
let libraries_dir = meta_dir.join("libraries");
for lib in libraries {
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
let maven_path = match crate::net::maven_coord_to_path(name) {
Some(p) => p,
None => {
return Err(NetError::Parse(format!("Invalid Maven coordinate: {name}")));
return Err(InstallError::Installer(InstallerError::Profile(format!("Invalid Maven coordinate: {name}"))));
}
};
let dest = libraries_dir.join(&maven_path);
if dest.exists() {
tracing::trace!("Legacy Forge library already cached: {}", name);
continue;
}
@@ -278,6 +323,7 @@ pub(crate) async fn install_forge_from_profile(
let download_url = format!("{base_url}/{maven_path}");
set_sub_action(name);
tracing::debug!("Downloading legacy Forge library {}", name);
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
@@ -296,8 +342,9 @@ pub(crate) async fn install_forge_from_profile(
// the source is a serde_json::Value (which doesn't preserve order),
// but no field is silently dropped.
let serialized = serde_json::to_vec(version_info)
.map_err(|e| NetError::Parse(format!("Failed to serialize Forge profile: {e}")))?;
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)?;
.map_err(|e| InstallError::Installer(InstallerError::Profile(format!("Failed to serialize Forge profile: {e}"))))?;
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
Ok(())
}
+77 -41
View File
@@ -23,8 +23,6 @@ pub enum NetError {
Parse(String),
#[error("Server returned error status {status}: {url}")]
StatusError { status: u16, url: String },
#[error("Installer process failed: {0}")]
InstallerFailed(String),
#[error("Task failed: {0}")]
TaskFailed(String),
}
@@ -42,14 +40,19 @@ impl Default for HttpClient {
impl HttpClient {
pub fn new() -> Self {
let user_agent = format!("rmcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION"));
let client = Client::builder()
.user_agent(format!(
"rmcl/{} (Minecraft Launcher)",
env!("CARGO_PKG_VERSION")
))
.user_agent(user_agent.clone())
.timeout(std::time::Duration::from_secs(30))
.build()
.unwrap_or_else(|_| Client::new());
.unwrap_or_else(|e| {
tracing::warn!(
"Failed to build configured HTTP client, falling back to reqwest default: {}",
e
);
Client::new()
});
tracing::trace!("Created HTTP client with user-agent '{}'", user_agent);
Self { inner: client }
}
@@ -58,13 +61,20 @@ impl HttpClient {
}
pub async fn get(&self, url: &str) -> Result<reqwest::Response, NetError> {
tracing::trace!("HTTP GET {}", url);
let response = self.inner.get(url).send().await?;
if !response.status().is_success() {
tracing::debug!(
"HTTP GET {} returned non-success status {}",
url,
response.status()
);
return Err(NetError::StatusError {
status: response.status().as_u16(),
url: url.to_string(),
});
}
tracing::trace!("HTTP GET {} succeeded with {}", url, response.status());
Ok(response)
}
@@ -90,7 +100,9 @@ impl HttpClient {
url: &str,
label: &str,
) -> Result<(T, Vec<u8>), NetError> {
tracing::debug!("Fetching {} JSON from {}", label, url);
let raw = self.get_bytes(url).await?;
tracing::trace!("Fetched {} byte(s) for {}", raw.len(), label);
let parsed: T = serde_json::from_slice(&raw)
.map_err(|e| NetError::Parse(format!("Failed to parse {label}: {e}")))?;
Ok((parsed, raw))
@@ -105,35 +117,47 @@ where
F: Fn(reqwest::Response) -> Fut,
Fut: std::future::Future<Output = Result<T, NetError>>,
{
let mut last_error = None;
for attempt in 0..=MAX_RETRIES {
if attempt > 0 {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1);
tracing::warn!(
"retrying request (attempt {}/{}): {}",
attempt + 1,
MAX_RETRIES + 1,
url
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
}
match client.get(url).await {
Ok(resp) => match decode(resp).await {
Ok(value) => return Ok(value),
Err(e) if is_retryable(&e) => last_error = Some(e),
Err(e) if is_retryable(&e) => {
if attempt == MAX_RETRIES {
return Err(e);
}
sleep_before_retry("request", url, attempt, &e).await;
}
Err(e) => return Err(e),
},
Err(e) if is_retryable(&e) => last_error = Some(e),
Err(e) if is_retryable(&e) => {
if attempt == MAX_RETRIES {
return Err(e);
}
sleep_before_retry("request", url, attempt, &e).await;
}
Err(e) => return Err(e),
}
}
Err(last_error.unwrap())
unreachable!("retry loop returns on success or final error")
}
const MAX_RETRIES: u32 = 3;
const RETRY_BASE_DELAY_MS: u64 = 500;
async fn sleep_before_retry(kind: &str, url: &str, attempt: u32, err: &NetError) {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt);
tracing::warn!(
"{} failed, retrying after {}ms (attempt {}/{}): {}: {}",
kind,
delay,
attempt + 2,
MAX_RETRIES + 1,
url,
err
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
}
// streams a file to disk in chunks, calling progress_cb(downloaded, total) along the way.
// total will be 0 if the server doesn't send content-length, so callers
// should handle that gracefully. retries transient failures with exponential backoff.
@@ -143,30 +167,25 @@ pub async fn download_file(
dest: &Path,
progress_cb: impl Fn(u64, u64),
) -> Result<(), NetError> {
let mut last_error = None;
tracing::debug!("Downloading {} to {}", url, dest.display());
for attempt in 0..=MAX_RETRIES {
if attempt > 0 {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1);
tracing::warn!(
"retrying download (attempt {}/{}): {}",
attempt + 1,
MAX_RETRIES + 1,
url
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
}
match download_file_once(client, url, dest, &progress_cb).await {
Ok(()) => return Ok(()),
Ok(()) => {
tracing::debug!("Downloaded {} to {}", url, dest.display());
return Ok(());
}
Err(e) if is_retryable(&e) => {
last_error = Some(e);
if attempt == MAX_RETRIES {
return Err(e);
}
sleep_before_retry("download", url, attempt, &e).await;
}
Err(e) => return Err(e),
}
}
Err(last_error.unwrap())
unreachable!("retry loop returns on success or final error")
}
// single attempt at downloading a file to disk
@@ -180,6 +199,7 @@ async fn download_file_once(
let response = client.get(url).await?;
let total = response.content_length().unwrap_or(0);
tracing::trace!("Download content length for {}: {}", url, total);
if let Some(parent) = dest.parent() {
tokio::fs::create_dir_all(parent).await?;
@@ -194,6 +214,7 @@ async fn download_file_once(
downloaded += chunk.len() as u64;
progress_cb(downloaded, total);
}
file.flush().await?;
Ok(())
}
@@ -217,12 +238,28 @@ pub fn detect_java_path() -> String {
let java_name = if cfg!(windows) { "java.exe" } else { "java" };
let bin = std::path::Path::new(&java_home).join("bin").join(java_name);
if bin.exists() {
tracing::debug!("Detected Java from JAVA_HOME: {}", bin.display());
return bin.to_string_lossy().to_string();
}
tracing::warn!(
"JAVA_HOME is set to {}, but {} does not exist",
java_home,
bin.display()
);
}
match which::which("java") {
Ok(path) => {
tracing::debug!("Detected Java from PATH: {}", path.display());
path.to_string_lossy().to_string()
}
Err(e) => {
tracing::warn!(
"Could not find java on PATH, falling back to literal 'java': {}",
e
);
"java".to_string()
}
}
which::which("java")
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| "java".to_string())
}
// converts maven coordinates like "org.example:artifact:1.0" into a
@@ -297,5 +334,4 @@ mod tests {
fn maven_empty_string() {
assert_eq!(maven_coord_to_path(""), None);
}
}
+56 -5
View File
@@ -66,9 +66,16 @@ pub fn loader_from_dependencies(
];
for (key, loader) in &loaders {
if let Some(version) = deps.get(*key) {
tracing::trace!(
"Resolved Modrinth loader dependency {}={} as {}",
key,
version,
loader
);
return (Some(*loader), Some(version.clone()));
}
}
tracing::trace!("No Modrinth loader dependency found; treating pack as vanilla");
(None, None)
}
@@ -101,7 +108,14 @@ pub async fn fetch_project(
slug_or_id: &str,
) -> Result<ProjectInfo, crate::net::NetError> {
let url = format!("{}/project/{}", API_BASE, url_encode(slug_or_id));
client.get_json(&url).await
tracing::debug!("Fetching Modrinth project '{}'", slug_or_id);
let project: ProjectInfo = client.get_json(&url).await?;
tracing::debug!(
"Fetched Modrinth project '{}' ({})",
project.slug,
project.id
);
Ok(project)
}
pub async fn fetch_versions(
@@ -113,7 +127,14 @@ pub async fn fetch_versions(
API_BASE,
url_encode(slug_or_id)
);
client.get_json(&url).await
tracing::debug!("Fetching Modrinth versions for project '{}'", slug_or_id);
let versions: Vec<VersionInfo> = client.get_json(&url).await?;
tracing::debug!(
"Fetched {} Modrinth version(s) for project '{}'",
versions.len(),
slug_or_id
);
Ok(versions)
}
pub async fn fetch_version(
@@ -121,7 +142,15 @@ pub async fn fetch_version(
version_id: &str,
) -> Result<VersionInfo, crate::net::NetError> {
let url = format!("{}/version/{}", API_BASE, url_encode(version_id));
client.get_json(&url).await
tracing::debug!("Fetching Modrinth version '{}'", version_id);
let version: VersionInfo = client.get_json(&url).await?;
tracing::debug!(
"Fetched Modrinth version '{}' ({}) with {} file(s)",
version.name,
version.id,
version.files.len()
);
Ok(version)
}
// grabs the primary file from a version, falling back to the first file
@@ -135,22 +164,44 @@ pub async fn download_mrpack(
.files
.iter()
.find(|f| f.primary)
.or_else(|| version.files.first())
.or_else(|| {
tracing::warn!(
"Modrinth version '{}' has no primary file; using first file",
version.id
);
version.files.first()
})
.ok_or_else(|| crate::net::NetError::Parse("No files in version".to_string()))?;
let mrpack_path = dest.join(&file.filename);
tracing::info!(
"Downloading Modrinth pack file '{}' for version '{}' to {}",
file.filename,
version.id,
mrpack_path.display()
);
crate::net::download_file(client, &file.url, &mrpack_path, |_, _| {}).await?;
Ok(mrpack_path)
}
// .mrpack is just a zip with modrinth.index.json at the root
pub fn parse_mrpack(path: &std::path::Path) -> Result<MrpackIndex, String> {
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
let entry = archive
.by_name("modrinth.index.json")
.map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?;
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))
let index: MrpackIndex =
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
index.version_id,
index.files.len(),
index.dependencies.len()
);
Ok(index)
}
#[cfg(test)]
+71 -9
View File
@@ -120,7 +120,15 @@ pub async fn fetch_version_manifest_from(
client: &HttpClient,
url: &str,
) -> Result<VersionManifest, NetError> {
client.get_json(url).await
tracing::debug!("Fetching Mojang version manifest from {}", url);
let manifest: VersionManifest = client.get_json(url).await?;
tracing::debug!(
"Fetched Mojang manifest with {} version(s); latest release={} snapshot={}",
manifest.versions.len(),
manifest.latest.release,
manifest.latest.snapshot
);
Ok(manifest)
}
// fetches and parses a version's metadata. also returns the raw response
@@ -131,6 +139,11 @@ pub async fn fetch_version_meta_with_raw(
client: &HttpClient,
entry: &VersionEntry,
) -> Result<(VersionMeta, Vec<u8>), NetError> {
tracing::debug!(
"Fetching Mojang version meta '{}' from {}",
entry.id,
entry.url
);
client.get_json_with_raw(&entry.url, "version meta").await
}
@@ -146,10 +159,16 @@ pub async fn download_client_jar(
if jar_path.exists() {
tracing::info!("Client JAR already cached: {}", meta.id);
tracing::trace!("Cached client JAR path: {}", jar_path.display());
return Ok(());
}
set_action(format!("Downloading Minecraft {}...", meta.id));
tracing::info!(
"Downloading Minecraft client JAR {} to {}",
meta.id,
jar_path.display()
);
let result = download_file(
client,
@@ -171,6 +190,11 @@ pub async fn download_libraries(
meta_dir: &Path,
) -> Result<(), NetError> {
set_action("Downloading libraries...");
tracing::debug!(
"Resolving {} libraries for Minecraft {}",
meta.libraries.len(),
meta.id
);
let features = crate::launch_profile::rules::FeatureSet::default();
let host_os_version = crate::launch_profile::system::mojang_os_version();
@@ -186,17 +210,25 @@ pub async fn download_libraries(
if let Some(rules) = &library.rules
&& !crate::launch_profile::rules::evaluate(rules, &rule_ctx)
{
tracing::trace!("Skipping library {} due to platform rules", library.name);
continue;
}
let artifact = match &library.downloads.artifact {
Some(artifact) => artifact,
None => continue,
None => {
tracing::trace!(
"Skipping library {} without artifact download",
library.name
);
continue;
}
};
let destination = meta_dir.join("libraries").join(&artifact.path);
if destination.exists() {
tracing::trace!("Library already cached: {}", artifact.path);
continue;
}
@@ -209,6 +241,7 @@ pub async fn download_libraries(
return Ok(());
}
tracing::debug!("Downloading {} missing libraries", downloads.len());
let result = run_parallel_downloads(client, downloads, false).await;
clear();
result
@@ -231,6 +264,11 @@ pub async fn download_assets_from(
assets_base: &str,
) -> Result<(), NetError> {
set_action("Downloading assets...");
tracing::debug!(
"Fetching asset index {} from {}",
meta.asset_index.id,
meta.asset_index.url
);
let asset_index: AssetIndexContent = match client.get_json(&meta.asset_index.url).await {
Ok(index) => index,
@@ -251,19 +289,25 @@ pub async fn download_assets_from(
match tokio::fs::create_dir_all(parent).await {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create asset index dir: {}", e);
tracing::debug!("Failed to create asset index dir: {}", e);
}
}
}
match tokio::fs::write(&index_path, json).await {
Ok(_) => {}
Ok(_) => {
tracing::debug!("Saved asset index to {}", index_path.display());
}
Err(e) => {
tracing::error!("Failed to write asset index: {}", e);
tracing::debug!(
"Failed to write asset index {}: {}",
index_path.display(),
e
);
}
}
}
Err(e) => {
tracing::error!("Failed to serialize asset index: {}", e);
tracing::debug!("Failed to serialize asset index: {}", e);
}
}
}
@@ -301,6 +345,11 @@ pub async fn download_assets_from(
return Ok(());
}
tracing::debug!(
"Downloading {} missing asset(s) from index {}",
downloads.len(),
meta.asset_index.id
);
let result = run_parallel_downloads(client, downloads, true).await;
clear();
result
@@ -315,6 +364,11 @@ async fn run_parallel_downloads(
report_count_progress: bool,
) -> Result<(), NetError> {
let total_downloads = downloads.len() as u64;
tracing::debug!(
"Starting {} parallel download job(s), max_concurrent={}",
total_downloads,
MAX_CONCURRENT_DOWNLOADS
);
let completed = Arc::new(AtomicU64::new(0));
let mut queue = downloads.into_iter();
let mut set = JoinSet::new();
@@ -340,13 +394,13 @@ async fn run_parallel_downloads(
set_sub_action(label);
}
Ok(Err(e)) => {
tracing::error!("Download failed: {}", e);
tracing::debug!("Download failed: {}", e);
if first_error.is_none() {
first_error = Some(e);
}
}
Err(e) => {
tracing::error!("Task panicked: {}", e);
tracing::debug!("Task panicked: {}", e);
if first_error.is_none() {
first_error = Some(NetError::TaskFailed(format!("Join error: {}", e)));
}
@@ -376,8 +430,16 @@ fn spawn_download_task(
let task_client = client.clone();
set.spawn(async move {
tracing::trace!(
"Starting parallel download '{}' to {}",
label,
destination.display()
);
let result = download_file(&task_client, &url, &destination, |_current, _total| {}).await;
result.map(|()| label)
result.map(|()| {
tracing::trace!("Finished parallel download '{}'", label);
label
})
});
}
+78 -17
View File
@@ -8,6 +8,7 @@ use std::path::Path;
use serde::Deserialize;
use crate::instance::loader::GameVersion;
use crate::instance::loader::InstallerError;
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_action;
@@ -20,8 +21,10 @@ struct NeoForgeMavenVersions {
versions: Vec<String>,
}
// neoforge dropped the "1." from minecraft versions in their scheme,
// so "1.20.4" becomes prefix "20.4." and "1.21" becomes "21.0."
// neoforge historically dropped the "1." from minecraft versions in
// their scheme, so "1.20.4" becomes prefix "20.4." and "1.21" becomes
// "21.0.". newer minecraft versions such as "26.1.2" keep their full
// version at the start of the neoforge coordinate: "26.1.2.76".
fn game_version_to_neoforge_prefix(game_version: &str) -> Option<String> {
let parts: Vec<&str> = game_version.split('.').collect();
match parts.as_slice() {
@@ -29,10 +32,45 @@ fn game_version_to_neoforge_prefix(game_version: &str) -> Option<String> {
["1", minor] => Some(format!("{}.0.", minor)),
// "1.20.4" → prefix "20.4."
["1", minor, patch] => Some(format!("{}.{}.", minor, patch)),
// "26.1.2" → prefix "26.1.2."
[major, minor, patch] if leading_u32(major).is_some_and(|major| major >= 26) => {
Some(format!("{major}.{minor}.{patch}."))
}
// "26.1" → prefix "26.1."
[major, minor] if leading_u32(major).is_some_and(|major| major >= 26) => {
Some(format!("{major}.{minor}."))
}
_ => None,
}
}
fn leading_u32(raw: &str) -> Option<u32> {
let digits: String = raw.chars().take_while(|c| c.is_ascii_digit()).collect();
if digits.is_empty() {
None
} else {
digits.parse().ok()
}
}
fn neoforge_version_to_game_version(version: &str) -> Option<String> {
let parts: Vec<&str> = version.split('.').collect();
let major = leading_u32(parts.first()?)?;
if major >= 26 {
let minor = leading_u32(parts.get(1)?)?;
let patch = leading_u32(parts.get(2)?)?;
return Some(format!("{major}.{minor}.{patch}"));
}
let minor = leading_u32(parts.get(1)?)?;
Some(if minor == 0 {
format!("1.{major}")
} else {
format!("1.{major}.{minor}")
})
}
pub async fn fetch_neoforge_versions(
client: &HttpClient,
game_version: &str,
@@ -64,6 +102,12 @@ pub async fn fetch_neoforge_versions_from(
.filter(|v| v.starts_with(&prefix) && !v.contains("-beta") && !v.contains("-alpha"))
.collect();
tracing::debug!(
"Resolved {} NeoForge version(s) for Minecraft {} with prefix {}",
versions.len(),
game_version,
prefix
);
Ok(versions)
}
@@ -83,22 +127,14 @@ pub async fn fetch_neoforge_game_versions_from(
let mut game_versions: Vec<String> = Vec::new();
for version in &maven.versions {
let parts: Vec<&str> = version.split('.').collect();
if parts.len() >= 2
&& let (Ok(major), Ok(minor)) = (parts[0].parse::<u32>(), parts[1].parse::<u32>())
if let Some(mc_version) = neoforge_version_to_game_version(version)
&& !game_versions.contains(&mc_version)
{
let mc_version = if minor == 0 {
format!("1.{}", major)
} else {
format!("1.{}.{}", major, minor)
};
if !game_versions.contains(&mc_version) {
game_versions.push(mc_version);
}
game_versions.push(mc_version);
}
}
game_versions.reverse();
tracing::debug!("Resolved {} NeoForge game version(s)", game_versions.len());
Ok(game_versions
.into_iter()
@@ -120,6 +156,11 @@ pub async fn download_neoforge_installer(
);
set_action(format!("Downloading NeoForge {}...", neoforge_version));
tracing::info!(
"Downloading NeoForge installer {} to {}",
neoforge_version,
dest.display()
);
download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
@@ -131,12 +172,13 @@ pub async fn run_neoforge_installer(
installer_path: &Path,
instance_dir: &Path,
java_path: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallerError> {
use tokio::process::Command;
set_action("Running NeoForge installer...");
let output = match Command::new(java_path)
.arg(format!("-Duser.home={}", instance_dir.display()))
.arg("-jar")
.arg(installer_path)
.arg("--installClient")
@@ -146,17 +188,32 @@ pub async fn run_neoforge_installer(
{
Ok(o) => o,
Err(e) => {
return Err(NetError::Io(e));
tracing::debug!(
"Failed to spawn NeoForge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(InstallerError::Io(e));
}
};
if !output.status.success() {
return Err(NetError::InstallerFailed(format!(
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.lines().last().unwrap_or("").trim();
tracing::debug!(
"NeoForge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(InstallerError::ProcessFailed(format!(
"NeoForge installer exited with {:?}",
output.status.code()
)));
}
tracing::debug!("NeoForge installer completed successfully");
Ok(())
}
@@ -207,6 +264,10 @@ mod tests {
game_version_to_neoforge_prefix("1.21.1"),
Some("21.1.".to_string())
);
assert_eq!(
game_version_to_neoforge_prefix("26.1.2"),
Some("26.1.2.".to_string())
);
assert_eq!(game_version_to_neoforge_prefix("invalid"), None);
}
}
+27 -1
View File
@@ -52,7 +52,9 @@ pub async fn fetch_quilt_game_versions_from(
meta_base: &str,
) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", meta_base);
tracing::debug!("Fetching Quilt game versions from {}", url);
let versions: Vec<QuiltGameVersion> = client.get_json(&url).await?;
tracing::debug!("Fetched {} Quilt game version(s)", versions.len());
Ok(versions
.into_iter()
@@ -76,7 +78,14 @@ pub async fn fetch_quilt_versions_from(
game_version: &str,
) -> Result<Vec<QuiltLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", meta_base, game_version);
client.get_json(&url).await
tracing::debug!("Fetching Quilt loader versions for {}", game_version);
let versions: Vec<QuiltLoaderVersion> = client.get_json(&url).await?;
tracing::debug!(
"Fetched {} Quilt loader version(s) for {}",
versions.len(),
game_version
);
Ok(versions)
}
pub async fn fetch_quilt_profile(
@@ -97,6 +106,11 @@ pub async fn fetch_quilt_profile_from(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json(&url).await
}
@@ -122,6 +136,11 @@ pub async fn fetch_quilt_profile_with_raw_from(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching raw Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json_with_raw(&url, "Quilt profile").await
}
@@ -131,6 +150,11 @@ pub async fn download_quilt_libraries(
meta_dir: &Path,
) -> Result<(), NetError> {
let libraries_dir = meta_dir.join("libraries");
tracing::debug!(
"Resolving {} Quilt libraries into {}",
profile.libraries.len(),
libraries_dir.display()
);
for lib in &profile.libraries {
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
@@ -155,10 +179,12 @@ pub async fn download_quilt_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Quilt library: {}", lib.name);
tracing::trace!("Quilt library destination: {}", dest.display());
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
tracing::debug!("Quilt library resolution complete for {}", profile.id);
Ok(())
}
-1
View File
@@ -254,7 +254,6 @@ impl App {
let instance = match self.instance_manager.load_one(&instance.name) {
Ok(config) => config,
Err(e) => {
tracing::error!("Failed to load instance '{}': {}", instance.name, e);
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
+11 -23
View File
@@ -71,16 +71,10 @@ impl App {
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
match self.instance_manager.delete(&name) {
Ok(_) => {
self.instances_state.remove_instance(&name);
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
}
if !name.is_empty()
&& let Ok(_) = self.instance_manager.delete(&name) {
self.instances_state.remove_instance(&name);
}
}
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
return Ok(());
@@ -192,21 +186,15 @@ impl App {
let new_name = self.instances_state.renaming.take().unwrap_or_default();
if let Some(inst) = self.instances_state.selected_instance() {
let old_name = inst.name.clone();
match self.instance_manager.rename(&old_name, &new_name) {
Ok(()) => {
if let Some(inst) = self
.instances_state
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_owned();
}
if let Ok(()) = self.instance_manager.rename(&old_name, &new_name)
&& let Some(inst) = self
.instances_state
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_owned();
}
Err(e) => {
tracing::error!("Rename failed: {}", e);
}
}
}
}
KeyCode::Esc => {
+37 -8
View File
@@ -8,6 +8,7 @@ use std::sync::{Arc, Mutex};
use tracing::field::{Field, Visit};
use tracing::{Level, Subscriber};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::filter::filter_fn;
use tracing_subscriber::layer::Context;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{EnvFilter, Layer};
@@ -16,6 +17,9 @@ use std::sync::LazyLock;
use crate::tui::error_buffer::{self, ErrorEvent};
const MINECRAFT_LOG_TARGET: &str = "mc_instance";
const DEFAULT_FILE_FILTER: &str = "warn,rmcl=trace";
// capped at 5000 lines so it doesn't eat all the ram if something goes haywire
static APP_LOG_LINES: LazyLock<Arc<Mutex<Vec<String>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
@@ -58,10 +62,10 @@ pub fn init() -> WorkerGuard {
let file_appender = tracing_appender::rolling::never(&log_dir, format!("rmcl_{now}.log"));
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let env_filter = EnvFilter::builder()
.with_default_directive(Level::INFO.into())
.from_env_lossy()
.add_directive("mc_instance=off".parse().unwrap());
let file_filter =
EnvFilter::try_from_env("RUST_LOG").unwrap_or_else(|_| EnvFilter::new(DEFAULT_FILE_FILTER));
let file_filter =
file_filter.add_directive(format!("{MINECRAFT_LOG_TARGET}=off").parse().unwrap());
let rust_log = std::env::var("RUST_LOG").unwrap_or_default().to_lowercase();
let tui_level = if rust_log.contains("debug") || rust_log.contains("trace") {
@@ -83,9 +87,13 @@ pub fn init() -> WorkerGuard {
tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_ansi(false)
.with_filter(env_filter),
.with_filter(file_filter),
)
.with(
tui_logger::TuiTracingSubscriberLayer.with_filter(filter_fn(|metadata| {
should_record_app_log(metadata.target())
})),
)
.with(tui_logger::TuiTracingSubscriberLayer)
.with(StatusLayer::new(error_buffer::ERROR_EVENTS.clone()))
.init();
@@ -119,9 +127,11 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
Level::TRACE => "TRACE",
};
let now = chrono::Local::now().format("%H:%M:%S");
push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message));
if should_record_app_log(target) {
push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message));
}
if level <= Level::WARN {
if level <= Level::WARN && should_record_app_log(target) {
error_buffer::push_error(ErrorEvent {
id: 0,
level,
@@ -132,6 +142,10 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
}
}
fn should_record_app_log(target: &str) -> bool {
target != MINECRAFT_LOG_TARGET
}
#[derive(Default)]
struct MessageVisitor {
message: String,
@@ -157,3 +171,18 @@ impl Visit for MessageVisitor {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn minecraft_events_are_not_general_app_logs() {
assert!(!should_record_app_log(MINECRAFT_LOG_TARGET));
}
#[test]
fn rmcl_events_are_general_app_logs() {
assert!(should_record_app_log("rmcl::instance::manager"));
}
}
+78 -27
View File
@@ -85,16 +85,16 @@ impl ContentListState {
};
let mut received = false;
let mut received_count = 0usize;
let mut finished = false;
loop {
match rx.try_recv() {
Ok(entry) => {
received = true;
received_count += 1;
let pos = self
.entries
.binary_search_by(|e| {
e.name.to_lowercase().cmp(&entry.name.to_lowercase())
})
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
.unwrap_or_else(|i| i);
self.entries.insert(pos, entry);
}
@@ -109,6 +109,20 @@ impl ContentListState {
if received || finished {
self.loading = false;
if received_count > 0 {
tracing::trace!(
"Drained {} streamed content entries for {}",
received_count,
self.loaded_for.as_deref().unwrap_or("<unknown>")
);
}
if finished {
tracing::debug!(
"Finished content scan for {} with {} entries",
self.loaded_for.as_deref().unwrap_or("<unknown>"),
self.entries.len()
);
}
if self.list_state.selected.is_none() && !self.entries.is_empty() {
self.list_state.selected = Some(0);
}
@@ -133,6 +147,13 @@ impl ContentListState {
};
// apply toggles (enabled/path changes)
tracing::debug!(
"Applying content watcher diff for {}: toggled={} removed={} added={}",
self.loaded_for.as_deref().unwrap_or("<unknown>"),
diff.toggled.len(),
diff.removed.len(),
diff.added.len()
);
for (stem, enabled, path) in &diff.toggled {
if let Some(entry) = self.entries.iter_mut().find(|e| &e.file_stem == stem) {
entry.enabled = *enabled;
@@ -160,8 +181,7 @@ impl ContentListState {
if self.entries.is_empty() {
self.list_state.selected = None;
} else {
self.list_state.selected =
Some(sel.min(self.entries.len().saturating_sub(1)));
self.list_state.selected = Some(sel.min(self.entries.len().saturating_sub(1)));
}
}
@@ -192,7 +212,12 @@ impl ContentListState {
let watch_dir = dir.clone();
let watcher = notify::recommended_watcher(move |res: Result<notify::Event, _>| {
if res.is_err() {
if let Err(e) = &res {
tracing::warn!(
"Content watcher event error for {}: {}",
watch_dir.display(),
e
);
return;
}
@@ -235,11 +260,7 @@ impl ContentListState {
for (stem, (old_path, old_enabled)) in known_map.iter() {
if let Some((disk_path, disk_enabled)) = on_disk.get(stem) {
if *disk_enabled != *old_enabled || *disk_path != *old_path {
toggled.push((
stem.clone(),
*disk_enabled,
disk_path.clone(),
));
toggled.push((stem.clone(), *disk_enabled, disk_path.clone()));
}
} else {
removed.push(stem.clone());
@@ -281,6 +302,7 @@ impl ContentListState {
if let Err(e) = w.watch(&dir, RecursiveMode::NonRecursive) {
tracing::warn!("Failed to watch {}: {e}", dir.display());
} else {
tracing::debug!("Watching content directory {}", dir.display());
self._watcher = Some(w);
}
}
@@ -320,6 +342,11 @@ impl ContentListState {
if let Some(prev) = self.loaded_for.take()
&& !self.entries.is_empty()
{
tracing::trace!(
"Caching {} content entries for {}",
self.entries.len(),
prev
);
self.cache.insert(
prev,
CachedList {
@@ -337,6 +364,11 @@ impl ContentListState {
self.stream_rx = None;
self.loaded_for = Some(instance_name.to_string());
self.update_scrollbar();
tracing::debug!(
"Restored {} cached content entries for {}",
self.entries.len(),
instance_name
);
return;
}
@@ -351,31 +383,47 @@ impl ContentListState {
self.stream_rx = Some(rx);
let dir = content_dir.to_path_buf();
tracing::debug!(
"Starting content scan for {} in {}",
instance_name,
content_dir.display()
);
tokio::spawn(async move {
let _ = tokio::task::spawn_blocking(move || {
let read_dir = match std::fs::read_dir(&dir) {
Ok(rd) => rd,
Err(_) => return,
Err(e) => {
tracing::warn!("Failed to read content directory {}: {}", dir.display(), e);
return;
}
};
let disabled_ext = format!("{ext}.disabled");
for dir_entry in read_dir.flatten() {
let path = dir_entry.path();
let Some(fname) = path.file_name().and_then(|n| n.to_str()) else {
tracing::trace!(
"Skipping content path with invalid filename: {}",
path.display()
);
continue;
};
let (enabled, file_stem) =
if let Some(stem) = fname.strip_suffix(&disabled_ext) {
(false, stem.to_owned())
} else if let Some(stem) = fname.strip_suffix(ext) {
(true, stem.to_owned())
} else if path.is_dir() {
crate::instance::content::parse_enabled_stem_dir(fname)
} else {
continue;
};
let (enabled, file_stem) = if let Some(stem) = fname.strip_suffix(&disabled_ext)
{
(false, stem.to_owned())
} else if let Some(stem) = fname.strip_suffix(ext) {
(true, stem.to_owned())
} else if path.is_dir() {
crate::instance::content::parse_enabled_stem_dir(fname)
} else {
tracing::trace!(
"Skipping content path with unsupported extension: {}",
path.display()
);
continue;
};
let entry = scan_one_fn(&path, &file_stem, enabled);
if tx.send(entry).is_err() {
@@ -429,7 +477,13 @@ impl ContentListState {
entry.path = new_path;
}
Err(e) => {
tracing::error!("Failed to toggle '{}': {}", entry.file_stem, e);
tracing::error!(
"Failed to toggle '{}' from {} to {}: {}",
entry.file_stem,
entry.path.display(),
new_path.display(),
e
);
}
}
}
@@ -879,10 +933,7 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
// used both by watch_dir to initialize known state and by the watcher
// thread to detect changes. when ext is empty (worlds), only directories
// are included.
fn read_dir_stems(
dir: &std::path::Path,
ext: &str,
) -> HashMap<String, (std::path::PathBuf, bool)> {
fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::path::PathBuf, bool)> {
let mut map = HashMap::new();
let Ok(read_dir) = std::fs::read_dir(dir) else {
return map;
+40 -8
View File
@@ -215,8 +215,16 @@ pub fn render(
ContentTab::Mods => {
if let Some(instance) = instance {
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("mods");
mods_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_mod, ".jar");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("mods");
mods_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_mod,
".jar",
);
mods_state.watch_dir(content_dir);
}
super::list::render(
@@ -238,8 +246,16 @@ pub fn render(
ContentTab::ResourcePacks => {
if let Some(instance) = instance {
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks");
resource_packs_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_resource_pack, ".zip");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("resourcepacks");
resource_packs_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_resource_pack,
".zip",
);
resource_packs_state.watch_dir(content_dir);
}
super::list::render(
@@ -261,8 +277,16 @@ pub fn render(
ContentTab::Shaders => {
if let Some(instance) = instance {
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks");
shaders_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_shader, ".zip");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("shaderpacks");
shaders_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_shader,
".zip",
);
shaders_state.watch_dir(content_dir);
}
super::list::render(
@@ -322,8 +346,16 @@ pub fn render(
ContentTab::Worlds => {
if let Some(instance) = instance {
if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("saves");
worlds_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_world, "");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("saves");
worlds_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_world,
"",
);
worlds_state.watch_dir(content_dir);
}
super::list::render(
+45 -13
View File
@@ -17,6 +17,7 @@ use ratatui::{
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::{BORDER_STYLE, THEME};
use crate::instance::launch::parser::LogLevel;
use crate::instance::log_files::{LogFileEntry, read_log_file, scan_log_files};
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
@@ -96,12 +97,7 @@ impl LogsState {
}
pub fn drain_pending(&mut self) {
// when the instance stops while viewing the live log, transition
// to the on-disk log file so the viewer doesn't go blank
let live_now = self.has_live();
if self.was_live && !live_now && self.list_state.selected == Some(0) {
self.load_selected_content();
}
self.was_live = live_now;
let taken = match self.pending.lock() {
@@ -161,12 +157,15 @@ impl LogsState {
});
}
// when an instance is running, a synthetic "Live" entry is injected at index 0
// when an instance is active or has just crashed, a synthetic "Live" entry
// is injected at index 0 so parsed live log styling is retained.
fn has_live(&self) -> bool {
let name = self.loaded_for.as_deref().unwrap_or("");
matches!(
crate::running::get(name),
Some(crate::running::RunState::Running) | Some(crate::running::RunState::Starting)
Some(crate::running::RunState::Running)
| Some(crate::running::RunState::Starting)
| Some(crate::running::RunState::Crashed(_))
)
}
@@ -515,16 +514,27 @@ fn render_viewer(
let theme = THEME.as_ref();
let is_live = has_live && state.list_state.selected == Some(0);
let all_lines: Vec<String> = if is_live {
let all_lines: Vec<ViewerLine> = if is_live {
let name = state.loaded_for.as_deref().unwrap_or("");
crate::instance_logs::get_all(name)
crate::instance_logs::get_entries(name)
.into_iter()
.map(|line| ViewerLine {
text: line.text,
level: Some(line.level),
})
.collect()
} else {
state.viewer_lines.clone()
state
.viewer_lines
.iter()
.cloned()
.map(|text| ViewerLine { text, level: None })
.collect()
};
let lines: Vec<&String> = all_lines
let lines: Vec<&ViewerLine> = all_lines
.iter()
.filter(|l| state.viewer_search.matches(l))
.filter(|l| state.viewer_search.matches(&l.text))
.collect();
let visible_height = area.height as usize;
@@ -548,7 +558,14 @@ fn render_viewer(
.iter()
.skip(state.viewer_scroll)
.take(visible_height)
.map(|line| search.highlight_line(line, line_level_style(line)))
.map(|line| {
search.highlight_line(
&line.text,
line.level
.map(log_level_style)
.unwrap_or_else(|| line_level_style(&line.text)),
)
})
.collect();
frame.render_widget(Paragraph::new(styled_lines), area);
@@ -576,6 +593,21 @@ fn render_viewer(
);
}
struct ViewerLine {
text: String,
level: Option<LogLevel>,
}
fn log_level_style(level: LogLevel) -> Style {
let theme = THEME.as_ref();
match level {
LogLevel::Error => Style::default().fg(theme.error()),
LogLevel::Warn => Style::default().fg(theme.warning()),
LogLevel::Debug | LogLevel::Trace => Style::default().fg(theme.text_dim()),
LogLevel::Info => Style::default().fg(theme.text()),
}
}
// color-code log lines by severity so errors actually stand out
// instead of drowning in a wall of white text
fn line_level_style(line: &str) -> Style {
+1 -1
View File
@@ -9,12 +9,12 @@ use ratatui::{
pub mod account;
pub mod content;
pub mod settings;
pub mod instances;
pub mod logs_viewer;
pub mod popups;
pub mod screenshots_grid;
pub mod search;
pub mod settings;
pub mod status;
// highlight the first character of a title with the accent color,
@@ -426,11 +426,8 @@ mod tests {
id: "1.20.1".into(),
stable: true,
}]);
guard.loader_versions = LoadState::Loaded(vec![
"47.2.0".into(),
"47.1.0".into(),
"47.0.50".into(),
]);
guard.loader_versions =
LoadState::Loaded(vec!["47.2.0".into(), "47.1.0".into(), "47.0.50".into()]);
}
let backend = TestBackend::new(60, 14);
+12 -3
View File
@@ -9,7 +9,10 @@ use ratatui::{
widgets::{Block, Borders, Paragraph},
};
use crate::config::{SETTINGS, theme::{BORDER_STYLE, THEME}};
use crate::config::{
SETTINGS,
theme::{BORDER_STYLE, THEME},
};
use crate::instance::models::InstanceConfig;
use crate::tui::app::FocusedArea;
@@ -66,8 +69,14 @@ pub fn render(
.add_modifier(Modifier::BOLD);
let dim_style = Style::default().fg(theme.text_dim());
let memory_min = inst.memory_min.as_deref().unwrap_or(&SETTINGS.defaults.memory_min);
let memory_max = inst.memory_max.as_deref().unwrap_or(&SETTINGS.defaults.memory_max);
let memory_min = inst
.memory_min
.as_deref()
.unwrap_or(&SETTINGS.defaults.memory_min);
let memory_max = inst
.memory_max
.as_deref()
.unwrap_or(&SETTINGS.defaults.memory_max);
let java_path = inst
.java_path
.as_deref()
+70 -16
View File
@@ -55,6 +55,22 @@ fn make_config_with(
}
}
#[cfg(unix)]
fn fake_java(tmp: &TempDir, major: u32) -> String {
use std::os::unix::fs::PermissionsExt;
let path = tmp.path().join(format!("java-{major}"));
std::fs::write(
&path,
format!("#!/bin/sh\necho 'openjdk version \"{major}.0.1\"' >&2\n"),
)
.unwrap();
let mut permissions = std::fs::metadata(&path).unwrap().permissions();
permissions.set_mode(0o755);
std::fs::set_permissions(&path, permissions).unwrap();
path.to_string_lossy().into_owned()
}
// builds the on-disk layout that build_launch_invocation expects:
// <tmp>/instances/<name>/.minecraft/ (instance dir, created empty)
// <tmp>/meta/versions/<game_version>/meta.json
@@ -148,6 +164,16 @@ fn modern_vanilla_meta(id: &str) -> serde_json::Value {
})
}
#[cfg(unix)]
fn modern_vanilla_meta_with_java(id: &str, java_major: u32) -> serde_json::Value {
let mut meta = modern_vanilla_meta(id);
meta["javaVersion"] = json!({
"component": format!("java-runtime-{java_major}"),
"majorVersion": java_major
});
meta
}
fn legacy_vanilla_meta(id: &str) -> serde_json::Value {
json!({
"id": id,
@@ -182,14 +208,11 @@ async fn vanilla_modern_builds_complete_invocation() {
assert_eq!(inv.main_class, "net.minecraft.client.main.Main");
assert!(inv.extra_args.is_empty());
let expected_natives = fx
.meta_dir
.join("versions")
.join("1.20.1")
.join("natives");
let expected_natives = fx.meta_dir.join("versions").join("1.20.1").join("natives");
assert!(
inv.jvm_args.iter().any(|a| a
== &format!("-Djava.library.path={}", expected_natives.display())),
inv.jvm_args
.iter()
.any(|a| a == &format!("-Djava.library.path={}", expected_natives.display())),
"jvm_args missing natives substitution: {:?}",
inv.jvm_args
);
@@ -215,6 +238,34 @@ async fn vanilla_modern_builds_complete_invocation() {
assert!(inv.classpath.contains(&client_jar));
}
#[cfg(unix)]
#[tokio::test]
async fn launch_fails_when_selected_java_is_older_than_profile_requires() {
let fx = Fixture::new(
"java-old",
"26.1.2",
modern_vanilla_meta_with_java("26.1.2", 25),
);
let mut config = make_config("java-old", "26.1.2", ModLoader::Vanilla);
config.java_path = Some(fake_java(&fx._tmp, 21));
let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth())
.await
.expect_err("java 21 should fail for a Java 25 profile");
assert!(
matches!(
err,
LaunchError::JavaTooOld {
required: 25,
detected: 21,
..
}
),
"expected JavaTooOld, got {err:?}"
);
}
#[tokio::test]
async fn vanilla_legacy_args_format_substitutes_tokens() {
let fx = Fixture::new("vlegacy", "1.7.10", legacy_vanilla_meta("1.7.10"));
@@ -270,7 +321,10 @@ async fn forge_modern_includes_add_opens() {
.await
.unwrap();
assert_eq!(inv.main_class, "cpw.mods.bootstraplauncher.BootstrapLauncher");
assert_eq!(
inv.main_class,
"cpw.mods.bootstraplauncher.BootstrapLauncher"
);
assert!(
inv.jvm_args.iter().any(|a| a == "--add-opens"),
"Forge --add-opens missing: {:?}",
@@ -311,9 +365,9 @@ async fn forge_local_lib_dir_preferred_over_meta_dir() {
// drop fmlloader into the instance-local libraries dir so the launcher
// finds it there rather than under the shared meta cache.
let local_lib =
fx.instance_libraries_dir("f2")
.join("net/minecraftforge/fmlloader/1.20.1-47.2.0");
let local_lib = fx
.instance_libraries_dir("f2")
.join("net/minecraftforge/fmlloader/1.20.1-47.2.0");
std::fs::create_dir_all(&local_lib).unwrap();
let local_jar = local_lib.join("fmlloader-1.20.1-47.2.0.jar");
std::fs::write(&local_jar, b"jar").unwrap();
@@ -412,7 +466,10 @@ async fn neoforge_inheritsfrom_resolves() {
.await
.unwrap();
assert_eq!(inv.main_class, "cpw.mods.bootstraplauncher.BootstrapLauncher");
assert_eq!(
inv.main_class,
"cpw.mods.bootstraplauncher.BootstrapLauncher"
);
assert!(
inv.jvm_args
.windows(2)
@@ -527,9 +584,7 @@ async fn rule_disallow_excludes_library() {
.await
.unwrap();
let denied = fx
.meta_dir
.join("libraries/com/denied/lib/1.0/lib-1.0.jar");
let denied = fx.meta_dir.join("libraries/com/denied/lib/1.0/lib-1.0.jar");
assert!(
!inv.classpath.contains(&denied),
"denied library was included: {:?}",
@@ -680,4 +735,3 @@ async fn legacy_loader_profile_missing_installer_json_errors() {
"expected Parse error about missing installer JSON, got: {err:?}"
);
}
+42 -10
View File
@@ -130,13 +130,15 @@ async fn fabric_fetch_profile_parses_libraries() {
.mount(&server)
.await;
let profile =
fetch_fabric_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.15.0")
.await
.expect("fabric profile");
let profile = fetch_fabric_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.15.0")
.await
.expect("fabric profile");
assert_eq!(profile.id, "fabric-loader-0.15.0-1.20.1");
assert_eq!(profile.main_class, "net.fabricmc.loader.impl.launch.knot.KnotClient");
assert_eq!(
profile.main_class,
"net.fabricmc.loader.impl.launch.knot.KnotClient"
);
assert_eq!(profile.libraries.len(), 1);
assert_eq!(profile.libraries[0].url, "https://maven.fabricmc.net/");
}
@@ -192,13 +194,15 @@ async fn quilt_fetch_profile_parses_libraries() {
.mount(&server)
.await;
let profile =
fetch_quilt_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.23.0")
.await
.expect("quilt profile");
let profile = fetch_quilt_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.23.0")
.await
.expect("quilt profile");
assert_eq!(profile.id, "quilt-loader-0.23.0-1.20.1");
assert_eq!(profile.libraries[0].url, "https://maven.quiltmc.org/repository/release/");
assert_eq!(
profile.libraries[0].url,
"https://maven.quiltmc.org/repository/release/"
);
}
// ---------- neoforge ----------
@@ -229,6 +233,30 @@ async fn neoforge_fetch_versions_filters_by_prefix() {
assert_eq!(versions, vec!["20.4.190", "20.4.150"]);
}
#[tokio::test]
async fn neoforge_fetch_versions_supports_modern_minecraft_numbering() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/maven-api"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"versions": [
"26.1.2.76",
"26.1.2.75",
"26.1.1.15",
"21.1.233"
]
})))
.mount(&server)
.await;
let url = format!("{}/maven-api", server.uri());
let versions = fetch_neoforge_versions_from(&HttpClient::new(), &url, "26.1.2")
.await
.expect("neoforge versions");
assert_eq!(versions, vec!["26.1.2.76", "26.1.2.75"]);
}
#[tokio::test]
async fn neoforge_fetch_game_versions_reverse_engineers_mc_versions() {
// neoforge "21.0.x" maps back to MC 1.21 (minor=0 strips the suffix);
@@ -239,6 +267,8 @@ async fn neoforge_fetch_game_versions_reverse_engineers_mc_versions() {
.and(path("/maven-api"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"versions": [
"26.1.2.76",
"26.1.1.15",
"21.0.10",
"21.0.5",
"20.4.190",
@@ -255,6 +285,8 @@ async fn neoforge_fetch_game_versions_reverse_engineers_mc_versions() {
let ids: Vec<&str> = versions.iter().map(|v| v.id.as_str()).collect();
// dedup keeps the first occurrence, output is reversed, so the
// resulting list is in upstream maven-version order, deduped.
assert!(ids.contains(&"26.1.2"));
assert!(ids.contains(&"26.1.1"));
assert!(ids.contains(&"1.21"));
assert!(ids.contains(&"1.20.4"));
// both versions should be marked stable (no snapshot flag in maven)
+6 -5
View File
@@ -10,7 +10,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate};
use rmcl::net::HttpClient;
use rmcl::net::mojang::{
AssetIndex, Artifact, Download, JavaVersion, Library, LibraryDownloads, VersionDownloads,
Artifact, AssetIndex, Download, JavaVersion, Library, LibraryDownloads, VersionDownloads,
VersionEntry, VersionMeta, download_assets, download_assets_from, download_libraries,
fetch_version_manifest_from, fetch_version_meta_with_raw,
};
@@ -226,9 +226,7 @@ async fn download_assets_from_writes_index_and_assets() {
.await;
// asset hash starts with "ab" so the per-asset URL is /<base>/ab/<hash>.
Mock::given(method("GET"))
.and(path(
"/cdn/ab/ab1234567890abcdef1234567890abcdef123456",
))
.and(path("/cdn/ab/ab1234567890abcdef1234567890abcdef123456"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"asset-bytes".to_vec()))
.expect(1)
.mount(&server)
@@ -272,7 +270,10 @@ async fn download_assets_writes_index_when_objects_is_empty() {
.expect("download_assets index-only");
let index_path = tmp.path().join("assets/indexes/5.json");
assert!(index_path.exists(), "expected asset index at {index_path:?}");
assert!(
index_path.exists(),
"expected asset index at {index_path:?}"
);
let body: serde_json::Value =
serde_json::from_slice(&std::fs::read(&index_path).unwrap()).unwrap();
assert!(body.get("objects").is_some());