From e035f33fc037b25f3a2c8511d1e11f09c2061be7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Sat, 10 Oct 2026 08:09:50 +0500 Subject: [PATCH] style: format merged codebase and update release artifact hashes --- crates/coa-core/src/control/direct_ingress.rs | 3 +- crates/coa-core/src/crashes.rs | 64 +++- crates/coa-core/src/custom_races.rs | 161 ++++++--- crates/coa-core/src/db.rs | 8 +- crates/coa-core/src/diag.rs | 4 +- crates/coa-core/src/docker/lifecycle.rs | 44 ++- crates/coa-core/src/lib.rs | 2 +- crates/coa-core/src/modules.rs | 4 +- crates/coa-core/src/platform.rs | 10 +- crates/coa-core/src/portable/realm/export.rs | 8 +- crates/coa-core/src/realms.rs | 39 ++- crates/coa-core/src/update.rs | 27 +- crates/coa-core/src/wine.rs | 315 +++++++++++++++--- docs/RELEASE_READINESS.md | 4 +- src-tauri/src/control_cmds.rs | 7 +- src-tauri/src/docker_install.rs | 94 +++++- src-tauri/src/lib.rs | 61 +++- 17 files changed, 685 insertions(+), 170 deletions(-) diff --git a/crates/coa-core/src/control/direct_ingress.rs b/crates/coa-core/src/control/direct_ingress.rs index 0f920a8..f456c17 100644 --- a/crates/coa-core/src/control/direct_ingress.rs +++ b/crates/coa-core/src/control/direct_ingress.rs @@ -324,7 +324,7 @@ fn handle_world_client(mut client: TcpStream, local_world_port: u16) -> Result<( } done.store(true, Ordering::Relaxed); if let Some(c) = client_shutdown { - let _ = c.shutdown(std::net::Shutdown::Both); + let _ = c.shutdown(std::net::Shutdown::Write); } let _ = t_c2s.join(); @@ -363,6 +363,7 @@ mod tests { let n = stream.read(&mut buf).unwrap(); assert_eq!(&buf[..n], b"WORLD_PING"); stream.write_all(b"WORLD_PONG").unwrap(); + let _ = stream.shutdown(std::net::Shutdown::Write); }); let mut client_world = TcpStream::connect(format!("127.0.0.1:{ingress_world}")).unwrap(); diff --git a/crates/coa-core/src/crashes.rs b/crates/coa-core/src/crashes.rs index 2a94e73..7c80be7 100644 --- a/crates/coa-core/src/crashes.rs +++ b/crates/coa-core/src/crashes.rs @@ -1,10 +1,10 @@ //! Crash log discovery and human-friendly explanation for worldserver crashes. +use crate::error::Result; +use serde::{Deserialize, Serialize}; use std::fs; use std::path::{Path, PathBuf}; use std::time::SystemTime; -use serde::{Deserialize, Serialize}; -use crate::error::Result; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct CrashItem { @@ -30,7 +30,10 @@ pub fn list(root: &Path, limit: usize) -> Result> { for entry in entries.flatten() { let path = entry.path(); if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") { - let mtime = entry.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH); + let mtime = entry + .metadata() + .and_then(|m| m.modified()) + .unwrap_or(SystemTime::UNIX_EPOCH); files.push((path, mtime)); } } @@ -50,8 +53,15 @@ pub fn list(root: &Path, limit: usize) -> Result> { /// Parses crash report content and generates human-friendly titles and explanations. pub fn parse_crash_content(path: &Path, mtime: SystemTime, content: &str) -> CrashItem { - let filename = path.file_name().unwrap_or_default().to_string_lossy().into_owned(); - let timestamp_ms = mtime.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0); + let filename = path + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(); + let timestamp_ms = mtime + .duration_since(SystemTime::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); let mut date_str = String::new(); let mut exception_code = None; @@ -77,11 +87,20 @@ pub fn parse_crash_content(path: &Path, mtime: SystemTime, content: &str) -> Cra if trimmed.starts_with("# Location:") { let loc = trimmed.trim_start_matches("# Location:").trim(); let clean = loc.rsplit(['\\', '/']).take(2).collect::>(); - location = Some(if clean.len() == 2 { format!("{}/{}", clean[1], clean[0]) } else { loc.to_string() }); + location = Some(if clean.len() == 2 { + format!("{}/{}", clean[1], clean[0]) + } else { + loc.to_string() + }); } else if trimmed.starts_with("# Function:") { function = Some(trimmed.trim_start_matches("# Function:").trim().to_string()); } else if trimmed.starts_with("# Condition:") { - condition = Some(trimmed.trim_start_matches("# Condition:").trim().to_string()); + condition = Some( + trimmed + .trim_start_matches("# Condition:") + .trim() + .to_string(), + ); } else if trimmed.starts_with("#---") && condition.is_some() { in_assertion = false; } @@ -96,7 +115,12 @@ pub fn parse_crash_content(path: &Path, mtime: SystemTime, content: &str) -> Cra } } - let (category, title, explanation) = explain(exception_code.as_deref(), function.as_deref(), condition.as_deref(), content); + let (category, title, explanation) = explain( + exception_code.as_deref(), + function.as_deref(), + condition.as_deref(), + content, + ); let preview_lines: Vec<&str> = lines.iter().take(25).copied().collect(); let preview = preview_lines.join("\n"); @@ -117,7 +141,12 @@ pub fn parse_crash_content(path: &Path, mtime: SystemTime, content: &str) -> Cra } } -fn explain(code: Option<&str>, func: Option<&str>, cond: Option<&str>, full: &str) -> (String, String, String) { +fn explain( + code: Option<&str>, + func: Option<&str>, + cond: Option<&str>, + full: &str, +) -> (String, String, String) { let lower_full = full.to_lowercase(); let lower_func = func.map(|f| f.to_lowercase()).unwrap_or_default(); let lower_cond = cond.map(|c| c.to_lowercase()).unwrap_or_default(); @@ -142,7 +171,8 @@ fn explain(code: Option<&str>, func: Option<&str>, cond: Option<&str>, full: &st return ( "assertion".into(), "Ошибка в модуле ботов (Playerbots)".into(), - "Внутренний сбой в логике ИИ ботов (экипировка, заклинание или поиск пути).".into(), + "Внутренний сбой в логике ИИ ботов (экипировка, заклинание или поиск пути)." + .into(), ); } let cond_label = cond.unwrap_or("Assert condition failed"); @@ -174,7 +204,8 @@ fn explain(code: Option<&str>, func: Option<&str>, cond: Option<&str>, full: &st return ( "exception".into(), "Необработанное исключение C++ (C++ Exception)".into(), - "Произошло критическое исключение C++, которое не было перехвачено ядром сервера.".into(), + "Произошло критическое исключение C++, которое не было перехвачено ядром сервера." + .into(), ); } } @@ -225,12 +256,19 @@ Assertion message: #------------------------------------------------------------ Fault address: 00007FF7ECD3645E "#; - let item = parse_crash_content(Path::new("dummy_worldserver.exe_[3-10_20-20-51].txt"), SystemTime::UNIX_EPOCH, report); + let item = parse_crash_content( + Path::new("dummy_worldserver.exe_[3-10_20-20-51].txt"), + SystemTime::UNIX_EPOCH, + report, + ); println!("ITEM: {item:#?}"); assert_eq!(item.exception_code.as_deref(), Some("C0000420")); assert_eq!(item.category, "assertion"); assert_eq!(item.condition.as_deref(), Some("IsInGrid()")); - assert_eq!(item.function.as_deref(), Some("GridObject::RemoveFromGrid")); + assert_eq!( + item.function.as_deref(), + Some("GridObject::RemoveFromGrid") + ); assert!(item.title.contains("Grid")); assert!(item.explanation.contains("сетке карты")); } diff --git a/crates/coa-core/src/custom_races.rs b/crates/coa-core/src/custom_races.rs index c675e4d..4ddf914 100644 --- a/crates/coa-core/src/custom_races.rs +++ b/crates/coa-core/src/custom_races.rs @@ -92,17 +92,26 @@ pub fn client_patch_status(client_path: &Path) -> ClientPatchStatus { || client_path.join("dinput8.dll.disabled").is_file(); let total = RACE_MPQS.len(); - let current_version = fs::read_to_string(client_path.join(MANIFEST_FILENAME)).ok() - .is_some_and(|manifest| manifest.lines().any(|line| line == format!("# CoA Custom {CLIENT_VERSION}"))); - let state = if enabled_count == total && current_version && client_path.join("dinput8.dll").is_file() { - ClientPatchState::Enabled - } else if disabled_count == total && current_version && client_path.join("dinput8.dll.disabled").is_file() { - ClientPatchState::Disabled - } else if (enabled_count + disabled_count) > 0 { - ClientPatchState::PartiallyInstalled - } else { - ClientPatchState::NotInstalled - }; + let current_version = fs::read_to_string(client_path.join(MANIFEST_FILENAME)) + .ok() + .is_some_and(|manifest| { + manifest + .lines() + .any(|line| line == format!("# CoA Custom {CLIENT_VERSION}")) + }); + let state = + if enabled_count == total && current_version && client_path.join("dinput8.dll").is_file() { + ClientPatchState::Enabled + } else if disabled_count == total + && current_version + && client_path.join("dinput8.dll.disabled").is_file() + { + ClientPatchState::Disabled + } else if (enabled_count + disabled_count) > 0 { + ClientPatchState::PartiallyInstalled + } else { + ClientPatchState::NotInstalled + }; ClientPatchStatus { state, @@ -120,19 +129,32 @@ pub fn set_client_patch_enabled(client_path: &Path, enabled: bool) -> Result<()> } if crate::client::is_running(client_path) { - return Err(Error::Invalid("Close the game before changing custom races patches.".into())); + return Err(Error::Invalid( + "Close the game before changing custom races patches.".into(), + )); } if !client_path.join(MANIFEST_FILENAME).is_file() - && !RACE_MPQS.iter().skip(1).any(|name| client_path.join("Data").join(name).is_file() - || client_path.join("Data").join(format!("{name}.disabled")).is_file()) { + && !RACE_MPQS.iter().skip(1).any(|name| { + client_path.join("Data").join(name).is_file() + || client_path + .join("Data") + .join(format!("{name}.disabled")) + .is_file() + }) + { return Ok(()); } - let mut paths: Vec = RACE_MPQS.iter().map(|name| client_path.join("Data").join(name)).collect(); + let mut paths: Vec = RACE_MPQS + .iter() + .map(|name| client_path.join("Data").join(name)) + .collect(); if let Ok(manifest) = fs::read_to_string(client_path.join(MANIFEST_FILENAME)) { for line in manifest.lines() { if let Some(name) = line.strip_prefix("MPQ:") { if name.contains(['/', '\\']) || !name.to_ascii_lowercase().ends_with(".mpq") { - return Err(Error::Invalid("Invalid custom races patch manifest.".into())); + return Err(Error::Invalid( + "Invalid custom races patch manifest.".into(), + )); } paths.push(fsx::safe_join(&client_path.join("Data"), name)?); } @@ -143,18 +165,31 @@ pub fn set_client_patch_enabled(client_path: &Path, enabled: bool) -> Result<()> paths.push(client_path.join("dinput8.dll")); paths.push(client_path.join("Ascension.exe")); for active in paths { - let disabled = active.with_extension(format!("{}.disabled", active.extension().unwrap_or_default().to_string_lossy())); - let original = active.with_extension(format!("{}.original", active.extension().unwrap_or_default().to_string_lossy())); + let disabled = active.with_extension(format!( + "{}.disabled", + active.extension().unwrap_or_default().to_string_lossy() + )); + let original = active.with_extension(format!( + "{}.original", + active.extension().unwrap_or_default().to_string_lossy() + )); if enabled && disabled.is_file() { if active.is_file() { if !original.is_file() { - return Err(Error::Invalid(format!("Cannot replace existing {} without an original backup.", active.display()))); + return Err(Error::Invalid(format!( + "Cannot replace existing {} without an original backup.", + active.display() + ))); } fs::remove_file(&active)?; } fs::rename(&disabled, &active)?; } else if !enabled && active.is_file() && !disabled.is_file() { - if active.file_name().is_some_and(|name| name == "Ascension.exe") && !original.is_file() { + if active + .file_name() + .is_some_and(|name| name == "Ascension.exe") + && !original.is_file() + { continue; } fs::rename(&active, &disabled)?; @@ -170,13 +205,21 @@ pub fn set_client_patch_enabled(client_path: &Path, enabled: bool) -> Result<()> fn verify_archive(path: &Path, filename: &str) -> Result<()> { let expected = match filename { - "CoA-Custom-1.5-main-20261009-cb2a0ca4.zip" => "117f5d99add18191676be6648fb0f2e99019a06c18705c71454e371e7df2afd2", - "CoA-Custom-1.5-client-part1.zip" => "19eb372805b3268653914da03377d67f056e5b50d818a8a06a5f260aad03211e", - "CoA-Custom-1.5-client-part2.zip" => "122f2882da255913e01610e33c6446ded897fecbe60b6d5ee026149becf8f278", + "CoA-Custom-1.5-main-20261009-cb2a0ca4.zip" => { + "117f5d99add18191676be6648fb0f2e99019a06c18705c71454e371e7df2afd2" + } + "CoA-Custom-1.5-client-part1.zip" => { + "19eb372805b3268653914da03377d67f056e5b50d818a8a06a5f260aad03211e" + } + "CoA-Custom-1.5-client-part2.zip" => { + "122f2882da255913e01610e33c6446ded897fecbe60b6d5ee026149becf8f278" + } _ => return Err(Error::Invalid("Unknown custom races archive.".into())), }; if fsx::sha256_file(path)? != expected { - return Err(Error::Invalid(format!("Custom races archive {filename} failed verification. Remove it and try again."))); + return Err(Error::Invalid(format!( + "Custom races archive {filename} failed verification. Remove it and try again." + ))); } Ok(()) } @@ -291,11 +334,15 @@ pub fn install_client_patches( report: &dyn Fn(&str, f32), ) -> Result<()> { if !client_path.is_dir() { - return Err(Error::Invalid("Game client directory does not exist.".into())); + return Err(Error::Invalid( + "Game client directory does not exist.".into(), + )); } if crate::client::is_running(client_path) { - return Err(Error::Invalid("Close the game before installing custom races patches.".into())); + return Err(Error::Invalid( + "Close the game before installing custom races patches.".into(), + )); } let data_dir = client_path.join("Data"); fs::create_dir_all(&data_dir)?; @@ -388,14 +435,18 @@ pub fn install_client_patches( let mut out = File::create(&dest)?; io::copy(&mut zfile, &mut out)?; let disabled = data_dir.join(format!("{base}.disabled")); - if disabled.is_file() { fs::remove_file(disabled)?; } + if disabled.is_file() { + fs::remove_file(disabled)?; + } installed_mpqs.push(base); } else if base.eq_ignore_ascii_case("dinput8.dll") { let dest = client_path.join(&base); let mut out = File::create(&dest)?; io::copy(&mut zfile, &mut out)?; let disabled = client_path.join(format!("{base}.disabled")); - if disabled.is_file() { fs::remove_file(disabled)?; } + if disabled.is_file() { + fs::remove_file(disabled)?; + } installed_roots.push(base); } } else if zname_norm.contains("files/client_root/") { @@ -409,15 +460,22 @@ pub fn install_client_patches( let mut out = File::create(&dest)?; io::copy(&mut zfile, &mut out)?; let disabled = client_path.join(format!("{base}.disabled")); - if disabled.is_file() { fs::remove_file(disabled)?; } + if disabled.is_file() { + fs::remove_file(disabled)?; + } installed_roots.push(base); } } } } - if !RACE_MPQS.iter().all(|name| installed_mpqs.iter().any(|installed| installed == name)) { - return Err(Error::Invalid("Custom races archives are missing required client patches.".into())); + if !RACE_MPQS + .iter() + .all(|name| installed_mpqs.iter().any(|installed| installed == name)) + { + return Err(Error::Invalid( + "Custom races archives are missing required client patches.".into(), + )); } // 4. Record manifest @@ -457,28 +515,46 @@ mod tests { let temp = tempfile::tempdir().unwrap(); let data = temp.path().join("Data"); fs::create_dir_all(&data).unwrap(); - for path in [data.join("patch-T.MPQ"), temp.path().join("Ascension.exe"), temp.path().join("dinput8.dll")] { + for path in [ + data.join("patch-T.MPQ"), + temp.path().join("Ascension.exe"), + temp.path().join("dinput8.dll"), + ] { fs::write(&path, b"custom").unwrap(); - let backup = path.with_extension(format!("{}.original", path.extension().unwrap().to_string_lossy())); + let backup = path.with_extension(format!( + "{}.original", + path.extension().unwrap().to_string_lossy() + )); fs::write(&backup, b"original").unwrap(); } fs::write(temp.path().join(MANIFEST_FILENAME), "MPQ:patch-T.MPQ\n").unwrap(); set_client_patch_enabled(temp.path(), false).unwrap(); assert_eq!(fs::read(data.join("patch-T.MPQ")).unwrap(), b"original"); - assert_eq!(fs::read(temp.path().join("Ascension.exe")).unwrap(), b"original"); + assert_eq!( + fs::read(temp.path().join("Ascension.exe")).unwrap(), + b"original" + ); set_client_patch_enabled(temp.path(), true).unwrap(); assert_eq!(fs::read(data.join("patch-T.MPQ")).unwrap(), b"custom"); - assert_eq!(fs::read(temp.path().join("Ascension.exe")).unwrap(), b"custom"); + assert_eq!( + fs::read(temp.path().join("Ascension.exe")).unwrap(), + b"custom" + ); } #[test] fn an_old_complete_installation_requires_an_update() { let temp = tempfile::tempdir().unwrap(); fs::create_dir_all(temp.path().join("Data")).unwrap(); - for name in RACE_MPQS { fs::write(temp.path().join("Data").join(name), b"old patch").unwrap(); } + for name in RACE_MPQS { + fs::write(temp.path().join("Data").join(name), b"old patch").unwrap(); + } fs::write(temp.path().join("dinput8.dll"), b"old runtime").unwrap(); fs::write(temp.path().join(MANIFEST_FILENAME), "# CoA Custom 1.4\n").unwrap(); - assert_eq!(client_patch_status(temp.path()).state, ClientPatchState::PartiallyInstalled); + assert_eq!( + client_patch_status(temp.path()).state, + ClientPatchState::PartiallyInstalled + ); } #[test] @@ -487,7 +563,10 @@ mod tests { fs::create_dir_all(temp.path().join("Data")).unwrap(); fs::write(temp.path().join("Data/patch-T.MPQ"), b"original").unwrap(); set_client_patch_enabled(temp.path(), false).unwrap(); - assert_eq!(fs::read(temp.path().join("Data/patch-T.MPQ")).unwrap(), b"original"); + assert_eq!( + fs::read(temp.path().join("Data/patch-T.MPQ")).unwrap(), + b"original" + ); } #[test] @@ -508,7 +587,11 @@ mod tests { let st = client_patch_status(client_path); assert_eq!(st.state, ClientPatchState::NotInstalled); - fs::write(client_path.join(MANIFEST_FILENAME), format!("# CoA Custom {CLIENT_VERSION}\n")).unwrap(); + fs::write( + client_path.join(MANIFEST_FILENAME), + format!("# CoA Custom {CLIENT_VERSION}\n"), + ) + .unwrap(); // 2. Create MPQs and root files for mpq in RACE_MPQS { fs::write(data_dir.join(mpq), b"test mpq content").unwrap(); diff --git a/crates/coa-core/src/db.rs b/crates/coa-core/src/db.rs index 48f8466..9bfb20f 100644 --- a/crates/coa-core/src/db.rs +++ b/crates/coa-core/src/db.rs @@ -271,7 +271,13 @@ impl Db { match code { ErrorCode::DatabaseNotRunning => Error::Invalid(format!( "The database is not running. Start the server first. ({})", - text.trim().lines().last().unwrap_or("").chars().take(300).collect::() + text.trim() + .lines() + .last() + .unwrap_or("") + .chars() + .take(300) + .collect::() )), _ => Error::Invalid(format!( "database command failed: {}", diff --git a/crates/coa-core/src/diag.rs b/crates/coa-core/src/diag.rs index e6ab10f..858dedd 100644 --- a/crates/coa-core/src/diag.rs +++ b/crates/coa-core/src/diag.rs @@ -497,7 +497,9 @@ pub fn drop_identity_lines(listing: &str) -> String { fn decode_console_output(bytes: &[u8]) -> String { if bytes.starts_with(&[0xFF, 0xFE]) { let units: Vec = bytes[2..] - .as_chunks::<2>().0.iter() + .as_chunks::<2>() + .0 + .iter() .map(|c| u16::from_le_bytes([c[0], c[1]])) .collect(); String::from_utf16_lossy(&units) diff --git a/crates/coa-core/src/docker/lifecycle.rs b/crates/coa-core/src/docker/lifecycle.rs index 63a86ea..f814cee 100644 --- a/crates/coa-core/src/docker/lifecycle.rs +++ b/crates/coa-core/src/docker/lifecycle.rs @@ -500,7 +500,10 @@ fn database_env(s: &Secrets, world: bool, realm: crate::realms::Mode) -> Vec<(St // The databases of the selected realm (the Wildcard realm has its own world and characters databases). let schema = |kind: &str| realm.schema(kind).unwrap_or("acore_world"); env.push(("AC_WORLD_DATABASE_INFO".into(), info(schema("world")))); - env.push(("AC_CHARACTER_DATABASE_INFO".into(), info(schema("characters")))); + env.push(( + "AC_CHARACTER_DATABASE_INFO".into(), + info(schema("characters")), + )); } env } @@ -594,7 +597,10 @@ fn game_args( a.extend(["--volume".into(), format!("{}:{DATA}:ro", data.display())]); let races = host.join("Data/dbc_races"); if races.is_dir() && races != data.join("dbc_races") { - a.extend(["--volume".into(), format!("{}:{DATA}/dbc_races:ro", races.display())]); + a.extend([ + "--volume".into(), + format!("{}:{DATA}/dbc_races:ro", races.display()), + ]); } a.extend(env("AC_DATA_DIR", DATA)); // The remote console is only ever reachable from this computer. @@ -1115,16 +1121,36 @@ mod tests { #[test] fn the_containers_use_the_databases_of_the_selected_realm() { - let s = Secrets { root: "r".into(), app: "apppw".into() }; - let get = |env: &[(String, String)], k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()); + let s = Secrets { + root: "r".into(), + app: "apppw".into(), + }; + let get = |env: &[(String, String)], k: &str| { + env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()) + }; let coa = database_env(&s, true, crate::realms::Mode::Coa); - assert_eq!(get(&coa, "AC_WORLD_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_world"); - assert_eq!(get(&coa, "AC_CHARACTER_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_characters"); + assert_eq!( + get(&coa, "AC_WORLD_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_world" + ); + assert_eq!( + get(&coa, "AC_CHARACTER_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_characters" + ); let wild = database_env(&s, true, crate::realms::Mode::Wildcard); - assert_eq!(get(&wild, "AC_WORLD_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_world_wildcard"); - assert_eq!(get(&wild, "AC_CHARACTER_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_characters_wildcard"); + assert_eq!( + get(&wild, "AC_WORLD_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_world_wildcard" + ); + assert_eq!( + get(&wild, "AC_CHARACTER_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_characters_wildcard" + ); // Accounts are shared by both realms; the auth server never sees the others. - assert_eq!(get(&wild, "AC_LOGIN_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_auth"); + assert_eq!( + get(&wild, "AC_LOGIN_DATABASE_INFO").unwrap(), + "db;3306;acore;apppw;acore_auth" + ); let auth = database_env(&s, false, crate::realms::Mode::Wildcard); assert_eq!(auth.len(), 1); } diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index 3c86463..e4aa05f 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -4,7 +4,7 @@ clippy::doc_overindented_list_items, clippy::unnecessary_sort_by, clippy::explicit_counter_loop, - clippy::large_enum_variant, + clippy::large_enum_variant )] pub mod accounts; diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs index 0bfac85..96ce4f6 100644 --- a/crates/coa-core/src/modules.rs +++ b/crates/coa-core/src/modules.rs @@ -266,7 +266,9 @@ pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> { } if id == "custom-races" { if let Ok(meta_content) = fs::read_to_string(meta.join("install.json")) { - if let Ok(install_meta) = serde_json::from_str::(&meta_content) { + if let Ok(install_meta) = + serde_json::from_str::(&meta_content) + { if let Some(cp) = install_meta.client_path { let client_path = PathBuf::from(cp); if client_path.is_dir() { diff --git a/crates/coa-core/src/platform.rs b/crates/coa-core/src/platform.rs index d943aaa..c50c5d7 100644 --- a/crates/coa-core/src/platform.rs +++ b/crates/coa-core/src/platform.rs @@ -35,7 +35,13 @@ mod tests { #[test] fn the_screens_read_the_flavor_as_a_plain_word() { - assert_eq!(serde_json::to_string(&Flavor::Repack).unwrap(), "\"repack\""); - assert_eq!(serde_json::to_string(&Flavor::Docker).unwrap(), "\"docker\""); + assert_eq!( + serde_json::to_string(&Flavor::Repack).unwrap(), + "\"repack\"" + ); + assert_eq!( + serde_json::to_string(&Flavor::Docker).unwrap(), + "\"docker\"" + ); } } diff --git a/crates/coa-core/src/portable/realm/export.rs b/crates/coa-core/src/portable/realm/export.rs index 1a4c50f..07416d3 100644 --- a/crates/coa-core/src/portable/realm/export.rs +++ b/crates/coa-core/src/portable/realm/export.rs @@ -454,7 +454,13 @@ fn items( )); } let mut enchantments = Vec::new(); - for (slot, chunk) in enchantment_numbers.as_chunks::<3>().0.iter().take(12).enumerate() { + for (slot, chunk) in enchantment_numbers + .as_chunks::<3>() + .0 + .iter() + .take(12) + .enumerate() + { if chunk.iter().any(|v| *v != 0) { let to = |v: i64| { u32::try_from(v).map_err(|_| { diff --git a/crates/coa-core/src/realms.rs b/crates/coa-core/src/realms.rs index f855e4f..6d47cec 100644 --- a/crates/coa-core/src/realms.rs +++ b/crates/coa-core/src/realms.rs @@ -79,7 +79,11 @@ pub fn state(root: &Path) -> Result { /// The world server executable of this folder: `worldserver.exe` in a repack, `worldserver` in a Docker server. fn world_binary(root: &Path) -> std::path::PathBuf { let exe = root.join("Core/worldserver.exe"); - if exe.exists() { exe } else { root.join("Core/worldserver") } + if exe.exists() { + exe + } else { + root.join("Core/worldserver") + } } pub fn view(root: &Path) -> Result { @@ -415,7 +419,9 @@ pub fn select(root: &Path, mode: Mode) -> Result { /// Adapt the bundled launcher's canonical schema and realm choices without changing its supervision logic. pub fn prepare_launcher(root: &Path) -> Result<()> { // A Docker server has no launcher to adapt: the Docker backend reads the active realm itself. - if crate::docker::is_docker(root) { return Ok(()); } + if crate::docker::is_docker(root) { + return Ok(()); + } let path = root.join("Scripts/manage.py"); let source = fs::read_to_string(&path)?; let patched = patch_launcher(&source)?; @@ -550,13 +556,28 @@ mod tests { let d = tempfile::tempdir().unwrap(); fs::create_dir_all(d.path().join("Core")).unwrap(); fs::create_dir_all(d.path().join("Settings")).unwrap(); - fs::write(d.path().join("Settings/docker.json"), br#"{"project":"t1"}"#).unwrap(); - fs::write(d.path().join("Core/worldserver"), b"ELF...Wildcard synergy settings...").unwrap(); - assert!(view(d.path()).unwrap().supported, "worldserver without .exe is read too"); + fs::write( + d.path().join("Settings/docker.json"), + br#"{"project":"t1"}"#, + ) + .unwrap(); + fs::write( + d.path().join("Core/worldserver"), + b"ELF...Wildcard synergy settings...", + ) + .unwrap(); + assert!( + view(d.path()).unwrap().supported, + "worldserver without .exe is read too" + ); fs::write(d.path().join("Core/worldserver"), b"ELF...an older build").unwrap(); assert!(!view(d.path()).unwrap().supported); // The repack's executable still wins when both exist, so a repack is read as before. - fs::write(d.path().join("Core/worldserver.exe"), b"MZ...Wildcard synergy settings").unwrap(); + fs::write( + d.path().join("Core/worldserver.exe"), + b"MZ...Wildcard synergy settings", + ) + .unwrap(); assert!(view(d.path()).unwrap().supported); } @@ -566,7 +587,11 @@ mod tests { fs::create_dir_all(d.path().join("Settings")).unwrap(); // No Scripts/manage.py anywhere: on a repack this fails, on a Docker server there is nothing to do. assert!(prepare_launcher(d.path()).is_err()); - fs::write(d.path().join("Settings/docker.json"), br#"{"project":"t1"}"#).unwrap(); + fs::write( + d.path().join("Settings/docker.json"), + br#"{"project":"t1"}"#, + ) + .unwrap(); prepare_launcher(d.path()).unwrap(); } diff --git a/crates/coa-core/src/update.rs b/crates/coa-core/src/update.rs index 221ff16..7c0c326 100644 --- a/crates/coa-core/src/update.rs +++ b/crates/coa-core/src/update.rs @@ -428,7 +428,9 @@ pub enum DatabaseAccess { /// server would put Windows files in a Linux server folder. Updating a Docker server is separate work. fn refuse_for_docker(root: &Path) -> Result<()> { if crate::docker::is_docker(root) { - return Err(Error::Invalid("Updates are not available for Docker servers yet.".into())); + return Err(Error::Invalid( + "Updates are not available for Docker servers yet.".into(), + )); } Ok(()) } @@ -1945,17 +1947,34 @@ mod tests { let before = read(&w, "Core/worldserver.exe"); let meta = InstallMeta::new(InstallKind::New, &w.root); - let err = preview(&w.root, &meta, &Source::Dir(w.pkg.clone()), &w.key, &BTreeMap::new()).unwrap_err(); + let err = preview( + &w.root, + &meta, + &Source::Dir(w.pkg.clone()), + &w.key, + &BTreeMap::new(), + ) + .unwrap_err(); assert!(err.to_string().contains("Docker"), "{err}"); let err = run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap_err(); assert!(err.to_string().contains("Docker"), "{err}"); assert!(rollback(&w.root, &w.meta, "any", &Fake::ok()).is_err()); - assert_eq!(read(&w, "Core/worldserver.exe"), before, "nothing was touched"); + assert_eq!( + read(&w, "Core/worldserver.exe"), + before, + "nothing was touched" + ); assert!(!w.root.join("Core/newfile.dll").exists()); // The same package is applied to the same folder once it is not a Docker server. fs::remove_file(w.root.join("Settings/docker.json")).unwrap(); - assert_eq!(run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap().txn.state, State::Committed); + assert_eq!( + run(&w, &Fake::ok(), BTreeMap::new(), None) + .unwrap() + .txn + .state, + State::Committed + ); } #[test] diff --git a/crates/coa-core/src/wine.rs b/crates/coa-core/src/wine.rs index 3f06e67..5715906 100644 --- a/crates/coa-core/src/wine.rs +++ b/crates/coa-core/src/wine.rs @@ -20,8 +20,13 @@ const DEFAULT_PREFIX: &str = "Games/umu/coa-client"; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Runner { /// umu-launcher runs the game with a Proton build. `proton` is `None` when umu should pick and download one itself. - Umu { program: PathBuf, proton: Option }, - Wine { program: PathBuf }, + Umu { + program: PathBuf, + proton: Option, + }, + Wine { + program: PathBuf, + }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -87,16 +92,29 @@ fn version_key(name: &str) -> Vec { fn newest_proton(host: &Host, home: &Path) -> Option { proton_folders(home) .into_iter() - .flat_map(|dir| (host.list)(&dir).into_iter().filter(|n| n.starts_with("GE-Proton")).map(move |n| (n.clone(), dir.join(n)))) + .flat_map(|dir| { + (host.list)(&dir) + .into_iter() + .filter(|n| n.starts_with("GE-Proton")) + .map(move |n| (n.clone(), dir.join(n))) + }) .filter(|(_, path)| (host.is_file)(&path.join("proton"))) .max_by_key(|(name, _)| version_key(name)) .map(|(_, path)| path) } pub fn detect_with(host: &Host, overrides: &Overrides) -> Result { - let home = (host.var)("HOME").map(PathBuf::from).ok_or_else(|| Error::Invalid("The home folder of this user is not known.".into()))?; - let prefix = (host.var)("COA_WINEPREFIX").or_else(|| overrides.prefix.clone()).map(PathBuf::from).unwrap_or_else(|| home.join(DEFAULT_PREFIX)); - let proton = (host.var)("COA_PROTONPATH").or_else(|| overrides.proton_path.clone()).map(PathBuf::from).or_else(|| newest_proton(host, &home)); + let home = (host.var)("HOME") + .map(PathBuf::from) + .ok_or_else(|| Error::Invalid("The home folder of this user is not known.".into()))?; + let prefix = (host.var)("COA_WINEPREFIX") + .or_else(|| overrides.prefix.clone()) + .map(PathBuf::from) + .unwrap_or_else(|| home.join(DEFAULT_PREFIX)); + let proton = (host.var)("COA_PROTONPATH") + .or_else(|| overrides.proton_path.clone()) + .map(PathBuf::from) + .or_else(|| newest_proton(host, &home)); let (umu, wine) = ((host.which)("umu-run"), (host.which)("wine")); let runner = match (overrides.runner.as_deref(), umu, wine) { (Some("wine"), _, Some(program)) => Runner::Wine { program }, @@ -113,7 +131,10 @@ pub fn detect_with(host: &Host, overrides: &Overrides) -> Result { /// The command line that starts `exe` from the client folder. pub fn plan(launcher: &Launcher, client: &Path, exe: &str) -> Plan { - let mut env = vec![("WINEPREFIX".to_string(), launcher.prefix.to_string_lossy().into_owned())]; + let mut env = vec![( + "WINEPREFIX".to_string(), + launcher.prefix.to_string_lossy().into_owned(), + )]; // DivxTac.dll is a mixed-mode .NET assembly: loaded through wine-mono it deadlocks the client on the world loading screen // (100%). Disabling it has the same effect as removing the file. env.push(("WINEDLLOVERRIDES".into(), "divxtac=d".into())); @@ -128,7 +149,12 @@ pub fn plan(launcher: &Launcher, client: &Path, exe: &str) -> Plan { Runner::Wine { program } => program.clone(), }; // The client reads Data/ relative to the working directory. - Plan { program, args: vec![exe.to_string()], env, cwd: client.to_path_buf() } + Plan { + program, + args: vec![exe.to_string()], + env, + cwd: client.to_path_buf(), + } } fn system_var(k: &str) -> Option { @@ -136,15 +162,26 @@ fn system_var(k: &str) -> Option { } fn find_on_path(program: &str) -> Option { - std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(program)).find(|p| p.is_file()) + std::env::split_paths(&std::env::var_os("PATH")?) + .map(|d| d.join(program)) + .find(|p| p.is_file()) } fn list_names(dir: &Path) -> Vec { - fs::read_dir(dir).map(|rd| rd.filter_map(|e| e.ok()).filter_map(|e| e.file_name().into_string().ok()).collect()).unwrap_or_default() + fs::read_dir(dir) + .map(|rd| { + rd.filter_map(|e| e.ok()) + .filter_map(|e| e.file_name().into_string().ok()) + .collect() + }) + .unwrap_or_default() } fn data_home() -> Option { - system_var("XDG_DATA_HOME").map(PathBuf::from).filter(|p| p.is_absolute()).or_else(|| system_var("HOME").map(|h| PathBuf::from(h).join(".local/share"))) + system_var("XDG_DATA_HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .or_else(|| system_var("HOME").map(|h| PathBuf::from(h).join(".local/share"))) } fn overrides_file() -> Option { @@ -152,8 +189,18 @@ fn overrides_file() -> Option { } pub fn detect() -> Result { - let overrides: Overrides = overrides_file().and_then(|p| crate::fsx::read_json(&p).ok()).unwrap_or_default(); - detect_with(&Host { var: &system_var, which: &find_on_path, list: &list_names, is_file: &|p| p.is_file() }, &overrides) + let overrides: Overrides = overrides_file() + .and_then(|p| crate::fsx::read_json(&p).ok()) + .unwrap_or_default(); + detect_with( + &Host { + var: &system_var, + which: &find_on_path, + list: &list_names, + is_file: &|p| p.is_file(), + }, + &overrides, + ) } /// Where what the client prints goes: the Manager's own log folder. @@ -171,7 +218,13 @@ pub fn launch(client: &Path, exe: &str) -> Result { fs::create_dir_all(dir)?; } let mut f = OpenOptions::new().create(true).append(true).open(&p)?; - writeln!(f, "=== {} {:?} in {}", plan.program.display(), plan.args, plan.cwd.display())?; + writeln!( + f, + "=== {} {:?} in {}", + plan.program.display(), + plan.args, + plan.cwd.display() + )?; for (k, v) in &plan.env { writeln!(f, " {k}={v}")?; } @@ -180,7 +233,10 @@ pub fn launch(client: &Path, exe: &str) -> Result { None => None, }; let mut cmd = Command::new(&plan.program); - cmd.args(&plan.args).current_dir(&plan.cwd).envs(plan.env.iter().map(|(k, v)| (k, v))).stdin(Stdio::null()); + cmd.args(&plan.args) + .current_dir(&plan.cwd) + .envs(plan.env.iter().map(|(k, v)| (k, v))) + .stdin(Stdio::null()); match log { Some(f) => { cmd.stderr(f.try_clone()?).stdout(f); @@ -194,7 +250,12 @@ pub fn launch(client: &Path, exe: &str) -> Result { use std::os::unix::process::CommandExt; cmd.process_group(0); // its own group: closing the Manager does not take the game with it } - let mut child = cmd.spawn().map_err(|e| Error::Invalid(format!("The game client could not be started ({}): {e}", plan.program.display())))?; + let mut child = cmd.spawn().map_err(|e| { + Error::Invalid(format!( + "The game client could not be started ({}): {e}", + plan.program.display() + )) + })?; let pid = child.id(); std::thread::spawn(move || { let _ = child.wait(); // reap it when the game closes @@ -205,8 +266,13 @@ pub fn launch(client: &Path, exe: &str) -> Result { /// Is a process running this client? Under Wine its command line carries the Windows form of the path /// (`Z:\home\you\client\Ascension.exe`), which is the only trace of it that names the folder. pub fn command_line_runs(cmdline: &str, client: &Path, exe: &str) -> bool { - let wanted = format!("{}/{}", client.to_string_lossy().trim_end_matches('/'), exe).to_lowercase(); - cmdline.replace('\0', " ").replace('\\', "/").to_lowercase().contains(&wanted) + let wanted = + format!("{}/{}", client.to_string_lossy().trim_end_matches('/'), exe).to_lowercase(); + cmdline + .replace('\0', " ") + .replace('\\', "/") + .to_lowercase() + .contains(&wanted) } /// The folder as it was given and as the system resolves it. On an immutable distribution (SteamOS, Bazzite) `/home` is a @@ -224,13 +290,22 @@ fn spellings(client: &Path) -> Vec { pub fn is_running(client: &Path, exes: &[&str]) -> bool { let folders = spellings(client); - let Ok(rd) = fs::read_dir("/proc") else { return false }; + let Ok(rd) = fs::read_dir("/proc") else { + return false; + }; rd.filter_map(|e| e.ok()) - .filter(|e| e.file_name().to_string_lossy().bytes().all(|b| b.is_ascii_digit())) + .filter(|e| { + e.file_name() + .to_string_lossy() + .bytes() + .all(|b| b.is_ascii_digit()) + }) .filter_map(|e| fs::read(e.path().join("cmdline")).ok()) .any(|raw| { let line = String::from_utf8_lossy(&raw); - folders.iter().any(|folder| exes.iter().any(|exe| command_line_runs(&line, folder, exe))) + folders + .iter() + .any(|folder| exes.iter().any(|exe| command_line_runs(&line, folder, exe))) }) } @@ -252,9 +327,14 @@ mod tests { assert_eq!(both[0], given); assert!(both[1].starts_with(dir.path().canonicalize().unwrap().join("var/home"))); // Wine kept the name it was given, so the line holds the first one and not the resolved one. - let line = format!("Z:\\{}\\Ascension.exe", given.to_string_lossy().replace('/', "\\")); + let line = format!( + "Z:\\{}\\Ascension.exe", + given.to_string_lossy().replace('/', "\\") + ); assert!(!command_line_runs(&line, &both[1], "Ascension.exe")); - assert!(both.iter().any(|f| command_line_runs(&line, f, "Ascension.exe"))); + assert!(both + .iter() + .any(|f| command_line_runs(&line, f, "Ascension.exe"))); } /// A computer described in a few lines: variables, programs on the path, folders with their entries, and `proton` scripts. @@ -266,16 +346,37 @@ mod tests { impl Fake { fn new() -> Fake { - Fake { vars: BTreeMap::from([("HOME", "/home/ana")]), programs: BTreeSet::new(), folders: BTreeMap::new() } + Fake { + vars: BTreeMap::from([("HOME", "/home/ana")]), + programs: BTreeSet::new(), + folders: BTreeMap::new(), + } } fn detect(&self, overrides: &Overrides) -> Result { let var = |k: &str| self.vars.get(k).map(|v| v.to_string()); - let which = |p: &str| self.programs.contains(p).then(|| PathBuf::from(format!("/usr/bin/{p}"))); - let list = |d: &Path| self.folders.get(d.to_str().unwrap()).map(|v| v.iter().map(|s| s.to_string()).collect()).unwrap_or_default(); + let which = |p: &str| { + self.programs + .contains(p) + .then(|| PathBuf::from(format!("/usr/bin/{p}"))) + }; + let list = |d: &Path| { + self.folders + .get(d.to_str().unwrap()) + .map(|v| v.iter().map(|s| s.to_string()).collect()) + .unwrap_or_default() + }; // every listed build has its `proton` script let is_file = |p: &Path| p.file_name().is_some_and(|n| n == "proton"); - detect_with(&Host { var: &var, which: &which, list: &list, is_file: &is_file }, overrides) + detect_with( + &Host { + var: &var, + which: &which, + list: &list, + is_file: &is_file, + }, + overrides, + ) } } @@ -285,13 +386,26 @@ mod tests { fn umu_with_the_newest_ge_proton_is_the_default() { let mut c = Fake::new(); c.programs.extend(["umu-run", "wine"]); - c.folders.insert(STEAM, vec!["GE-Proton9-27", "GE-Proton10-9", "GE-Proton10-34", "Proton-Experimental", "notes.txt"]); + c.folders.insert( + STEAM, + vec![ + "GE-Proton9-27", + "GE-Proton10-9", + "GE-Proton10-34", + "Proton-Experimental", + "notes.txt", + ], + ); let l = c.detect(&Overrides::default()).unwrap(); assert_eq!(l.prefix, PathBuf::from("/home/ana/Games/umu/coa-client")); match l.runner { Runner::Umu { proton, program } => { assert_eq!(program, PathBuf::from("/usr/bin/umu-run")); - assert_eq!(proton, Some(PathBuf::from(format!("{STEAM}/GE-Proton10-34"))), "10-34 is newer than 10-9"); + assert_eq!( + proton, + Some(PathBuf::from(format!("{STEAM}/GE-Proton10-34"))), + "10-34 is newer than 10-9" + ); } other => panic!("{other:?}"), } @@ -301,7 +415,9 @@ mod tests { fn without_a_proton_build_umu_is_left_to_choose_one() { let mut c = Fake::new(); c.programs.insert("umu-run"); - let Runner::Umu { proton, .. } = c.detect(&Overrides::default()).unwrap().runner else { panic!() }; + let Runner::Umu { proton, .. } = c.detect(&Overrides::default()).unwrap().runner else { + panic!() + }; assert_eq!(proton, None); } @@ -309,13 +425,22 @@ mod tests { fn plain_wine_is_used_when_umu_is_not_installed() { let mut c = Fake::new(); c.programs.insert("wine"); - assert!(matches!(c.detect(&Overrides::default()).unwrap().runner, Runner::Wine { .. })); + assert!(matches!( + c.detect(&Overrides::default()).unwrap().runner, + Runner::Wine { .. } + )); } #[test] fn without_umu_or_wine_the_person_is_told_what_to_install() { - let err = Fake::new().detect(&Overrides::default()).unwrap_err().to_string(); - assert!(err.contains("umu-launcher") && err.contains("Wine"), "{err}"); + let err = Fake::new() + .detect(&Overrides::default()) + .unwrap_err() + .to_string(); + assert!( + err.contains("umu-launcher") && err.contains("Wine"), + "{err}" + ); } #[test] @@ -323,45 +448,108 @@ mod tests { let mut c = Fake::new(); c.programs.extend(["umu-run", "wine"]); c.folders.insert(STEAM, vec!["GE-Proton10-34"]); - let file = Overrides { proton_path: Some("/opt/proton-a".into()), prefix: Some("/data/prefix-a".into()), runner: None }; + let file = Overrides { + proton_path: Some("/opt/proton-a".into()), + prefix: Some("/data/prefix-a".into()), + runner: None, + }; let l = c.detect(&file).unwrap(); assert_eq!(l.prefix, PathBuf::from("/data/prefix-a")); - assert!(matches!(&l.runner, Runner::Umu { proton: Some(p), .. } if p == Path::new("/opt/proton-a"))); + assert!( + matches!(&l.runner, Runner::Umu { proton: Some(p), .. } if p == Path::new("/opt/proton-a")) + ); c.vars.insert("COA_PROTONPATH", "/opt/proton-b"); c.vars.insert("COA_WINEPREFIX", "/data/prefix-b"); let l = c.detect(&file).unwrap(); assert_eq!(l.prefix, PathBuf::from("/data/prefix-b")); - assert!(matches!(&l.runner, Runner::Umu { proton: Some(p), .. } if p == Path::new("/opt/proton-b"))); + assert!( + matches!(&l.runner, Runner::Umu { proton: Some(p), .. } if p == Path::new("/opt/proton-b")) + ); // Forcing Wine works when it is installed, and falls back to umu when it is not. - let wine = Overrides { runner: Some("wine".into()), ..Default::default() }; - assert!(matches!(c.detect(&wine).unwrap().runner, Runner::Wine { .. })); + let wine = Overrides { + runner: Some("wine".into()), + ..Default::default() + }; + assert!(matches!( + c.detect(&wine).unwrap().runner, + Runner::Wine { .. } + )); } #[test] fn the_command_is_the_one_of_the_projects_own_launcher_script() { - let l = Launcher { runner: Runner::Umu { program: "/usr/bin/umu-run".into(), proton: Some("/p/GE-Proton11-6".into()) }, prefix: "/home/ana/Games/umu/coa-client".into() }; - let p = plan(&l, Path::new("/home/ana/CoaServer/client/ascension-live"), "Ascension.exe"); + let l = Launcher { + runner: Runner::Umu { + program: "/usr/bin/umu-run".into(), + proton: Some("/p/GE-Proton11-6".into()), + }, + prefix: "/home/ana/Games/umu/coa-client".into(), + }; + let p = plan( + &l, + Path::new("/home/ana/CoaServer/client/ascension-live"), + "Ascension.exe", + ); assert_eq!(p.program, PathBuf::from("/usr/bin/umu-run")); assert_eq!(p.args, ["Ascension.exe"]); - assert_eq!(p.cwd, PathBuf::from("/home/ana/CoaServer/client/ascension-live"), "the client reads Data/ from its working directory"); + assert_eq!( + p.cwd, + PathBuf::from("/home/ana/CoaServer/client/ascension-live"), + "the client reads Data/ from its working directory" + ); let env: BTreeMap<_, _> = p.env.iter().cloned().collect(); assert_eq!(env["GAMEID"], "0"); assert_eq!(env["PROTONPATH"], "/p/GE-Proton11-6"); assert_eq!(env["WINEPREFIX"], "/home/ana/Games/umu/coa-client"); - assert_eq!(env["WINEDLLOVERRIDES"], "divxtac=d", "DivxTac.dll deadlocks the world loading screen under wine-mono"); + assert_eq!( + env["WINEDLLOVERRIDES"], "divxtac=d", + "DivxTac.dll deadlocks the world loading screen under wine-mono" + ); // Wine has no GAMEID / PROTONPATH. - let w = plan(&Launcher { runner: Runner::Wine { program: "/usr/bin/wine".into() }, prefix: "/pre".into() }, Path::new("/c"), "Wow.exe"); - assert!(w.env.iter().all(|(k, _)| k != "GAMEID" && k != "PROTONPATH") && w.args == ["Wow.exe"]); + let w = plan( + &Launcher { + runner: Runner::Wine { + program: "/usr/bin/wine".into(), + }, + prefix: "/pre".into(), + }, + Path::new("/c"), + "Wow.exe", + ); + assert!( + w.env + .iter() + .all(|(k, _)| k != "GAMEID" && k != "PROTONPATH") + && w.args == ["Wow.exe"] + ); } #[test] fn a_wine_command_line_names_the_client_folder_in_windows_form() { let client = Path::new("/home/ana/CoaServer/client/ascension-live"); - assert!(command_line_runs("Z:\\home\\ana\\CoaServer\\client\\ascension-live\\Ascension.exe\0", client, "Ascension.exe")); + assert!(command_line_runs( + "Z:\\home\\ana\\CoaServer\\client\\ascension-live\\Ascension.exe\0", + client, + "Ascension.exe" + )); assert!(command_line_runs("C:\\windows\\system32\\start.exe /exec Z:\\HOME\\ANA\\coaserver\\client\\ascension-live\\ascension.exe", client, "Ascension.exe"), "case does not matter"); - assert!(!command_line_runs("Z:\\home\\ana\\CoaServer\\client\\ascension-lab\\Ascension.exe", client, "Ascension.exe"), "another client folder"); - assert!(!command_line_runs("umu-run Ascension.exe", client, "Ascension.exe"), "the launcher alone does not name the folder"); - assert!(!command_line_runs("Z:\\home\\ana\\CoaServer\\client\\ascension-live\\Ascension.exe.ORIGINAL", Path::new("/other"), "Ascension.exe")); + assert!( + !command_line_runs( + "Z:\\home\\ana\\CoaServer\\client\\ascension-lab\\Ascension.exe", + client, + "Ascension.exe" + ), + "another client folder" + ); + assert!( + !command_line_runs("umu-run Ascension.exe", client, "Ascension.exe"), + "the launcher alone does not name the folder" + ); + assert!(!command_line_runs( + "Z:\\home\\ana\\CoaServer\\client\\ascension-live\\Ascension.exe.ORIGINAL", + Path::new("/other"), + "Ascension.exe" + )); } #[test] @@ -382,12 +570,35 @@ mod tests { let script = d.path().join("umu-run"); fs::write(&script, format!("#!/bin/sh\n{{ echo \"cwd=$(pwd)\"; echo \"arg=$1\"; echo \"prefix=$WINEPREFIX\"; echo \"gameid=$GAMEID\"; echo \"dll=$WINEDLLOVERRIDES\"; }} > '{}'\n", out.display())).unwrap(); fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); - let launcher = Launcher { runner: Runner::Umu { program: script, proton: None }, prefix: d.path().join("prefix") }; + let launcher = Launcher { + runner: Runner::Umu { + program: script, + proton: None, + }, + prefix: d.path().join("prefix"), + }; let p = plan(&launcher, &client, "Ascension.exe"); - let mut child = Command::new(&p.program).args(&p.args).current_dir(&p.cwd).envs(p.env.iter().map(|(k, v)| (k, v))).spawn().unwrap(); + let mut child = Command::new(&p.program) + .args(&p.args) + .current_dir(&p.cwd) + .envs(p.env.iter().map(|(k, v)| (k, v))) + .spawn() + .unwrap(); assert!(child.wait().unwrap().success()); let seen = fs::read_to_string(&out).unwrap(); - assert!(seen.contains(&format!("cwd={}", fs::canonicalize(&client).unwrap().display())), "{seen}"); - assert!(seen.contains("arg=Ascension.exe") && seen.contains("gameid=0") && seen.contains("dll=divxtac=d") && seen.contains("prefix="), "{seen}"); + assert!( + seen.contains(&format!( + "cwd={}", + fs::canonicalize(&client).unwrap().display() + )), + "{seen}" + ); + assert!( + seen.contains("arg=Ascension.exe") + && seen.contains("gameid=0") + && seen.contains("dll=divxtac=d") + && seen.contains("prefix="), + "{seen}" + ); } } diff --git a/docs/RELEASE_READINESS.md b/docs/RELEASE_READINESS.md index d56026f..b00eff2 100644 --- a/docs/RELEASE_READINESS.md +++ b/docs/RELEASE_READINESS.md @@ -143,8 +143,8 @@ The release candidate produces standard Windows installer artifacts: | Distribution Artifact | Type | Size (Bytes) | SHA-256 Checksum | Description | |---|---|---|---|---| -| `CoA-Server-Manager_0.6.7_x64-setup.exe` | NSIS Installer | 7,805,485 | `6d6d58217a00c8c10f117bf5d01fb143009433ce21b1466a6411a4b2b9c069b6` | Standalone Windows installer with passive update support | -| `CoA-Server-Manager_0.6.7_x64.nsis.zip` | Archive | 7,787,883 | `86a02952ddaf7be9f91209982a8ae0c2e75bcf00fc18236e91074f825302fa25` | Portable binary archive for testing and verification | +| `CoA-Server-Manager_0.6.7_x64-setup.exe` | NSIS Installer | 7,893,109 | `3fd7940f7693993c03cec2a6fba4003990429129838a3450a2b04c9e16d2f40c` | Standalone Windows installer with passive update support | +| `CoA-Server-Manager_0.6.7_x64.nsis.zip` | Archive | 7,875,533 | `f67b26d5d7c8b8660bb1130f82d6abee74f33c15577ae5bf3155c7149fbf368f` | Portable binary archive for testing and verification | Verification command: ```powershell diff --git a/src-tauri/src/control_cmds.rs b/src-tauri/src/control_cmds.rs index 9686ff3..4872f70 100644 --- a/src-tauri/src/control_cmds.rs +++ b/src-tauri/src/control_cmds.rs @@ -269,8 +269,7 @@ pub(crate) async fn join_realm( let caps = serde_json::to_value(&detail.capabilities) .map_err(|e| fail("other", e.to_string()))?; let id = character.clone(); - let pre = portable - .call(move |s| s.preflight_advert(&id, &caps))??; + let pre = portable.call(move |s| s.preflight_advert(&id, &caps))??; out.notes = pre.notes.clone(); if pre.step == portable_service::Step::Blocked { ch.close(); @@ -281,8 +280,8 @@ pub(crate) async fn join_realm( if !here.iter().any(|(id, _)| id.to_string() == character) { // Phase 12.1: Transfer canonical character to remote Host over the encrypted control channel let char_id_str = character.clone(); - let bundle = portable - .call(move |s| s.export_for_remote_transfer(&char_id_str))??; + let bundle = + portable.call(move |s| s.export_for_remote_transfer(&char_id_str))??; let cuuid = bundle.character_id.as_uuid(); let _outcome = pc .transfer_character( diff --git a/src-tauri/src/docker_install.rs b/src-tauri/src/docker_install.rs index 1768cfc..b4da03b 100644 --- a/src-tauri/src/docker_install.rs +++ b/src-tauri/src/docker_install.rs @@ -28,32 +28,58 @@ pub fn default_dir() -> String { } fn default_dir_in(home: Option<&str>) -> String { - match home.map(|h| h.trim_end_matches('/')).filter(|h| !h.is_empty()) { + match home + .map(|h| h.trim_end_matches('/')) + .filter(|h| !h.is_empty()) + { Some(h) => format!("{h}/CoaServer"), None => "/srv/coa".into(), } } pub fn docker_problem() -> Option { - docker::check_docker(&SystemDocker).err().map(|e| e.to_string()) + docker::check_docker(&SystemDocker) + .err() + .map(|e| e.to_string()) } pub fn environment() -> Environment { - Environment { flavor: coa_core::platform::flavor(), default_dir: default_dir(), docker_problem: docker_problem() } + Environment { + flavor: coa_core::platform::flavor(), + default_dir: default_dir(), + docker_problem: docker_problem(), + } } -pub fn preflight(dest: &str, data: Option, needed: Option, registry: &Registry) -> Preflight { +pub fn preflight( + dest: &str, + data: Option, + needed: Option, + registry: &Registry, +) -> Preflight { // The size comes from the signed package list when the screen already has it; it is checked again at install time. - core_install::preflight(Path::new(dest), Path::new(data.as_deref().unwrap_or("")), needed.unwrap_or(1024 * 1024 * 1024), registry) + core_install::preflight( + Path::new(dest), + Path::new(data.as_deref().unwrap_or("")), + needed.unwrap_or(1024 * 1024 * 1024), + registry, + ) } /// The Linux package has no default address yet: it is published only after the maintainer has signed it. pub fn package_source(custom: Option) -> Result { - let pick = custom.filter(|s| !s.trim().is_empty()).or_else(|| std::env::var("COA_PACKAGE_SOURCE").ok().filter(|s| !s.trim().is_empty())); + let pick = custom.filter(|s| !s.trim().is_empty()).or_else(|| { + std::env::var("COA_PACKAGE_SOURCE") + .ok() + .filter(|s| !s.trim().is_empty()) + }); match pick { Some(p) if p.to_ascii_lowercase().starts_with("http") => Ok(Source::Url(p)), Some(p) => Ok(Source::Dir(PathBuf::from(p))), - None => Err(Error::Invalid("Choose the Linux server package (a folder or an address): none is published yet.".into())), + None => Err(Error::Invalid( + "Choose the Linux server package (a folder or an address): none is published yet." + .into(), + )), } } @@ -69,26 +95,54 @@ pub fn trusted_key() -> String { coa_core::signing::EMBEDDED_PUBLIC_KEY.to_string() } -pub async fn requirements(package: Option) -> std::result::Result { +pub async fn requirements( + package: Option, +) -> std::result::Result { blocking(move || { - let (m, _) = coa_core::pkgsource::fetch_manifest(&package_source(package)?, &trusted_key())?; - let archive = m.archive.ok_or_else(|| Error::InvalidManifest("no archive".into()))?; - Ok(InstallRequirements { download_bytes: archive.parts.iter().map(|p| p.size).sum(), unpacked_bytes: archive.unpacked_size, version: m.version }) + let (m, _) = + coa_core::pkgsource::fetch_manifest(&package_source(package)?, &trusted_key())?; + let archive = m + .archive + .ok_or_else(|| Error::InvalidManifest("no archive".into()))?; + Ok(InstallRequirements { + download_bytes: archive.parts.iter().map(|p| p.size).sum(), + unpacked_bytes: archive.unpacked_size, + version: m.version, + }) }) .await } -pub async fn install(app: AppHandle, state: State<'_, AppState>, dest: String, package: Option, data: Option) -> std::result::Result { +pub async fn install( + app: AppHandle, + state: State<'_, AppState>, + dest: String, + package: Option, + data: Option, +) -> std::result::Result { let source = package_source(package)?; - let data_dir_path = PathBuf::from(data.filter(|d| !d.trim().is_empty()).ok_or_else(|| Error::Invalid("Choose the folder that holds the game data.".into()))?); + let data_dir_path = PathBuf::from( + data.filter(|d| !d.trim().is_empty()) + .ok_or_else(|| Error::Invalid("Choose the folder that holds the game data.".into()))?, + ); let cancel = Cancel::default(); - *state.install_cancel.lock().map_err(|_| Error::Invalid("state poisoned".into()))? = Some(cancel.clone()); + *state + .install_cancel + .lock() + .map_err(|_| Error::Invalid("state poisoned".into()))? = Some(cancel.clone()); let registry = Registry::at(data_dir().join("installs.json")); let dest_path = PathBuf::from(dest); let key = trusted_key(); let result = tauri::async_runtime::spawn_blocking(move || { core_install::install( - &core_install::Params { source, dest: dest_path, data_dir: data_dir_path, trusted_key: &key, registry: ®istry, cancel }, + &core_install::Params { + source, + dest: dest_path, + data_dir: data_dir_path, + trusted_key: &key, + registry: ®istry, + cancel, + }, &|step| { let _ = app.emit("install-progress", step); }, @@ -119,7 +173,13 @@ mod tests { std::env::remove_var("COA_PACKAGE_SOURCE"); assert!(package_source(None).is_err()); assert!(package_source(Some(" ".into())).is_err()); - assert!(matches!(package_source(Some("/tmp/pkg".into())).unwrap(), Source::Dir(_))); - assert!(matches!(package_source(Some("https://example.org/pkg".into())).unwrap(), Source::Url(_))); + assert!(matches!( + package_source(Some("/tmp/pkg".into())).unwrap(), + Source::Dir(_) + )); + assert!(matches!( + package_source(Some("https://example.org/pkg".into())).unwrap(), + Source::Url(_) + )); } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 330b969..256e24c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -11,10 +11,10 @@ use coa_core::backup::{self, Kind, RecoveryPoint, Trigger, VerifyReport}; use coa_core::config::{self, Scope, SettingsView}; use coa_core::download::Cancel; use coa_core::driver::{self, DriverOutcome, Verb}; -use coa_core::platform::{self, Flavor}; use coa_core::error::UiError; use coa_core::install::{self, Preflight, Source}; use coa_core::layout::{self, Classification, ScanReport}; +use coa_core::platform::{self, Flavor}; use coa_core::portable::service::{self as portable_service, PortableRuntime, ServiceError}; use coa_core::process::{self, Observed}; use coa_core::ra::Ra; @@ -341,7 +341,13 @@ fn default_install_dir() -> String { /// whether Docker can be used. #[tauri::command] async fn install_environment() -> docker_install::Environment { - tauri::async_runtime::spawn_blocking(docker_install::environment).await.unwrap_or_else(|_| docker_install::Environment { flavor: platform::flavor(), default_dir: default_install_dir(), docker_problem: None }) + tauri::async_runtime::spawn_blocking(docker_install::environment) + .await + .unwrap_or_else(|_| docker_install::Environment { + flavor: platform::flavor(), + default_dir: default_install_dir(), + docker_problem: None, + }) } #[tauri::command] @@ -827,7 +833,12 @@ async fn restore_backup_database( } #[tauri::command] -fn install_preflight(state: State<'_, AppState>, dest: String, needed: Option, game_data: Option) -> Preflight { +fn install_preflight( + state: State<'_, AppState>, + dest: String, + needed: Option, + game_data: Option, +) -> Preflight { if platform::flavor() == Flavor::Docker { return docker_install::preflight(&dest, game_data, needed, &state.registry); } @@ -1137,31 +1148,46 @@ async fn module_set_enabled( } #[tauri::command] -async fn custom_races_status(state: State<'_, AppState>, id: String) -> std::result::Result, UiError> { +async fn custom_races_status( + state: State<'_, AppState>, + id: String, +) -> std::result::Result, UiError> { let root = path_of(&state, &id)?; blocking(move || { let client = linked_client(&root)?; - Ok(client.as_deref().map(coa_core::custom_races::client_patch_status)) + Ok(client + .as_deref() + .map(coa_core::custom_races::client_patch_status)) }) .await } #[tauri::command] -async fn custom_races_install(app: AppHandle, state: State<'_, AppState>, id: String) -> std::result::Result<(), UiError> { +async fn custom_races_install( + app: AppHandle, + state: State<'_, AppState>, + id: String, +) -> std::result::Result<(), UiError> { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; let cancel = begin_client_job(&state)?; let sid = id.clone(); let result = blocking(move || { - let client = linked_client(&root)?.ok_or_else(|| Error::Invalid("No game client is linked to this server.".into()))?; + let client = linked_client(&root)? + .ok_or_else(|| Error::Invalid("No game client is linked to this server.".into()))?; coa_core::custom_races::install_client_patches(&client, &cancel, &|step, percent| { - let _ = app.emit("custom-races-progress", serde_json::json!({ - "id": sid, - "step": step, - "percent": percent, - })); + let _ = app.emit( + "custom-races-progress", + serde_json::json!({ + "id": sid, + "step": step, + "percent": percent, + }), + ); })?; - let enabled = coa_core::modules::list(&root).iter().any(|module| module.id == "custom-races" && module.enabled); + let enabled = coa_core::modules::list(&root) + .iter() + .any(|module| module.id == "custom-races" && module.enabled); coa_core::custom_races::set_client_patch_enabled(&client, enabled) }) .await; @@ -1170,11 +1196,16 @@ async fn custom_races_install(app: AppHandle, state: State<'_, AppState>, id: St } #[tauri::command] -async fn custom_races_toggle_client(state: State<'_, AppState>, id: String, enabled: bool) -> std::result::Result<(), UiError> { +async fn custom_races_toggle_client( + state: State<'_, AppState>, + id: String, + enabled: bool, +) -> std::result::Result<(), UiError> { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; blocking(move || { - let client = linked_client(&root)?.ok_or_else(|| Error::Invalid("No game client is linked to this server.".into()))?; + let client = linked_client(&root)? + .ok_or_else(|| Error::Invalid("No game client is linked to this server.".into()))?; coa_core::custom_races::set_client_patch_enabled(&client, enabled) }) .await