chore: improve rmcl diagnostic logging

This commit is contained in:
objz committed 2026-06-16 10:22:51 +02:00
1 parent a58e6fb76d
commit 09bc8f26fb
23 files changed
+924 -60

No files matched your search

+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 -2
View File
@@ -23,14 +23,30 @@ 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 Err(e) = fs::create_dir_all(parent) {
tracing::warn!(
"Failed to create config directory {}: {}",
parent.display(),
e
);
}
let _ = fs::write(&config_path, include_str!("../../assets/config.toml"));
}
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
),
}
} 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()?
+23 -2
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)
}
+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);
}
}
+40 -3
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,
+64 -2
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('/')
@@ -116,9 +145,16 @@ async fn download_mod_files(
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
if 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 +172,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('/')
@@ -145,9 +184,16 @@ async fn download_mod_files(
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
if 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 +221,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 +239,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 +250,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(())
}
+27
View File
@@ -523,6 +523,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);
@@ -563,13 +573,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();
@@ -636,6 +656,7 @@ pub async fn launch(
break;
}
}
tracing::trace!("Minecraft stdout capture task ended");
});
}
@@ -654,6 +675,7 @@ pub async fn launch(
break;
}
}
tracing::trace!("Minecraft stderr capture task ended");
});
}
drop(log_tx);
@@ -675,6 +697,11 @@ pub async fn launch(
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 {
+24
View File
@@ -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)
@@ -41,14 +50,29 @@ impl ModLoaderInstaller for FabricInstaller {
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
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,
)?;
tracing::debug!(
"Saved Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
Ok(())
}
}
+23 -1
View File
@@ -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(
@@ -39,6 +46,12 @@ impl ModLoaderInstaller for ForgeInstaller {
meta_dir: &Path,
) -> Result<(), NetError> {
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,
@@ -56,6 +70,7 @@ impl ModLoaderInstaller for ForgeInstaller {
.await
{
let _ = tokio::fs::remove_file(&installer_jar).await;
tracing::error!("Legacy Forge installation failed: {}", e);
return Err(e);
}
} else {
@@ -65,10 +80,12 @@ 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;
tracing::error!("Modern Forge installer failed: {}", e);
return Err(e);
}
@@ -80,6 +97,11 @@ impl ModLoaderInstaller for ForgeInstaller {
tracing::warn!("Failed to remove Forge installer JAR: {}", e);
}
tracing::debug!(
"Installed Forge {} for Minecraft {}",
loader_version,
game_version
);
Ok(())
}
}
+14
View File
@@ -79,18 +79,32 @@ pub(crate) fn save_installer_profile(
.join(format!("{version_dir_name}.json"));
if !ver_json_path.exists() {
tracing::error!(
"Installer profile JSON missing: {}",
ver_json_path.display()
);
return Err(NetError::Parse(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(())
}
+13 -1
View File
@@ -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(
@@ -40,6 +47,8 @@ impl ModLoaderInstaller for NeoForgeInstaller {
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,10 +57,12 @@ 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;
tracing::error!("NeoForge installer failed: {}", e);
return Err(e);
}
@@ -61,6 +72,7 @@ impl ModLoaderInstaller for NeoForgeInstaller {
save_neoforge_profile(instance_dir, meta_dir, loader_version)?;
tracing::debug!("Installed NeoForge {}", loader_version);
Ok(())
}
}
+24
View File
@@ -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)
@@ -41,14 +50,29 @@ impl ModLoaderInstaller for QuiltInstaller {
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
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,
)?;
tracing::debug!(
"Saved Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
Ok(())
}
}
+143 -9
View File
@@ -33,11 +33,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 +57,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)?;
}
@@ -68,8 +92,20 @@ impl InstanceManager {
.await;
// 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);
if let Err(e) = &result {
tracing::error!("Instance '{}' creation failed: {}", name, e);
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 +120,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,13 +149,33 @@ 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 => {
tracing::warn!(
"Minecraft version '{}' not found in manifest with {} entries",
game_version,
manifest.versions.len()
);
return Err(InstanceError::InvalidName(format!(
"Minecraft version '{}' not found in manifest",
game_version
@@ -117,6 +185,12 @@ impl InstanceManager {
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 +203,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 +234,12 @@ impl InstanceManager {
)));
}
};
tracing::debug!(
"Installing loader {} {} for instance '{}'",
loader,
effective_loader_version,
name
);
installer
.install(
&self.client,
@@ -175,6 +265,7 @@ impl InstanceManager {
};
self.save(&config)?;
tracing::info!("Created instance '{}'", name);
crate::tui::progress::clear();
Ok(config)
@@ -183,8 +274,14 @@ 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()));
}
tracing::info!("Deleting instance '{}' at {}", name, instance_dir.display());
std::fs::remove_dir_all(&instance_dir)?;
if let Err(e) = crate::instance::desktop::remove(name) {
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
@@ -200,16 +297,29 @@ impl InstanceManager {
));
}
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()));
}
tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name);
std::fs::rename(&old_dir, &new_dir)?;
let config_path = new_dir.join("instance.json");
@@ -223,6 +333,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 +345,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 +367,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 +384,7 @@ impl InstanceManager {
}
}
}
tracing::debug!("Loaded {} instance(s)", instances.len());
instances
}
@@ -271,9 +393,15 @@ 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()));
}
tracing::debug!("Loading instance '{}' from {}", name, config_path.display());
let contents = std::fs::read_to_string(&config_path)?;
Ok(serde_json::from_str::<InstanceConfig>(&contents)?)
}
@@ -283,12 +411,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)
}
}
+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
+27 -1
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
}
@@ -126,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
}
@@ -137,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) {
@@ -161,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(())
}
+43 -2
View File
@@ -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);
}
}
}
@@ -140,6 +156,12 @@ pub async fn run_forge_installer(
{
Ok(o) => o,
Err(e) => {
tracing::error!(
"Failed to spawn Forge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(NetError::Io(e));
}
};
@@ -151,9 +173,16 @@ pub async fn run_forge_installer(
} else {
stderr.lines().last().unwrap_or("unknown error").to_string()
};
tracing::error!(
"Forge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(NetError::InstallerFailed(detail));
}
tracing::debug!("Forge installer completed successfully");
Ok(())
}
@@ -190,6 +219,11 @@ pub(crate) async fn install_forge_from_profile(
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 mut archive = zip::ZipArchive::new(file)
@@ -248,6 +282,11 @@ pub(crate) async fn install_forge_from_profile(
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
std::fs::write(&universal_dest, &buf)?;
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
@@ -267,6 +306,7 @@ pub(crate) async fn install_forge_from_profile(
let dest = libraries_dir.join(&maven_path);
if dest.exists() {
tracing::trace!("Legacy Forge library already cached: {}", name);
continue;
}
@@ -278,6 +318,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?;
}
+57 -13
View File
@@ -42,14 +42,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 +63,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::warn!(
"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 +102,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))
@@ -110,7 +124,8 @@ where
if attempt > 0 {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1);
tracing::warn!(
"retrying request (attempt {}/{}): {}",
"retrying request after {}ms (attempt {}/{}): {}",
delay,
attempt + 1,
MAX_RETRIES + 1,
url
@@ -121,10 +136,16 @@ where
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) => {
tracing::warn!("Retryable decode/request error for {}: {}", url, e);
last_error = Some(e);
}
Err(e) => return Err(e),
},
Err(e) if is_retryable(&e) => last_error = Some(e),
Err(e) if is_retryable(&e) => {
tracing::warn!("Retryable request error for {}: {}", url, e);
last_error = Some(e);
}
Err(e) => return Err(e),
}
}
@@ -144,12 +165,14 @@ pub async fn download_file(
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 {}/{}): {}",
"retrying download after {}ms (attempt {}/{}): {}",
delay,
attempt + 1,
MAX_RETRIES + 1,
url
@@ -158,8 +181,12 @@ pub async fn download_file(
}
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) => {
tracing::warn!("Retryable download error for {}: {}", url, e);
last_error = Some(e);
}
Err(e) => return Err(e),
@@ -180,6 +207,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?;
@@ -217,12 +245,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
+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)]
+68 -5
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,
@@ -256,9 +294,15 @@ pub async fn download_assets_from(
}
}
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::error!(
"Failed to write asset index {}: {}",
index_path.display(),
e
);
}
}
}
@@ -289,6 +333,7 @@ pub async fn download_assets_from(
.join(&object.hash);
if destination.exists() {
tracing::trace!("Asset already cached: {}", object.hash);
continue;
}
@@ -301,6 +346,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 +365,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();
@@ -376,8 +431,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
})
});
}
+27
View File
@@ -64,6 +64,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)
}
@@ -99,6 +105,7 @@ pub async fn fetch_neoforge_game_versions_from(
}
}
game_versions.reverse();
tracing::debug!("Resolved {} NeoForge game version(s)", game_versions.len());
Ok(game_versions
.into_iter()
@@ -120,6 +127,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);
@@ -146,17 +158,32 @@ pub async fn run_neoforge_installer(
{
Ok(o) => o,
Err(e) => {
tracing::error!(
"Failed to spawn NeoForge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(NetError::Io(e));
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.lines().last().unwrap_or("").trim();
tracing::error!(
"NeoForge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(NetError::InstallerFailed(format!(
"NeoForge installer exited with {:?}",
output.status.code()
)));
}
tracing::debug!("NeoForge installer completed successfully");
Ok(())
}
+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(())
}
+36 -7
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");
if should_record_app_log(target) {
push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message));
}
if level <= Level::WARN && target != "mc_instance" {
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"));
}
}
+64 -3
View File
@@ -85,11 +85,13 @@ 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()))
@@ -107,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);
}
@@ -131,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;
@@ -189,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;
}
@@ -274,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);
}
}
@@ -313,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 {
@@ -330,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;
}
@@ -344,18 +383,30 @@ 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;
};
@@ -367,6 +418,10 @@ impl ContentListState {
} 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;
};
@@ -422,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
);
}
}
}