diff --git a/src/auth/accounts.rs b/src/auth/accounts.rs index 1fa7c1f..300a697 100644 --- a/src/auth/accounts.rs +++ b/src/auth/accounts.rs @@ -36,14 +36,6 @@ pub struct AccountStore { } impl AccountStore { - #[cfg(test)] - pub(crate) fn empty_for_test(path: PathBuf) -> Self { - Self { - accounts: Vec::new(), - path, - } - } - pub fn load() -> Self { let path = account_store_path(); let accounts = match std::fs::read_to_string(&path) { @@ -200,177 +192,5 @@ pub fn create_offline_account(username: &str) -> Account { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn offline_uuid_has_valid_v3_shape() { - let uuid = offline_uuid("Steve"); - let parts: Vec<&str> = uuid.split('-').collect(); - assert_eq!(parts.len(), 5, "UUID must have 5 dash-separated parts"); - assert_eq!(parts[0].len(), 8); - assert_eq!(parts[1].len(), 4); - assert_eq!(parts[2].len(), 4); - assert_eq!(parts[3].len(), 4); - assert_eq!(parts[4].len(), 12); - assert!(parts[2].starts_with('3')); - let first_nibble = u8::from_str_radix(&parts[3][..1], 16).unwrap(); - assert!((0x8..=0xb).contains(&first_nibble)); - } - - #[test] - fn offline_uuid_deterministic() { - assert_eq!(offline_uuid("Steve"), offline_uuid("Steve")); - assert_eq!(offline_uuid("Alex"), offline_uuid("Alex")); - } - - #[test] - fn offline_uuid_different_for_different_names() { - assert_ne!(offline_uuid("Steve"), offline_uuid("Alex")); - } - - #[test] - fn create_offline_account_fields() { - let acc = create_offline_account("TestPlayer"); - assert_eq!(acc.username, "TestPlayer"); - assert_eq!(acc.account_type, AccountType::Offline); - assert!(!acc.active); - assert!(acc.refresh_token.is_none()); - // pin the uuid to the deterministic offline_uuid output so a regression - // in the uuid derivation (e.g. salt change) would fail this test, not - // just a non-empty-string check that any garbage would pass. - assert_eq!(acc.uuid, offline_uuid("TestPlayer")); - } - - fn make_store(dir: &std::path::Path) -> AccountStore { - AccountStore { - accounts: Vec::new(), - path: dir.join("accounts.json"), - } - } - - fn microsoft_account(name: &str) -> Account { - Account { - uuid: format!("00000000-0000-0000-0000-{:012}", name.len()), - username: name.to_owned(), - account_type: AccountType::Microsoft, - active: false, - refresh_token: Some("refresh".to_owned()), - cached_mc_token: None, - cached_mc_token_expires_at: None, - } - } - - #[test] - fn store_add_first_becomes_active() { - let tmp = tempfile::tempdir().unwrap(); - let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - assert_eq!(store.accounts.len(), 1); - assert!(store.accounts[0].active); - } - - #[test] - fn store_add_second_stays_inactive() { - let tmp = tempfile::tempdir().unwrap(); - let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); - assert_eq!(store.accounts.len(), 2); - assert!(store.accounts[0].active); - assert!(!store.accounts[1].active); - } - - #[test] - fn store_add_duplicate_uuid_replaces() { - let tmp = tempfile::tempdir().unwrap(); - let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - let mut dup = create_offline_account("Alice"); - dup.username = "AliceRenamed".to_owned(); - dup.uuid = store.accounts[0].uuid.clone(); - store.add(dup); - assert_eq!(store.accounts.len(), 1); - assert_eq!(store.accounts[0].username, "AliceRenamed"); - } - - #[test] - fn store_active_account_none_when_empty() { - let tmp = tempfile::tempdir().unwrap(); - let store = make_store(tmp.path()); - assert!(store.active_account().is_none()); - } - - #[test] - fn store_has_microsoft_account_when_one_exists() { - let tmp = tempfile::tempdir().unwrap(); - let mut store = make_store(tmp.path()); - store.add(create_offline_account("Offline")); - assert!(!store.has_microsoft_account()); - - store.add(microsoft_account("Owner")); - assert!(store.has_microsoft_account()); - } - - #[test] - fn store_active_account_returns_active() { - let tmp = tempfile::tempdir().unwrap(); - let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); - let active = store.active_account().unwrap(); - assert_eq!(active.username, "Alice"); - } - - #[test] - fn store_set_active_changes_active() { - let tmp = tempfile::tempdir().unwrap(); - let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); - store.set_active(1); - assert!(!store.accounts[0].active); - assert!(store.accounts[1].active); - } - - #[test] - fn store_remove_activates_first_remaining() { - let tmp = tempfile::tempdir().unwrap(); - let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); - store.remove(0); - assert_eq!(store.accounts.len(), 1); - assert_eq!(store.accounts[0].username, "Bob"); - assert!(store.accounts[0].active); - } - - #[test] - fn store_remove_out_of_bounds_noop() { - let tmp = tempfile::tempdir().unwrap(); - let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.remove(5); - assert_eq!(store.accounts.len(), 1); - } - - #[test] - fn store_save_and_reload() { - let tmp = tempfile::tempdir().unwrap(); - let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); - store.save(); - - let reloaded = AccountStore { - accounts: serde_json::from_str( - &std::fs::read_to_string(tmp.path().join("accounts.json")).unwrap(), - ) - .unwrap(), - path: tmp.path().join("accounts.json"), - }; - assert_eq!(reloaded.accounts.len(), 2); - assert_eq!(reloaded.accounts[0].username, "Alice"); - assert!(reloaded.accounts[0].active); - } -} +#[path = "tests/accounts.rs"] +mod tests; diff --git a/src/auth/oauth.rs b/src/auth/oauth.rs index 9efbe48..87ebae6 100644 --- a/src/auth/oauth.rs +++ b/src/auth/oauth.rs @@ -74,7 +74,7 @@ async fn run_full_oauth_flow() -> Result<(String, Option), String> { user_code: details.user_code().secret().to_owned(), verification_uri: details.verification_uri().to_string(), }); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } let token = oauth_client @@ -99,7 +99,7 @@ pub fn start_microsoft_auth() -> Arc>> { let outcome = run_full_auth_flow().await; if let Ok(mut slot) = result_clone.lock() { *slot = Some(outcome); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } }); @@ -242,57 +242,5 @@ pub async fn refresh_and_get_token( } #[cfg(test)] -mod tests { - use super::*; - - fn microsoft_account(cached_mc_token_expires_at: Option) -> Account { - Account { - uuid: "00000000-0000-0000-0000-000000000000".to_owned(), - username: "TestPlayer".to_owned(), - account_type: AccountType::Microsoft, - active: true, - refresh_token: Some("refresh".to_owned()), - cached_mc_token: Some("cached".to_owned()), - cached_mc_token_expires_at, - } - } - - #[test] - fn cached_mc_token_is_valid_before_refresh_margin() { - let now = 1_000; - let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS + 1)); - - assert_eq!(valid_cached_mc_token(&account, now), Some("cached")); - } - - #[test] - fn cached_mc_token_expires_inside_refresh_margin() { - let now = 1_000; - let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS)); - - assert!(valid_cached_mc_token(&account, now).is_none()); - } - - #[test] - fn cached_mc_token_requires_expiry() { - let account = microsoft_account(None); - - assert!(valid_cached_mc_token(&account, 1_000).is_none()); - } - - #[test] - fn profile_uuid_is_normalized_without_slicing_unicode() { - assert_eq!( - normalize_profile_uuid("0123456789abcdef0123456789abcdef"), - Some("01234567-89ab-cdef-0123-456789abcdef".to_owned()) - ); - - let unicode_id = format!("{}é{}", "a".repeat(7), "b".repeat(23)); - assert_eq!(unicode_id.len(), 32); - assert_eq!(normalize_profile_uuid(&unicode_id), None); - assert_eq!( - normalize_profile_uuid("not-a-valid-minecraft-profile-id"), - None - ); - } -} +#[path = "tests/oauth.rs"] +mod tests; diff --git a/src/auth/tests/accounts.rs b/src/auth/tests/accounts.rs new file mode 100644 index 0000000..6f482de --- /dev/null +++ b/src/auth/tests/accounts.rs @@ -0,0 +1,181 @@ +use super::*; + +impl AccountStore { + pub(crate) fn empty_for_test(path: PathBuf) -> Self { + Self { + accounts: Vec::new(), + path, + } + } +} + +#[test] +fn offline_uuid_has_valid_v3_shape() { + let uuid = offline_uuid("Steve"); + let parts: Vec<&str> = uuid.split('-').collect(); + assert_eq!(parts.len(), 5, "UUID must have 5 dash-separated parts"); + assert_eq!(parts[0].len(), 8); + assert_eq!(parts[1].len(), 4); + assert_eq!(parts[2].len(), 4); + assert_eq!(parts[3].len(), 4); + assert_eq!(parts[4].len(), 12); + assert!(parts[2].starts_with('3')); + let first_nibble = u8::from_str_radix(&parts[3][..1], 16).unwrap(); + assert!((0x8..=0xb).contains(&first_nibble)); +} + +#[test] +fn offline_uuid_deterministic() { + assert_eq!(offline_uuid("Steve"), offline_uuid("Steve")); + assert_eq!(offline_uuid("Alex"), offline_uuid("Alex")); +} + +#[test] +fn offline_uuid_different_for_different_names() { + assert_ne!(offline_uuid("Steve"), offline_uuid("Alex")); +} + +#[test] +fn create_offline_account_fields() { + let acc = create_offline_account("TestPlayer"); + assert_eq!(acc.username, "TestPlayer"); + assert_eq!(acc.account_type, AccountType::Offline); + assert!(!acc.active); + assert!(acc.refresh_token.is_none()); + // pin the uuid to the deterministic offline_uuid output so a regression + // in the uuid derivation (e.g. salt change) would fail this test, not + // just a non-empty-string check that any garbage would pass. + assert_eq!(acc.uuid, offline_uuid("TestPlayer")); +} + +fn make_store(dir: &std::path::Path) -> AccountStore { + AccountStore { + accounts: Vec::new(), + path: dir.join("accounts.json"), + } +} + +fn microsoft_account(name: &str) -> Account { + Account { + uuid: format!("00000000-0000-0000-0000-{:012}", name.len()), + username: name.to_owned(), + account_type: AccountType::Microsoft, + active: false, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: None, + cached_mc_token_expires_at: None, + } +} + +#[test] +fn store_add_first_becomes_active() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(create_offline_account("Alice")); + assert_eq!(store.accounts.len(), 1); + assert!(store.accounts[0].active); +} + +#[test] +fn store_add_second_stays_inactive() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); + assert_eq!(store.accounts.len(), 2); + assert!(store.accounts[0].active); + assert!(!store.accounts[1].active); +} + +#[test] +fn store_add_duplicate_uuid_replaces() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(create_offline_account("Alice")); + let mut dup = create_offline_account("Alice"); + dup.username = "AliceRenamed".to_owned(); + dup.uuid = store.accounts[0].uuid.clone(); + store.add(dup); + assert_eq!(store.accounts.len(), 1); + assert_eq!(store.accounts[0].username, "AliceRenamed"); +} + +#[test] +fn store_active_account_none_when_empty() { + let tmp = tempfile::tempdir().unwrap(); + let store = make_store(tmp.path()); + assert!(store.active_account().is_none()); +} + +#[test] +fn store_has_microsoft_account_when_one_exists() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(create_offline_account("Offline")); + assert!(!store.has_microsoft_account()); + + store.add(microsoft_account("Owner")); + assert!(store.has_microsoft_account()); +} + +#[test] +fn store_active_account_returns_active() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); + let active = store.active_account().unwrap(); + assert_eq!(active.username, "Alice"); +} + +#[test] +fn store_set_active_changes_active() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); + store.set_active(1); + assert!(!store.accounts[0].active); + assert!(store.accounts[1].active); +} + +#[test] +fn store_remove_activates_first_remaining() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); + store.remove(0); + assert_eq!(store.accounts.len(), 1); + assert_eq!(store.accounts[0].username, "Bob"); + assert!(store.accounts[0].active); +} + +#[test] +fn store_remove_out_of_bounds_noop() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(create_offline_account("Alice")); + store.remove(5); + assert_eq!(store.accounts.len(), 1); +} + +#[test] +fn store_save_and_reload() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(create_offline_account("Alice")); + store.add(create_offline_account("Bob")); + store.save(); + + let reloaded = AccountStore { + accounts: serde_json::from_str( + &std::fs::read_to_string(tmp.path().join("accounts.json")).unwrap(), + ) + .unwrap(), + path: tmp.path().join("accounts.json"), + }; + assert_eq!(reloaded.accounts.len(), 2); + assert_eq!(reloaded.accounts[0].username, "Alice"); + assert!(reloaded.accounts[0].active); +} diff --git a/src/auth/tests/oauth.rs b/src/auth/tests/oauth.rs new file mode 100644 index 0000000..ef8f05e --- /dev/null +++ b/src/auth/tests/oauth.rs @@ -0,0 +1,52 @@ +use super::*; + +fn microsoft_account(cached_mc_token_expires_at: Option) -> Account { + Account { + uuid: "00000000-0000-0000-0000-000000000000".to_owned(), + username: "TestPlayer".to_owned(), + account_type: AccountType::Microsoft, + active: true, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: Some("cached".to_owned()), + cached_mc_token_expires_at, + } +} + +#[test] +fn cached_mc_token_is_valid_before_refresh_margin() { + let now = 1_000; + let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS + 1)); + + assert_eq!(valid_cached_mc_token(&account, now), Some("cached")); +} + +#[test] +fn cached_mc_token_expires_inside_refresh_margin() { + let now = 1_000; + let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS)); + + assert!(valid_cached_mc_token(&account, now).is_none()); +} + +#[test] +fn cached_mc_token_requires_expiry() { + let account = microsoft_account(None); + + assert!(valid_cached_mc_token(&account, 1_000).is_none()); +} + +#[test] +fn profile_uuid_is_normalized_without_slicing_unicode() { + assert_eq!( + normalize_profile_uuid("0123456789abcdef0123456789abcdef"), + Some("01234567-89ab-cdef-0123-456789abcdef".to_owned()) + ); + + let unicode_id = format!("{}é{}", "a".repeat(7), "b".repeat(23)); + assert_eq!(unicode_id.len(), 32); + assert_eq!(normalize_profile_uuid(&unicode_id), None); + assert_eq!( + normalize_profile_uuid("not-a-valid-minecraft-profile-id"), + None + ); +} diff --git a/src/cli/account.rs b/src/cli/account.rs index 4e61a98..b9032d4 100644 --- a/src/cli/account.rs +++ b/src/cli/account.rs @@ -19,22 +19,6 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult { } } -// trait indirection so a mock store can be swapped in for tests -trait AccountStoreLike { - fn has_microsoft_account(&self) -> bool; - fn add_account(&mut self, account: Account); -} - -impl AccountStoreLike for AccountStore { - fn has_microsoft_account(&self) -> bool { - AccountStore::has_microsoft_account(self) - } - - fn add_account(&mut self, account: Account) { - self.add(account); - } -} - fn list_accounts() -> CliResult { let store = AccountStore::load(); let rows = store @@ -109,7 +93,7 @@ async fn add_microsoft_account() -> CliResult { } } -fn add_offline_account(store: &mut T, username: &str) -> CliResult { +fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult { let username = username.trim(); if username.is_empty() { return Err(io::Error::other("offline username cannot be empty").into()); @@ -121,7 +105,7 @@ fn add_offline_account(store: &mut T, username: &str) -> Cl .into()); } - store.add_account(crate::auth::create_offline_account(username)); + store.add(crate::auth::create_offline_account(username)); Ok(()) } @@ -160,63 +144,5 @@ fn find_account_index(accounts: &[Account], username: &str) -> Option { use super::utils::{confirm, required_arg}; #[cfg(test)] -mod tests { - use super::{AccountStoreLike, add_offline_account}; - use crate::auth::{Account, AccountType}; - - #[derive(Default)] - struct MockStore { - accounts: Vec, - } - - impl AccountStoreLike for MockStore { - fn has_microsoft_account(&self) -> bool { - self.accounts - .iter() - .any(|account| account.account_type == AccountType::Microsoft) - } - - fn add_account(&mut self, account: Account) { - self.accounts.push(account); - } - } - - fn microsoft_account() -> Account { - Account { - uuid: "00000000-0000-0000-0000-000000000001".to_owned(), - username: "Owner".to_owned(), - account_type: AccountType::Microsoft, - active: false, - refresh_token: Some("refresh".to_owned()), - cached_mc_token: None, - cached_mc_token_expires_at: None, - } - } - - #[test] - fn creates_offline_account_after_microsoft_account_exists() { - let mut store = MockStore::default(); - store.add_account(microsoft_account()); - add_offline_account(&mut store, "Steve").expect("offline account should be added"); - - assert_eq!(store.accounts.len(), 2); - assert_eq!(store.accounts[1].username, "Steve"); - assert_eq!(store.accounts[1].account_type, AccountType::Offline); - } - - #[test] - fn rejects_offline_account_before_microsoft_account_exists() { - let mut store = MockStore::default(); - let err = add_offline_account(&mut store, "Steve") - .expect_err("offline account should require a microsoft account"); - - assert!(err.to_string().contains("Microsoft account")); - assert!(store.accounts.is_empty()); - } - - #[test] - fn rejects_empty_offline_username() { - let mut store = MockStore::default(); - assert!(add_offline_account(&mut store, " ").is_err()); - } -} +#[path = "tests/account.rs"] +mod tests; diff --git a/src/cli/content.rs b/src/cli/content.rs index 23f0d55..71d02ed 100644 --- a/src/cli/content.rs +++ b/src/cli/content.rs @@ -116,40 +116,5 @@ fn toggle_entry( } #[cfg(test)] -mod tests { - use super::find_entry_by_stem; - use crate::instance::ContentEntry; - use std::path::PathBuf; - - fn entry(file_stem: &str) -> ContentEntry { - ContentEntry { - file_stem: file_stem.to_string(), - name: file_stem.to_string(), - source_slug: None, - installed_path: None, - provider_project: None, - title_suffix: None, - footer_label: None, - description: String::new(), - enabled: true, - icon_bytes: None, - provider_icon: false, - provider_description: false, - path: PathBuf::from(file_stem), - icon_lines: None, - } - } - - #[test] - fn matches_by_stem_case_insensitively() { - let entries = vec![entry("Sodium"), entry("Lithium")]; - let found = find_entry_by_stem(&entries, "sOdIuM").expect("entry should match"); - assert_eq!(found.file_stem, "Sodium"); - } - - #[test] - fn returns_none_for_missing_stem() { - let entries = vec![entry("Sodium")]; - assert!(find_entry_by_stem(&entries, "iris").is_none()); - } -} +#[path = "tests/content.rs"] +mod tests; diff --git a/src/cli/import.rs b/src/cli/import.rs index cbd4910..f4d46ab 100644 --- a/src/cli/import.rs +++ b/src/cli/import.rs @@ -120,4 +120,5 @@ fn select_version<'a>( } #[cfg(test)] +#[path = "tests/import.rs"] mod tests; diff --git a/src/cli/instance.rs b/src/cli/instance.rs index f5f2435..c54ab75 100644 --- a/src/cli/instance.rs +++ b/src/cli/instance.rs @@ -7,8 +7,8 @@ use clap::ArgMatches; use super::utils::{confirm, required_arg}; use crate::cli::output::{format_datetime, print_table}; +use crate::instance::runtime::RunState; use crate::instance::{InstanceManager, ModLoader}; -use crate::running::RunState; type CliResult = Result<(), Box>; const LOCAL_CONFIG_PROFILE: &str = "instance default"; @@ -143,7 +143,7 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult { // poll until the game process exits. in CLI mode this blocks here // so the user gets a proper exit code at the end. loop { - match crate::running::get(name) { + match crate::instance::runtime::get(name) { Some(RunState::Crashed(Some(code))) => { println!("Game exited with status {}", code); break; @@ -354,21 +354,5 @@ fn apply_config_update( } #[cfg(test)] -mod tests { - use super::parse_resolution; - - #[test] - fn parses_valid_resolution() { - assert_eq!( - parse_resolution("1920x1080").expect("should parse"), - (1920, 1080) - ); - } - - #[test] - fn rejects_invalid_resolution_format() { - assert!(parse_resolution("1920").is_err()); - assert!(parse_resolution("1920xa").is_err()); - assert!(parse_resolution("0x1080").is_err()); - } -} +#[path = "tests/instance.rs"] +mod tests; diff --git a/src/cli/log.rs b/src/cli/log.rs index df1e677..dfd75e2 100644 --- a/src/cli/log.rs +++ b/src/cli/log.rs @@ -20,7 +20,7 @@ pub async fn handle_log(matches: &ArgMatches) -> CliResult { fn list_logs(instance: &str) -> CliResult { let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); require_instance(&instances_dir, instance)?; - let rows = crate::instance::log_files::scan_log_files(&instances_dir, instance) + let rows = crate::instance::logs::files::scan_log_files(&instances_dir, instance) .into_iter() .map(|entry| { let size = std::fs::metadata(&entry.path) @@ -42,7 +42,7 @@ async fn show_log(matches: &ArgMatches) -> CliResult { require_instance(&instances_dir, instance)?; let path = resolve_log_path(&instances_dir, instance, file)?; - let lines = crate::instance::log_files::read_log_file(&path); + let lines = crate::instance::logs::files::read_log_file(&path); for line in &lines { println!("{}", line); } @@ -53,7 +53,7 @@ async fn show_log(matches: &ArgMatches) -> CliResult { let mut last_len = lines.len(); loop { tokio::time::sleep(Duration::from_millis(500)).await; - let new_lines = crate::instance::log_files::read_log_file(&path); + let new_lines = crate::instance::logs::files::read_log_file(&path); for line in new_lines.iter().skip(last_len) { println!("{}", line); } @@ -71,14 +71,14 @@ pub(crate) fn resolve_log_path( file: Option<&str>, ) -> Result { if let Some(name) = file { - let path = crate::instance::log_files::log_dir(instances_dir, instance).join(name); + let path = crate::instance::logs::files::log_dir(instances_dir, instance).join(name); if !path.exists() { return Err(io::Error::other(format!("log '{}' not found", name))); } return Ok(path); } - crate::instance::log_files::scan_log_files(instances_dir, instance) + crate::instance::logs::files::scan_log_files(instances_dir, instance) .into_iter() .next() .map(|entry| entry.path) @@ -88,36 +88,5 @@ pub(crate) fn resolve_log_path( use super::utils::{require_instance, required_arg}; #[cfg(test)] -mod tests { - use super::resolve_log_path; - - #[test] - fn resolves_latest_log_when_no_file_is_given() { - let tmp = tempfile::tempdir().unwrap(); - let dir = tmp.path().join("demo/minecraft/logs/launches"); - std::fs::create_dir_all(&dir).expect("log directory should exist"); - std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log"); - std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log"); - - let path = resolve_log_path(tmp.path(), "demo", None).expect("latest log should resolve"); - assert_eq!( - path.file_name().and_then(|name| name.to_str()), - Some("2024-01-02_03-04-05.log") - ); - } - - #[test] - fn resolves_named_log_file() { - let tmp = tempfile::tempdir().unwrap(); - let dir = tmp.path().join("demo/minecraft/logs/launches"); - std::fs::create_dir_all(&dir).expect("log directory should exist"); - std::fs::write(dir.join("latest.log"), "hello").expect("write named log"); - - let path = resolve_log_path(tmp.path(), "demo", Some("latest.log")) - .expect("named log should resolve"); - assert_eq!( - path.file_name().and_then(|name| name.to_str()), - Some("latest.log") - ); - } -} +#[path = "tests/log.rs"] +mod tests; diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 2659c6a..91f1571 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -289,21 +289,5 @@ fn build_content_command(name: &'static str, about: &'static str) -> Command { } #[cfg(test)] -mod tests { - use super::build_command; - - #[test] - fn parses_instance_list_subcommand() { - let matches = build_command() - .try_get_matches_from(["rmcl", "instance", "list"]) - .expect("command should parse"); - let instance = matches - .subcommand_matches("instance") - .expect("instance subcommand should be present"); - assert_eq!( - instance.subcommand_name(), - Some("list"), - "instance list should resolve to the list subcommand" - ); - } -} +#[path = "tests/arguments.rs"] +mod tests; diff --git a/src/cli/output.rs b/src/cli/output.rs index 9d8c56a..18f9f84 100644 --- a/src/cli/output.rs +++ b/src/cli/output.rs @@ -78,30 +78,5 @@ fn render_separator(widths: &[usize]) -> String { } #[cfg(test)] -mod tests { - use super::{format_datetime, render_table}; - use chrono::{TimeZone, Utc}; - - #[test] - fn render_table_aligns_columns() { - let rendered = render_table( - &["Name", "State"], - &[ - vec!["Alpha".to_string(), "enabled".to_string()], - vec!["Longer Name".to_string(), "off".to_string()], - ], - ); - - let lines: Vec<&str> = rendered.lines().collect(); - assert_eq!(lines[0], "Name State "); - assert_eq!(lines[1], "----------- -------"); - assert_eq!(lines[2], "Alpha enabled"); - assert_eq!(lines[3], "Longer Name off "); - } - - #[test] - fn formats_datetime_consistently() { - let dt = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap(); - assert_eq!(format_datetime(&dt), "2024-01-02 03:04:05 UTC"); - } -} +#[path = "tests/output.rs"] +mod tests; diff --git a/src/cli/tests/account.rs b/src/cli/tests/account.rs new file mode 100644 index 0000000..dde4529 --- /dev/null +++ b/src/cli/tests/account.rs @@ -0,0 +1,44 @@ +use super::add_offline_account; +use crate::auth::{Account, AccountStore, AccountType}; + +fn microsoft_account() -> Account { + Account { + uuid: "00000000-0000-0000-0000-000000000001".to_owned(), + username: "Owner".to_owned(), + account_type: AccountType::Microsoft, + active: false, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: None, + cached_mc_token_expires_at: None, + } +} + +#[test] +fn creates_offline_account_after_microsoft_account_exists() { + let temp = tempfile::tempdir().unwrap(); + let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json")); + store.add(microsoft_account()); + add_offline_account(&mut store, "Steve").expect("offline account should be added"); + + assert_eq!(store.accounts.len(), 2); + assert_eq!(store.accounts[1].username, "Steve"); + assert_eq!(store.accounts[1].account_type, AccountType::Offline); +} + +#[test] +fn rejects_offline_account_before_microsoft_account_exists() { + let temp = tempfile::tempdir().unwrap(); + let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json")); + let err = add_offline_account(&mut store, "Steve") + .expect_err("offline account should require a microsoft account"); + + assert!(err.to_string().contains("Microsoft account")); + assert!(store.accounts.is_empty()); +} + +#[test] +fn rejects_empty_offline_username() { + let temp = tempfile::tempdir().unwrap(); + let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json")); + assert!(add_offline_account(&mut store, " ").is_err()); +} diff --git a/src/cli/tests/arguments.rs b/src/cli/tests/arguments.rs new file mode 100644 index 0000000..d9c49f5 --- /dev/null +++ b/src/cli/tests/arguments.rs @@ -0,0 +1,16 @@ +use super::build_command; + +#[test] +fn parses_instance_list_subcommand() { + let matches = build_command() + .try_get_matches_from(["rmcl", "instance", "list"]) + .expect("command should parse"); + let instance = matches + .subcommand_matches("instance") + .expect("instance subcommand should be present"); + assert_eq!( + instance.subcommand_name(), + Some("list"), + "instance list should resolve to the list subcommand" + ); +} diff --git a/src/cli/tests/content.rs b/src/cli/tests/content.rs new file mode 100644 index 0000000..dcb55eb --- /dev/null +++ b/src/cli/tests/content.rs @@ -0,0 +1,35 @@ +use super::find_entry_by_stem; +use crate::instance::ContentEntry; +use std::path::PathBuf; + +fn entry(file_stem: &str) -> ContentEntry { + ContentEntry { + file_stem: file_stem.to_string(), + name: file_stem.to_string(), + source_slug: None, + installed_path: None, + provider_project: None, + title_suffix: None, + footer_label: None, + description: String::new(), + enabled: true, + icon_bytes: None, + provider_icon: false, + provider_description: false, + path: PathBuf::from(file_stem), + icon_lines: None, + } +} + +#[test] +fn matches_by_stem_case_insensitively() { + let entries = vec![entry("Sodium"), entry("Lithium")]; + let found = find_entry_by_stem(&entries, "sOdIuM").expect("entry should match"); + assert_eq!(found.file_stem, "Sodium"); +} + +#[test] +fn returns_none_for_missing_stem() { + let entries = vec![entry("Sodium")]; + assert!(find_entry_by_stem(&entries, "iris").is_none()); +} diff --git a/src/cli/import/tests.rs b/src/cli/tests/import.rs similarity index 100% rename from src/cli/import/tests.rs rename to src/cli/tests/import.rs diff --git a/src/cli/tests/instance.rs b/src/cli/tests/instance.rs new file mode 100644 index 0000000..05bdbf7 --- /dev/null +++ b/src/cli/tests/instance.rs @@ -0,0 +1,16 @@ +use super::parse_resolution; + +#[test] +fn parses_valid_resolution() { + assert_eq!( + parse_resolution("1920x1080").expect("should parse"), + (1920, 1080) + ); +} + +#[test] +fn rejects_invalid_resolution_format() { + assert!(parse_resolution("1920").is_err()); + assert!(parse_resolution("1920xa").is_err()); + assert!(parse_resolution("0x1080").is_err()); +} diff --git a/src/cli/tests/log.rs b/src/cli/tests/log.rs new file mode 100644 index 0000000..27018e7 --- /dev/null +++ b/src/cli/tests/log.rs @@ -0,0 +1,31 @@ +use super::resolve_log_path; + +#[test] +fn resolves_latest_log_when_no_file_is_given() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("demo/minecraft/logs/launches"); + std::fs::create_dir_all(&dir).expect("log directory should exist"); + std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log"); + std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log"); + + let path = resolve_log_path(tmp.path(), "demo", None).expect("latest log should resolve"); + assert_eq!( + path.file_name().and_then(|name| name.to_str()), + Some("2024-01-02_03-04-05.log") + ); +} + +#[test] +fn resolves_named_log_file() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("demo/minecraft/logs/launches"); + std::fs::create_dir_all(&dir).expect("log directory should exist"); + std::fs::write(dir.join("latest.log"), "hello").expect("write named log"); + + let path = + resolve_log_path(tmp.path(), "demo", Some("latest.log")).expect("named log should resolve"); + assert_eq!( + path.file_name().and_then(|name| name.to_str()), + Some("latest.log") + ); +} diff --git a/src/cli/tests/output.rs b/src/cli/tests/output.rs new file mode 100644 index 0000000..2e00a4d --- /dev/null +++ b/src/cli/tests/output.rs @@ -0,0 +1,25 @@ +use super::{format_datetime, render_table}; +use chrono::{TimeZone, Utc}; + +#[test] +fn render_table_aligns_columns() { + let rendered = render_table( + &["Name", "State"], + &[ + vec!["Alpha".to_string(), "enabled".to_string()], + vec!["Longer Name".to_string(), "off".to_string()], + ], + ); + + let lines: Vec<&str> = rendered.lines().collect(); + assert_eq!(lines[0], "Name State "); + assert_eq!(lines[1], "----------- -------"); + assert_eq!(lines[2], "Alpha enabled"); + assert_eq!(lines[3], "Longer Name off "); +} + +#[test] +fn formats_datetime_consistently() { + let dt = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap(); + assert_eq!(format_datetime(&dt), "2024-01-02 03:04:05 UTC"); +} diff --git a/src/cli/tests/version.rs b/src/cli/tests/version.rs new file mode 100644 index 0000000..8865378 --- /dev/null +++ b/src/cli/tests/version.rs @@ -0,0 +1,41 @@ +use super::filter_manifest_versions; +use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest}; +use std::collections::HashSet; + +fn manifest() -> VersionManifest { + VersionManifest { + latest: LatestVersions { + release: "1.20.1".to_string(), + snapshot: "24w01a".to_string(), + }, + versions: vec![ + VersionEntry { + id: "1.20.1".to_string(), + version_type: "release".to_string(), + url: "https://example.com/release".to_string(), + sha1: "a".to_string(), + }, + VersionEntry { + id: "24w01a".to_string(), + version_type: "snapshot".to_string(), + url: "https://example.com/snapshot".to_string(), + sha1: "b".to_string(), + }, + ], + } +} + +#[test] +fn filters_out_snapshots_by_default() { + let rows = filter_manifest_versions(&manifest(), None, false); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].id, "1.20.1"); +} + +#[test] +fn intersects_supported_versions() { + let supported = HashSet::from(["24w01a".to_string()]); + let rows = filter_manifest_versions(&manifest(), Some(&supported), true); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].id, "24w01a"); +} diff --git a/src/cli/version.rs b/src/cli/version.rs index e8b16db..4a522e2 100644 --- a/src/cli/version.rs +++ b/src/cli/version.rs @@ -96,46 +96,5 @@ fn filter_manifest_versions( } #[cfg(test)] -mod tests { - use super::filter_manifest_versions; - use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest}; - use std::collections::HashSet; - - fn manifest() -> VersionManifest { - VersionManifest { - latest: LatestVersions { - release: "1.20.1".to_string(), - snapshot: "24w01a".to_string(), - }, - versions: vec![ - VersionEntry { - id: "1.20.1".to_string(), - version_type: "release".to_string(), - url: "https://example.com/release".to_string(), - sha1: "a".to_string(), - }, - VersionEntry { - id: "24w01a".to_string(), - version_type: "snapshot".to_string(), - url: "https://example.com/snapshot".to_string(), - sha1: "b".to_string(), - }, - ], - } - } - - #[test] - fn filters_out_snapshots_by_default() { - let rows = filter_manifest_versions(&manifest(), None, false); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].id, "1.20.1"); - } - - #[test] - fn intersects_supported_versions() { - let supported = HashSet::from(["24w01a".to_string()]); - let rows = filter_manifest_versions(&manifest(), Some(&supported), true); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].id, "24w01a"); - } -} +#[path = "tests/version.rs"] +mod tests; diff --git a/src/config/mod.rs b/src/config/mod.rs index ded7787..77b8bef 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -68,56 +68,5 @@ pub static SETTINGS: LazyLock = LazyLock::new(|| { }); #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn load_config_from_valid_toml() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("config.toml"); - std::fs::write( - &path, - r#" - [defaults] - memory_max = "4G" - "#, - ) - .unwrap(); - let config = load_config(&path).unwrap(); - assert_eq!(config.defaults.memory_max, "4G"); - assert_eq!(config.defaults.memory_min, "512M"); - } - - #[test] - fn load_config_from_empty_file() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("config.toml"); - std::fs::write(&path, "").unwrap(); - let config = load_config(&path).unwrap(); - assert_eq!(config.defaults.memory_max, "2G"); - } - - #[test] - fn load_config_missing_file_uses_defaults() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("nonexistent.toml"); - load_config(&path).unwrap(); - } - - #[test] - fn load_config_partial_sections() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("config.toml"); - std::fs::write( - &path, - r#" - [paths] - instances_dir = "/custom/path" - "#, - ) - .unwrap(); - let config = load_config(&path).unwrap(); - assert_eq!(config.paths.instances_dir, "/custom/path"); - assert!(config.paths.java_path.is_none()); - } -} +#[path = "tests/loading.rs"] +mod tests; diff --git a/src/config/settings.rs b/src/config/settings.rs index 2393964..ceb5c5e 100644 --- a/src/config/settings.rs +++ b/src/config/settings.rs @@ -203,71 +203,5 @@ pub struct Config { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn effective_java_path_none_when_absent() { - let paths = Paths { - java_path: None, - ..Paths::default() - }; - assert!(paths.effective_java_path().is_none()); - } - - #[test] - fn effective_java_path_none_when_empty() { - let paths = Paths { - java_path: Some(String::new()), - ..Paths::default() - }; - assert!(paths.effective_java_path().is_none()); - } - - #[test] - fn effective_java_path_some_when_set() { - let paths = Paths { - java_path: Some("/usr/bin/java".to_owned()), - ..Paths::default() - }; - assert_eq!(paths.effective_java_path(), Some("/usr/bin/java")); - } - - #[test] - fn resolve_path_absolute() { - assert_eq!(resolve_path("/opt/rmcl"), PathBuf::from("/opt/rmcl")); - } - - #[test] - fn resolve_path_tilde_prefix() { - let resolved = resolve_path("~/games/rmcl"); - assert!(!resolved.to_string_lossy().starts_with('~')); - assert!(resolved.to_string_lossy().ends_with("games/rmcl")); - } - - #[test] - fn resolve_path_bare_tilde() { - let resolved = resolve_path("~"); - assert!(!resolved.to_string_lossy().starts_with('~')); - } - - #[test] - fn config_deserializes_from_empty_toml() { - let config: Config = toml::from_str("").unwrap(); - assert_eq!(config.defaults.memory_max, "2G"); - } - - #[test] - fn config_deserializes_partial_toml() { - let toml_str = r#" -[general] -debug = true - -[defaults] -memory_max = "8G" -"#; - let config: Config = toml::from_str(toml_str).unwrap(); - assert_eq!(config.defaults.memory_max, "8G"); - assert_eq!(config.defaults.memory_min, "512M"); - } -} +#[path = "tests/settings.rs"] +mod tests; diff --git a/src/config/tests/loading.rs b/src/config/tests/loading.rs new file mode 100644 index 0000000..b8709f3 --- /dev/null +++ b/src/config/tests/loading.rs @@ -0,0 +1,51 @@ +use super::*; + +#[test] +fn load_config_from_valid_toml() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("config.toml"); + std::fs::write( + &path, + r#" + [defaults] + memory_max = "4G" + "#, + ) + .unwrap(); + let config = load_config(&path).unwrap(); + assert_eq!(config.defaults.memory_max, "4G"); + assert_eq!(config.defaults.memory_min, "512M"); +} + +#[test] +fn load_config_from_empty_file() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("config.toml"); + std::fs::write(&path, "").unwrap(); + let config = load_config(&path).unwrap(); + assert_eq!(config.defaults.memory_max, "2G"); +} + +#[test] +fn load_config_missing_file_uses_defaults() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("nonexistent.toml"); + load_config(&path).unwrap(); +} + +#[test] +fn load_config_partial_sections() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("config.toml"); + std::fs::write( + &path, + r#" + [paths] + instances_dir = "/custom/path" + "#, + ) + .unwrap(); + let config = load_config(&path).unwrap(); + assert_eq!(config.paths.instances_dir, "/custom/path"); + assert!(config.paths.java_path.is_none()); +} diff --git a/src/config/tests/settings.rs b/src/config/tests/settings.rs new file mode 100644 index 0000000..e59666f --- /dev/null +++ b/src/config/tests/settings.rs @@ -0,0 +1,66 @@ +use super::*; + +#[test] +fn effective_java_path_none_when_absent() { + let paths = Paths { + java_path: None, + ..Paths::default() + }; + assert!(paths.effective_java_path().is_none()); +} + +#[test] +fn effective_java_path_none_when_empty() { + let paths = Paths { + java_path: Some(String::new()), + ..Paths::default() + }; + assert!(paths.effective_java_path().is_none()); +} + +#[test] +fn effective_java_path_some_when_set() { + let paths = Paths { + java_path: Some("/usr/bin/java".to_owned()), + ..Paths::default() + }; + assert_eq!(paths.effective_java_path(), Some("/usr/bin/java")); +} + +#[test] +fn resolve_path_absolute() { + assert_eq!(resolve_path("/opt/rmcl"), PathBuf::from("/opt/rmcl")); +} + +#[test] +fn resolve_path_tilde_prefix() { + let resolved = resolve_path("~/games/rmcl"); + assert!(!resolved.to_string_lossy().starts_with('~')); + assert!(resolved.to_string_lossy().ends_with("games/rmcl")); +} + +#[test] +fn resolve_path_bare_tilde() { + let resolved = resolve_path("~"); + assert!(!resolved.to_string_lossy().starts_with('~')); +} + +#[test] +fn config_deserializes_from_empty_toml() { + let config: Config = toml::from_str("").unwrap(); + assert_eq!(config.defaults.memory_max, "2G"); +} + +#[test] +fn config_deserializes_partial_toml() { + let toml_str = r#" +[general] +debug = true + +[defaults] +memory_max = "8G" +"#; + let config: Config = toml::from_str(toml_str).unwrap(); + assert_eq!(config.defaults.memory_max, "8G"); + assert_eq!(config.defaults.memory_min, "512M"); +} diff --git a/src/config/tests/theme.rs b/src/config/tests/theme.rs new file mode 100644 index 0000000..0acce86 --- /dev/null +++ b/src/config/tests/theme.rs @@ -0,0 +1,74 @@ +use super::*; + +// cover every BorderStyle variant. a mutation that swaps two arms of the +// match (e.g. Rounded -> Plain) would slip past testing just one variant. +#[rstest::rstest] +#[case::plain(BorderStyle::Plain, BorderType::Plain)] +#[case::rounded(BorderStyle::Rounded, BorderType::Rounded)] +#[case::double(BorderStyle::Double, BorderType::Double)] +#[case::thick(BorderStyle::Thick, BorderType::Thick)] +fn border_style_roundtrip(#[case] style: BorderStyle, #[case] expected: BorderType) { + assert_eq!(style.to_border_type(), expected); +} + +#[test] +fn theme_config_deserialize_builtin() { + let toml_str = r#" +theme = "dracula" +border_style = "plain" +"#; + let config: ThemeConfig = toml::from_str(toml_str).unwrap(); + assert_eq!(config.theme, "dracula"); + assert_eq!(config.border_style, BorderStyle::Plain); + assert!(config.custom.is_none()); +} + +#[test] +fn theme_config_with_partial_overrides() { + let toml_str = r#" +theme = "dracula" + +[custom] +accent = "Red" +"#; + let config: ThemeConfig = toml::from_str(toml_str).unwrap(); + assert_eq!(config.theme, "dracula"); + let overrides = config.custom.unwrap(); + assert_eq!(overrides.accent, Some(Color::Red)); + assert!(overrides.text.is_none()); +} + +#[test] +fn resolve_with_overrides_keeps_base() { + let config = ThemeConfig { + theme: "dracula".to_owned(), + custom: Some(ThemeOverrides { + accent: Some(Color::Red), + ..ThemeOverrides::default() + }), + ..ThemeConfig::default() + }; + let theme = resolve_app_theme(&config); + assert_eq!(theme.accent(), Color::Red); + let base = resolve_theme("dracula"); + assert_eq!(theme.text(), base.text()); + assert_eq!(theme.error(), base.error()); +} + +#[test] +fn resolve_builtin_theme() { + let theme = resolve_theme("dracula"); + let expected = if std::env::var_os("NO_COLOR").is_some() { + "no-color" + } else { + "dracula" + }; + assert_eq!(theme.id(), expected); +} + +#[test] +fn theme_config_empty_toml_uses_defaults() { + let config: ThemeConfig = toml::from_str("").unwrap(); + assert_eq!(config.theme, "catppuccin"); + assert_eq!(config.border_style, BorderStyle::Rounded); +} diff --git a/src/config/theme.rs b/src/config/theme.rs index 8e602d8..b6c3e0e 100644 --- a/src/config/theme.rs +++ b/src/config/theme.rs @@ -169,79 +169,5 @@ pub static BORDER_STYLE: LazyLock = LazyLock::new(|| THEME_CONFIG.border_style.clone()); #[cfg(test)] -mod tests { - use super::*; - - // cover every BorderStyle variant. a mutation that swaps two arms of the - // match (e.g. Rounded -> Plain) would slip past testing just one variant. - #[rstest::rstest] - #[case::plain(BorderStyle::Plain, BorderType::Plain)] - #[case::rounded(BorderStyle::Rounded, BorderType::Rounded)] - #[case::double(BorderStyle::Double, BorderType::Double)] - #[case::thick(BorderStyle::Thick, BorderType::Thick)] - fn border_style_roundtrip(#[case] style: BorderStyle, #[case] expected: BorderType) { - assert_eq!(style.to_border_type(), expected); - } - - #[test] - fn theme_config_deserialize_builtin() { - let toml_str = r#" -theme = "dracula" -border_style = "plain" -"#; - let config: ThemeConfig = toml::from_str(toml_str).unwrap(); - assert_eq!(config.theme, "dracula"); - assert_eq!(config.border_style, BorderStyle::Plain); - assert!(config.custom.is_none()); - } - - #[test] - fn theme_config_with_partial_overrides() { - let toml_str = r#" -theme = "dracula" - -[custom] -accent = "Red" -"#; - let config: ThemeConfig = toml::from_str(toml_str).unwrap(); - assert_eq!(config.theme, "dracula"); - let overrides = config.custom.unwrap(); - assert_eq!(overrides.accent, Some(Color::Red)); - assert!(overrides.text.is_none()); - } - - #[test] - fn resolve_with_overrides_keeps_base() { - let config = ThemeConfig { - theme: "dracula".to_owned(), - custom: Some(ThemeOverrides { - accent: Some(Color::Red), - ..ThemeOverrides::default() - }), - ..ThemeConfig::default() - }; - let theme = resolve_app_theme(&config); - assert_eq!(theme.accent(), Color::Red); - let base = resolve_theme("dracula"); - assert_eq!(theme.text(), base.text()); - assert_eq!(theme.error(), base.error()); - } - - #[test] - fn resolve_builtin_theme() { - let theme = resolve_theme("dracula"); - let expected = if std::env::var_os("NO_COLOR").is_some() { - "no-color" - } else { - "dracula" - }; - assert_eq!(theme.id(), expected); - } - - #[test] - fn theme_config_empty_toml_uses_defaults() { - let config: ThemeConfig = toml::from_str("").unwrap(); - assert_eq!(config.theme, "catppuccin"); - assert_eq!(config.border_style, BorderStyle::Rounded); - } -} +#[path = "tests/theme.rs"] +mod tests; diff --git a/src/tui/error_buffer.rs b/src/feedback/errors.rs similarity index 94% rename from src/tui/error_buffer.rs rename to src/feedback/errors.rs index 8303582..3412881 100644 --- a/src/tui/error_buffer.rs +++ b/src/feedback/errors.rs @@ -38,7 +38,7 @@ pub fn push_error(event: ErrorEvent) { while events.len() > MAX_ERROR_EVENTS { events.pop_front(); } - crate::tui::request_redraw(); + super::request_redraw(); } Err(e) => { tracing::error!("Error buffer lock poisoned: {}", e); @@ -60,7 +60,7 @@ pub fn pop_error() -> Option { Ok(mut events) => { let event = events.pop_front(); if event.is_some() { - crate::tui::request_redraw(); + super::request_redraw(); } event } @@ -86,5 +86,5 @@ pub fn peek_all_errors() -> Vec { } #[cfg(test)] -#[path = "tests/error_buffer.rs"] +#[path = "tests/errors.rs"] mod tests; diff --git a/src/feedback/mod.rs b/src/feedback/mod.rs new file mode 100644 index 0000000..0b8744f --- /dev/null +++ b/src/feedback/mod.rs @@ -0,0 +1,16 @@ +// application feedback shared by background work and every frontend. + +use std::sync::atomic::{AtomicBool, Ordering}; + +pub mod errors; +pub mod progress; + +static REDRAW_REQUESTED: AtomicBool = AtomicBool::new(true); + +pub fn request_redraw() { + REDRAW_REQUESTED.store(true, Ordering::Release); +} + +pub(crate) fn take_redraw_request() -> bool { + REDRAW_REQUESTED.swap(false, Ordering::AcqRel) +} diff --git a/src/tui/progress.rs b/src/feedback/progress.rs similarity index 94% rename from src/tui/progress.rs rename to src/feedback/progress.rs index c981948..b3474fc 100644 --- a/src/tui/progress.rs +++ b/src/feedback/progress.rs @@ -52,7 +52,7 @@ impl ProgressTask { refresh_visible(&mut state); } tracing::info!("{}", action); - crate::tui::request_redraw(); + super::request_redraw(); Self { id, finished: false, @@ -91,7 +91,7 @@ impl ProgressTask { state.tasks.remove(&self.id); refresh_visible(&mut state); } - crate::tui::request_redraw(); + super::request_redraw(); } } @@ -112,7 +112,7 @@ fn update_task_action(id: u64, text: String) { } refresh_visible(&mut state); } - crate::tui::request_redraw(); + super::request_redraw(); } fn update_task_sub_action(id: u64, text: String) { @@ -122,7 +122,7 @@ fn update_task_sub_action(id: u64, text: String) { } refresh_visible(&mut state); } - crate::tui::request_redraw(); + super::request_redraw(); } fn update_task_progress(id: u64, current: u64, total: u64) { @@ -132,7 +132,7 @@ fn update_task_progress(id: u64, current: u64, total: u64) { } refresh_visible(&mut state); } - crate::tui::request_redraw(); + super::request_redraw(); } impl Drop for ProgressTask { @@ -161,7 +161,7 @@ pub fn set_action(text: impl Into) { Ok(mut state) => { state.legacy_active = true; state.current_action = Some(text.clone()); - crate::tui::request_redraw(); + super::request_redraw(); } Err(e) => { tracing::error!("Progress lock poisoned: {}", e); @@ -174,7 +174,7 @@ pub fn set_progress(current: u64, total: u64) { match PROGRESS.lock() { Ok(mut state) => { state.progress = Some((current, total)); - crate::tui::request_redraw(); + super::request_redraw(); } Err(e) => { tracing::error!("Progress lock poisoned: {}", e); @@ -187,7 +187,7 @@ pub fn set_sub_action(text: impl Into) { match PROGRESS.lock() { Ok(mut state) => { state.sub_action = Some(text.clone()); - crate::tui::request_redraw(); + super::request_redraw(); } Err(e) => { tracing::error!("Progress lock poisoned: {}", e); @@ -201,7 +201,7 @@ pub fn clear() { Ok(mut state) => { state.legacy_active = false; refresh_visible(&mut state); - crate::tui::request_redraw(); + super::request_redraw(); } Err(e) => { tracing::error!("Progress lock poisoned: {}", e); diff --git a/src/tui/tests/error_buffer.rs b/src/feedback/tests/errors.rs similarity index 88% rename from src/tui/tests/error_buffer.rs rename to src/feedback/tests/errors.rs index 0715dd0..d687e64 100644 --- a/src/tui/tests/error_buffer.rs +++ b/src/feedback/tests/errors.rs @@ -1,5 +1,5 @@ use super::*; -use crate::tui::tests::UI_TEST_LOCK; +use crate::tests::TEST_LOCK; fn clear_errors_for_test() { ERROR_EVENTS.lock().unwrap().clear(); @@ -16,7 +16,7 @@ fn make_event(msg: &str) -> ErrorEvent { #[test] fn peek_does_not_remove() { - let _guard = UI_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); clear_errors_for_test(); push_error(make_event("peek-test")); @@ -36,7 +36,7 @@ fn peek_does_not_remove() { #[test] fn peek_all_returns_newest_first() { - let _guard = UI_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); clear_errors_for_test(); push_error(make_event("newest_a")); @@ -52,7 +52,7 @@ fn peek_all_returns_newest_first() { #[test] fn auto_assigned_ids_are_unique() { - let _guard = UI_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); clear_errors_for_test(); push_error(make_event("unique_1")); @@ -66,7 +66,7 @@ fn auto_assigned_ids_are_unique() { #[test] fn overflow_drops_oldest() { - let _guard = UI_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); clear_errors_for_test(); for i in 0..(MAX_ERROR_EVENTS + 10) { diff --git a/src/tui/tests/progress.rs b/src/feedback/tests/progress.rs similarity index 89% rename from src/tui/tests/progress.rs rename to src/feedback/tests/progress.rs index 013eff5..ded8132 100644 --- a/src/tui/tests/progress.rs +++ b/src/feedback/tests/progress.rs @@ -1,9 +1,9 @@ use super::*; -use crate::tui::tests::UI_TEST_LOCK; +use crate::tests::TEST_LOCK; #[test] fn newest_task_is_visible_and_drop_restores_previous_task() { - let _guard = UI_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); clear(); let first = ProgressTask::start("first"); first.set_progress(1, 2); @@ -24,7 +24,7 @@ fn newest_task_is_visible_and_drop_restores_previous_task() { #[test] fn changing_phase_keeps_the_existing_progress_visible() { - let _guard = UI_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); clear(); let task = ProgressTask::start("inventory"); task.set_progress(4, 10); @@ -42,7 +42,7 @@ fn changing_phase_keeps_the_existing_progress_visible() { #[test] fn clearing_legacy_progress_keeps_owned_tasks() { - let _guard = UI_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); clear(); let task = ProgressTask::start("indexing"); set_action("legacy download"); diff --git a/src/instance/config_sync.rs b/src/instance/config_sync.rs index 10ec7f3..51a44f1 100644 --- a/src/instance/config_sync.rs +++ b/src/instance/config_sync.rs @@ -110,7 +110,7 @@ pub fn switch_profile( meta_dir: &Path, instance_dir: &Path, ) -> Result, ConfigSyncError> { - if crate::running::get(instance_name).is_some() { + if crate::instance::runtime::get(instance_name).is_some() { return Err(ConfigSyncError::InstanceRunning { instance: instance_name.to_string(), }); @@ -330,316 +330,5 @@ fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn first_prepare_seeds_shared_config() { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - let minecraft = tmp.path().join("instance/minecraft"); - create_profile(&meta, "main").unwrap(); - std::fs::create_dir_all(minecraft.join("config/nested")).unwrap(); - std::fs::write(minecraft.join("options.txt"), "local-options").unwrap(); - std::fs::write(minecraft.join("optionsshaders.txt"), "shader-options").unwrap(); - std::fs::write(minecraft.join("config/options.txt"), "local-config").unwrap(); - std::fs::write(minecraft.join("config/nested/mod.toml"), "nested").unwrap(); - - assert!(prepare(Some("main"), &meta, &minecraft).unwrap()); - - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(), - "local-options" - ); - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/main/optionsshaders.txt")).unwrap(), - "shader-options" - ); - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/main/config/options.txt")).unwrap(), - "local-config" - ); - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/main/config/nested/mod.toml")) - .unwrap(), - "nested" - ); - } - - #[test] - fn prepare_mirrors_shared_config_into_instance() { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - let minecraft = tmp.path().join("instance/minecraft"); - std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap(); - std::fs::create_dir_all(minecraft.join("config")).unwrap(); - std::fs::write( - meta.join("state/profiles/main/options.txt"), - "shared-options", - ) - .unwrap(); - std::fs::write( - meta.join("state/profiles/main/config/shared.toml"), - "shared", - ) - .unwrap(); - std::fs::write(minecraft.join("options.txt"), "stale-options").unwrap(); - std::fs::write(minecraft.join("config/local.toml"), "stale").unwrap(); - - assert!(prepare(Some("main"), &meta, &minecraft).unwrap()); - - assert_eq!( - std::fs::read_to_string(minecraft.join("options.txt")).unwrap(), - "shared-options" - ); - assert_eq!( - std::fs::read_to_string(minecraft.join("config/shared.toml")).unwrap(), - "shared" - ); - assert!(!minecraft.join("config/local.toml").exists()); - } - - #[test] - fn finish_mirrors_instance_config_back_to_shared() { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - let minecraft = tmp.path().join("instance/minecraft"); - std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap(); - std::fs::write(meta.join("state/profiles/main/config/old.toml"), "old").unwrap(); - std::fs::create_dir_all(minecraft.join("config")).unwrap(); - std::fs::write(minecraft.join("options.txt"), "new-options").unwrap(); - std::fs::write(minecraft.join("config/new.toml"), "new").unwrap(); - - finish(Some("main"), &meta, &minecraft).unwrap(); - - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(), - "new-options" - ); - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/main/config/new.toml")).unwrap(), - "new" - ); - assert!(!meta.join("state/profiles/main/config/old.toml").exists()); - } - - #[test] - fn prepare_releases_lock_for_another_instance() { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - let minecraft = tmp.path().join("instance/minecraft"); - create_profile(&meta, "main").unwrap(); - std::fs::create_dir_all(minecraft.join("config")).unwrap(); - - assert!(prepare(Some("main"), &meta, &minecraft).unwrap()); - let second = tmp.path().join("second/minecraft"); - std::fs::create_dir_all(second.join("config")).unwrap(); - - assert!(prepare(Some("main"), &meta, &second).unwrap()); - } - - #[test] - fn profile_rejects_path_traversal() { - let tmp = tempfile::tempdir().unwrap(); - let err = prepare(Some("../bad"), tmp.path(), tmp.path()).unwrap_err(); - - assert!(matches!(err, ConfigSyncError::InvalidProfile(_))); - } - - #[test] - fn profile_rejects_builtin_names() { - for profile in [ - "none", - "default", - "local", - "instance default", - "local default", - ] { - let err = validate_profile(profile).unwrap_err(); - assert!(matches!(err, ConfigSyncError::InvalidProfile(_))); - } - } - - #[test] - fn prepare_ignores_deleted_profile() { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - let minecraft = tmp.path().join("instance/minecraft"); - std::fs::create_dir_all(minecraft.join("config")).unwrap(); - - let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap(); - - assert!(!lock); - assert!(!meta.join("state/profiles/deleted").exists()); - } - - #[test] - fn create_profile_trims_and_lists_profiles() { - let tmp = tempfile::tempdir().unwrap(); - - let profile = create_profile(tmp.path(), " main ").unwrap(); - let profiles = list_profiles(tmp.path()).unwrap(); - - assert_eq!(profile, "main"); - assert_eq!(profiles, vec!["main"]); - } - - #[test] - fn delete_profile_removes_profile_dir() { - let tmp = tempfile::tempdir().unwrap(); - create_profile(tmp.path(), "main").unwrap(); - - delete_profile(tmp.path(), "main").unwrap(); - - assert!(list_profiles(tmp.path()).unwrap().is_empty()); - } - - #[test] - fn switch_to_profile_backs_up_local_config_and_restores_none() { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - let instance = tmp.path().join("instance"); - let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME); - std::fs::create_dir_all(minecraft.join("config")).unwrap(); - std::fs::write(minecraft.join("options.txt"), "local-options").unwrap(); - std::fs::write(minecraft.join("config/local.txt"), "local").unwrap(); - - let selected = switch_profile("inst", None, Some("main"), &meta, &instance).unwrap(); - assert_eq!(selected.as_deref(), Some("main")); - assert_eq!( - std::fs::read_to_string(instance.join("rmcl/content/config/options.txt")).unwrap(), - "local-options" - ); - assert_eq!( - std::fs::read_to_string(instance.join("rmcl/content/config/config/local.txt")).unwrap(), - "local" - ); - - std::fs::write(minecraft.join("options.txt"), "shared-options").unwrap(); - std::fs::write(minecraft.join("config/shared.txt"), "shared").unwrap(); - let selected = switch_profile("inst", Some("main"), None, &meta, &instance).unwrap(); - - assert_eq!(selected, None); - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(), - "shared-options" - ); - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/main/config/shared.txt")).unwrap(), - "shared" - ); - assert_eq!( - std::fs::read_to_string(minecraft.join("options.txt")).unwrap(), - "local-options" - ); - assert_eq!( - std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(), - "local" - ); - assert!(!minecraft.join("config/shared.txt").exists()); - } - - #[test] - fn switch_from_deleted_profile_restores_local_without_recreating_profile() { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - let instance = tmp.path().join("instance"); - let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME); - std::fs::create_dir_all(minecraft.join("config")).unwrap(); - std::fs::create_dir_all(instance.join("rmcl/content/config/config")).unwrap(); - std::fs::write(minecraft.join("options.txt"), "deleted-profile-options").unwrap(); - std::fs::write( - instance.join("rmcl/content/config/options.txt"), - "local-options", - ) - .unwrap(); - std::fs::write( - instance.join("rmcl/content/config/config/local.txt"), - "local", - ) - .unwrap(); - - let selected = switch_profile("inst", Some("deleted"), None, &meta, &instance).unwrap(); - - assert_eq!(selected, None); - assert_eq!( - std::fs::read_to_string(minecraft.join("options.txt")).unwrap(), - "local-options" - ); - assert_eq!( - std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(), - "local" - ); - assert!(!meta.join("state/profiles/deleted").exists()); - } - - #[test] - fn switch_between_profiles_saves_old_and_loads_new() { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - let instance = tmp.path().join("instance"); - let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME); - std::fs::create_dir_all(minecraft.join("config")).unwrap(); - std::fs::write(minecraft.join("options.txt"), "changed-a-options").unwrap(); - std::fs::write(minecraft.join("config/a.txt"), "changed-a").unwrap(); - create_profile(&meta, "a").unwrap(); - std::fs::create_dir_all(meta.join("state/profiles/b/config")).unwrap(); - std::fs::write( - meta.join("state/profiles/b/options.txt"), - "profile-b-options", - ) - .unwrap(); - std::fs::write(meta.join("state/profiles/b/config/b.txt"), "profile-b").unwrap(); - - let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap(); - - assert_eq!(selected.as_deref(), Some("b")); - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/a/options.txt")).unwrap(), - "changed-a-options" - ); - assert_eq!( - std::fs::read_to_string(meta.join("state/profiles/a/config/a.txt")).unwrap(), - "changed-a" - ); - assert_eq!( - std::fs::read_to_string(minecraft.join("options.txt")).unwrap(), - "profile-b-options" - ); - assert_eq!( - std::fs::read_to_string(minecraft.join("config/b.txt")).unwrap(), - "profile-b" - ); - assert!(!minecraft.join("config/a.txt").exists()); - } - - #[test] - fn second_instance_uses_profile_options_saved_by_first_instance() { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - let first = tmp.path().join("first/minecraft"); - let second_instance = tmp.path().join("second"); - let second = second_instance.join(crate::storage::MINECRAFT_DIR_NAME); - std::fs::create_dir_all(first.join("config")).unwrap(); - std::fs::create_dir_all(second.join("config")).unwrap(); - std::fs::write(first.join("options.txt"), "first-default").unwrap(); - std::fs::write(second.join("options.txt"), "second-local").unwrap(); - create_profile(&meta, "main").unwrap(); - - assert!(prepare(Some("main"), &meta, &first).unwrap()); - std::fs::write(first.join("options.txt"), "changed-in-main").unwrap(); - finish(Some("main"), &meta, &first).unwrap(); - - switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap(); - - assert_eq!( - std::fs::read_to_string(second.join("options.txt")).unwrap(), - "changed-in-main" - ); - assert_eq!( - std::fs::read_to_string(second_instance.join("rmcl/content/config/options.txt")) - .unwrap(), - "second-local" - ); - } -} +#[path = "tests/config_sync.rs"] +mod tests; diff --git a/src/instance/content/icons.rs b/src/instance/content/icons.rs index 780554e..c0a2d6d 100644 --- a/src/instance/content/icons.rs +++ b/src/instance/content/icons.rs @@ -244,31 +244,5 @@ pub(crate) fn fallback_icon_large() -> Vec> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn quadrant_raster_has_requested_dimensions() { - let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel( - 2, - 2, - image::Rgb([12, 34, 56]), - )); - let rows = make_icon_quadrants_from_image(&image, 7, 3); - - assert_eq!(rows.len(), 3); - assert!(rows.iter().all(|row| row.len() == 7)); - assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}')); - } - - #[test] - fn fallback_icon_is_square_and_contains_a_separate_question_mark_dot() { - let icon = fallback_icon(); - - assert_eq!(icon.len(), 3); - assert!(icon.iter().all(|row| row.len() == 6)); - assert_eq!(icon[2][2].bg_r, 45); - assert_eq!(icon[2][2].fg_r, 150); - assert_eq!(icon[2][3].fg_r, 150); - } -} +#[path = "../tests/content/icons.rs"] +mod tests; diff --git a/src/instance/content/manifest.rs b/src/instance/content/manifest.rs index cfbffcd..3bd6f56 100644 --- a/src/instance/content/manifest.rs +++ b/src/instance/content/manifest.rs @@ -263,89 +263,5 @@ pub fn fingerprint_metadata(path: &Path) -> Result, path: &str) -> O } #[cfg(test)] -mod tests { - use super::*; - use std::path::PathBuf; - - fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf { - let dir = tmp - .join(instance) - .join(crate::storage::MINECRAFT_DIR_NAME) - .join("mods"); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn scan_mods_empty_dir() { - let tmp = tempfile::tempdir().unwrap(); - setup_mods_dir(tmp.path(), "inst"); - let mods = scan_mods(tmp.path(), "inst"); - assert!(mods.is_empty()); - } - - #[test] - fn scan_mods_missing_dir_returns_empty() { - let tmp = tempfile::tempdir().unwrap(); - let mods = scan_mods(tmp.path(), "ghost"); - assert!(mods.is_empty()); - } - - #[test] - fn scan_mods_enabled_disabled_flags() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - std::fs::write(dir.join("active.jar"), b"PK\x03\x04").unwrap(); - std::fs::write(dir.join("inactive.jar.disabled"), b"PK\x03\x04").unwrap(); - let mods = scan_mods(tmp.path(), "inst"); - let active = mods.iter().find(|m| m.file_stem == "active").unwrap(); - let inactive = mods.iter().find(|m| m.file_stem == "inactive").unwrap(); - assert!(active.enabled); - assert!(!inactive.enabled); - } - - #[test] - fn scan_mods_ignores_non_jar() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - std::fs::write(dir.join("readme.txt"), "not a mod").unwrap(); - std::fs::write(dir.join("config.json"), "{}").unwrap(); - std::fs::write(dir.join("real.jar"), b"PK\x03\x04").unwrap(); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods.len(), 1); - } - - #[test] - fn scan_mods_sorted_case_insensitive() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - std::fs::write(dir.join("Zebra.jar"), b"PK\x03\x04").unwrap(); - std::fs::write(dir.join("alpha.jar"), b"PK\x03\x04").unwrap(); - std::fs::write(dir.join("Beta.jar"), b"PK\x03\x04").unwrap(); - let mods = scan_mods(tmp.path(), "inst"); - let names: Vec<&str> = mods.iter().map(|m| m.name.as_str()).collect(); - assert_eq!(names, vec!["alpha", "Beta", "Zebra"]); - } - - #[test] - fn toggle_entry_enable() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let disabled_path = dir.join("mymod.jar.disabled"); - std::fs::write(&disabled_path, b"PK\x03\x04").unwrap(); - - let entry = ContentEntry { - file_stem: "mymod".to_string(), - name: "mymod".to_string(), - source_slug: None, - installed_path: None, - provider_project: None, - title_suffix: None, - footer_label: None, - description: String::new(), - enabled: false, - icon_bytes: None, - provider_icon: false, - provider_description: false, - path: disabled_path.clone(), - icon_lines: None, - }; - - toggle_entry(&entry).unwrap(); - assert!(!disabled_path.exists()); - assert!(dir.join("mymod.jar").exists()); - } - - use std::io::Write as _; - - fn make_jar(dir: &Path, name: &str, entries: &[(&str, &[u8])]) { - let path = dir.join(name); - let file = std::fs::File::create(&path).unwrap(); - let mut zip = zip::ZipWriter::new(file); - let options: zip::write::FileOptions<()> = - zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored); - for (entry_name, data) in entries { - zip.start_file(*entry_name, options).unwrap(); - zip.write_all(data).unwrap(); - } - zip.finish().unwrap(); - } - - #[test] - fn scan_mods_reads_fabric_metadata() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let meta = r#"{"name":"Fabric Mod","description":"A fabric mod","icon":"icon.png"}"#; - make_jar( - &dir, - "fabric-mod.jar", - &[("fabric.mod.json", meta.as_bytes())], - ); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods.len(), 1); - assert_eq!(mods[0].name, "Fabric Mod"); - assert_eq!(mods[0].description, "A fabric mod"); - } - - #[test] - fn scan_mods_reads_quilt_metadata() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let meta = - r#"{"quilt_loader":{"metadata":{"name":"Quilt Mod","description":"A quilt mod"}}}"#; - make_jar( - &dir, - "quilt-mod.jar", - &[("quilt.mod.json", meta.as_bytes())], - ); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods.len(), 1); - assert_eq!(mods[0].name, "Quilt Mod"); - assert_eq!(mods[0].description, "A quilt mod"); - } - - #[test] - fn scan_mods_reads_forge_toml_metadata() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let meta = r#" -logoFile = "logo.png" - -[[mods]] -displayName = "Forge Mod" -description = "A forge mod" -"#; - make_jar( - &dir, - "forge-mod.jar", - &[("META-INF/mods.toml", meta.as_bytes())], - ); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods.len(), 1); - assert_eq!(mods[0].name, "Forge Mod"); - assert_eq!(mods[0].description, "A forge mod"); - } - - #[test] - fn scan_mods_reads_neoforge_toml_metadata() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let meta = r#" -logoFile = "logo.png" - -[[mods]] -displayName = "NeoForge Mod" -description = "A neoforge mod" -"#; - make_jar( - &dir, - "neoforge-mod.jar", - &[("META-INF/neoforge.mods.toml", meta.as_bytes())], - ); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods.len(), 1); - assert_eq!(mods[0].name, "NeoForge Mod"); - assert_eq!(mods[0].description, "A neoforge mod"); - } - - #[test] - fn scan_mods_reads_mcmod_info_array() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let meta = r#"[{"name":"Legacy Mod","description":"An old forge mod"}]"#; - make_jar(&dir, "legacy-mod.jar", &[("mcmod.info", meta.as_bytes())]); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods.len(), 1); - assert_eq!(mods[0].name, "Legacy Mod"); - assert_eq!(mods[0].description, "An old forge mod"); - } - - #[test] - fn scan_mods_reads_mcmod_info_modlist() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let meta = r#"{"modList":[{"name":"Wrapped Mod","description":"Has modList wrapper"}]}"#; - make_jar(&dir, "wrapped-mod.jar", &[("mcmod.info", meta.as_bytes())]); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods.len(), 1); - assert_eq!(mods[0].name, "Wrapped Mod"); - assert_eq!(mods[0].description, "Has modList wrapper"); - } - - #[test] - fn scan_mods_prefers_fabric_over_forge() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let fabric = r#"{"name":"Fabric Name","description":"fabric desc"}"#; - let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n"; - make_jar( - &dir, - "multi.jar", - &[ - ("fabric.mod.json", fabric.as_bytes()), - ("META-INF/mods.toml", forge.as_bytes()), - ], - ); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods[0].name, "Fabric Name"); - } - - #[test] - fn scan_mods_prefers_quilt_over_forge() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let quilt = r#"{"quilt_loader":{"id":"x","version":"1","metadata":{"name":"Quilt Name","description":"quilt desc"}}}"#; - let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n"; - make_jar( - &dir, - "quilt-over-forge.jar", - &[ - ("quilt.mod.json", quilt.as_bytes()), - ("META-INF/mods.toml", forge.as_bytes()), - ], - ); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods[0].name, "Quilt Name"); - } - - #[test] - fn scan_mods_prefers_forge_toml_over_mcmod_info() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n"; - let mcmod = r#"[{"modid":"legacy","name":"Legacy Name","description":"legacy desc"}]"#; - make_jar( - &dir, - "forge-over-legacy.jar", - &[ - ("META-INF/mods.toml", forge.as_bytes()), - ("mcmod.info", mcmod.as_bytes()), - ], - ); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods[0].name, "Forge Name"); - } - - // when both neoforge.mods.toml and mods.toml exist in the same jar (the - // shape a dual-format mod might ship), the neoforge one wins because - // read_forge_toml_meta tries it first via .or_else. - #[test] - fn scan_mods_prefers_neoforge_toml_over_forge_toml() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let neoforge = - "[[mods]]\ndisplayName = \"NeoForge Name\"\ndescription = \"neoforge desc\"\n"; - let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n"; - make_jar( - &dir, - "neoforge-over-forge.jar", - &[ - ("META-INF/neoforge.mods.toml", neoforge.as_bytes()), - ("META-INF/mods.toml", forge.as_bytes()), - ], - ); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods[0].name, "NeoForge Name"); - } - - // a mods.toml with logoFile but no [[mods]] array (e.g. a dependency-only - // library jar) should still surface as a scanned mod with empty name + - // description but with the icon resolved. - #[test] - fn scan_mods_reads_mods_toml_without_mods_array() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let mods_toml = "logoFile = \"icon.png\"\n"; - let png_bytes = b"\x89PNG fake icon"; - make_jar( - &dir, - "lib-only.jar", - &[ - ("META-INF/mods.toml", mods_toml.as_bytes()), - ("icon.png", png_bytes), - ], - ); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods.len(), 1); - // file-stem fallback when metadata name is empty - covered here - // because no other test exercises an empty-name + present-logo combo. - assert_eq!(mods[0].name, "lib-only"); - assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice())); - } - - #[test] - fn scan_mods_fallback_icon_paths() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let png_bytes = b"\x89PNG fake"; - make_jar(&dir, "no-meta.jar", &[("logo.png", png_bytes)]); - let mods = scan_mods(tmp.path(), "inst"); - assert_eq!(mods.len(), 1); - assert_eq!(mods[0].name, "no-meta"); - assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice())); - } - - #[test] - fn icon_path_from_value_string() { - let val = serde_json::json!("assets/icon.png"); - assert_eq!(icon_path_from_value(&val), "assets/icon.png"); - } - - #[test] - fn icon_path_from_value_map() { - // serde_json::Map is a BTreeMap, so iteration is sorted by key. - // "128" sorts before "64" lexicographically, so the first value wins. - let val = serde_json::json!({"64": "icon_64.png", "128": "icon_128.png"}); - assert_eq!(icon_path_from_value(&val), "icon_128.png"); - } - - #[test] - fn icon_path_from_value_null() { - let val = serde_json::Value::Null; - assert_eq!(icon_path_from_value(&val), ""); - } - - #[test] - fn toggle_entry_disable() { - let tmp = tempfile::tempdir().unwrap(); - let dir = setup_mods_dir(tmp.path(), "inst"); - let enabled_path = dir.join("mymod.jar"); - std::fs::write(&enabled_path, b"PK\x03\x04").unwrap(); - - let entry = ContentEntry { - file_stem: "mymod".to_string(), - name: "mymod".to_string(), - source_slug: None, - installed_path: None, - provider_project: None, - title_suffix: None, - footer_label: None, - description: String::new(), - enabled: true, - icon_bytes: None, - provider_icon: false, - provider_description: false, - path: enabled_path.clone(), - icon_lines: None, - }; - - toggle_entry(&entry).unwrap(); - assert!(!enabled_path.exists()); - assert!(dir.join("mymod.jar.disabled").exists()); - } -} +#[path = "../tests/content/mods.rs"] +mod tests; diff --git a/src/content_provider.rs b/src/instance/content/provider.rs similarity index 95% rename from src/content_provider.rs rename to src/instance/content/provider.rs index 9bb3f0c..3f6a18c 100644 --- a/src/content_provider.rs +++ b/src/instance/content/provider.rs @@ -207,12 +207,5 @@ impl ProviderRegistry { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn registry_falls_back_to_first_capable_provider() { - let registry = ProviderRegistry::modrinth(crate::net::HttpClient::new()); - assert_eq!(registry.preferred("unknown").unwrap().id(), "modrinth"); - } -} +#[path = "../tests/content/provider.rs"] +mod tests; diff --git a/src/instance/content/reconcile.rs b/src/instance/content/reconcile.rs index 3736b4a..9e9a27b 100644 --- a/src/instance/content/reconcile.rs +++ b/src/instance/content/reconcile.rs @@ -3,14 +3,14 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, LazyLock, Mutex}; use std::time::{SystemTime, UNIX_EPOCH}; -use crate::content_provider::{FingerprintQuery, ProviderRegistry}; +use crate::feedback::progress::{ProgressTask, ProgressTaskHandle}; use crate::instance::InstanceConfig; use crate::instance::content::manifest::{ ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution, fingerprint, fingerprint_metadata, }; +use crate::instance::content::provider::{FingerprintQuery, ProviderRegistry}; use crate::storage::InstancePaths; -use crate::tui::progress::{ProgressTask, ProgressTaskHandle}; #[derive(Debug)] pub struct ReconcileResult { @@ -126,7 +126,7 @@ async fn reconcile_worker() { coordinator.scheduled.remove(&instance_name); } } - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } @@ -545,121 +545,5 @@ fn directory_fingerprint_metadata(path: &Path) -> Result ReconcileJob { - ReconcileJob { - instance: InstanceConfig { - name: name.to_owned(), - game_version: "1.21.1".to_owned(), - loader: crate::instance::ModLoader::Fabric, - loader_version: None, - created: chrono::Utc::now(), - last_played: None, - java_path: None, - memory_max: None, - memory_min: None, - jvm_args: Vec::new(), - resolution: None, - config_sync_profile: None, - }, - instances_dir: PathBuf::new(), - client: crate::net::HttpClient::new(), - } - } - - #[test] - fn coordinator_queues_instances_once_and_preserves_order() { - let mut coordinator = ReconcileCoordinator::default(); - assert!(coordinator.enqueue(job("one"), false)); - assert!(!coordinator.enqueue(job("two"), false)); - assert!(!coordinator.enqueue(job("one"), false)); - assert!(!coordinator.rerun.contains("one")); - assert!(!coordinator.enqueue(job("one"), true)); - assert_eq!(coordinator.queue.len(), 2); - assert!(coordinator.rerun.contains("one")); - assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "one"); - assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "two"); - } - - #[test] - fn oversized_content_is_kept_without_hashing_or_provider_query() { - let temp = tempfile::tempdir().unwrap(); - let minecraft = temp.path().join("minecraft"); - let resource_packs = minecraft.join("resourcepacks"); - std::fs::create_dir_all(&resource_packs).unwrap(); - let pack = resource_packs.join("large.zip"); - let file = std::fs::File::create(&pack).unwrap(); - file.set_len(2 * 1024 * 1024).unwrap(); - let manifest_path = temp.path().join("manifest.json"); - - let inventory = - reconcile_inventory(&manifest_path, &minecraft, 24, 1, &NoopProgress).unwrap(); - - assert!(inventory.queries.is_empty()); - assert_eq!(inventory.manifest.files.len(), 1); - assert!(inventory.manifest.files[0].fingerprint.hashes.is_empty()); - assert!(matches!( - inventory.manifest.files[0].resolution, - Resolution::Unmatched { .. } - )); - } - - #[test] - fn unchanged_saved_index_reuses_fingerprint_and_skips_provider_query() { - let temp = tempfile::tempdir().unwrap(); - let minecraft = temp.path().join("minecraft"); - let mods = minecraft.join("mods"); - std::fs::create_dir_all(&mods).unwrap(); - std::fs::write(mods.join("example.jar"), b"example").unwrap(); - let manifest_path = temp.path().join("manifest.json"); - - let mut first = - reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap(); - assert_eq!(first.queries.len(), 1); - let fingerprint = first.manifest.files[0].fingerprint.clone(); - first.manifest.files[0].resolution = Resolution::Unmatched { - checked_at: chrono::Utc::now().timestamp(), - providers: vec!["modrinth".to_owned()], - }; - first.manifest.save(&manifest_path).unwrap(); - - let second = - reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap(); - assert!(second.queries.is_empty()); - assert_eq!(second.manifest.files[0].fingerprint, fingerprint); - } - - #[test] - fn directory_packs_are_indexed_without_provider_queries() { - let temp = tempfile::tempdir().unwrap(); - let minecraft = temp.path().join("minecraft"); - let pack = minecraft.join("resourcepacks/example"); - std::fs::create_dir_all(&pack).unwrap(); - std::fs::write(pack.join("pack.mcmeta"), b"{}").unwrap(); - - let inventory = reconcile_inventory( - &temp.path().join("manifest.json"), - &minecraft, - 24, - 512, - &NoopProgress, - ) - .unwrap(); - - assert!(inventory.queries.is_empty()); - assert_eq!( - inventory.manifest.files[0].relative_path, - PathBuf::from("resourcepacks/example") - ); - } -} +#[path = "../tests/content/reconcile.rs"] +mod tests; diff --git a/src/instance/content/resource_packs.rs b/src/instance/content/resource_packs.rs index e8e9146..4273b53 100644 --- a/src/instance/content/resource_packs.rs +++ b/src/instance/content/resource_packs.rs @@ -13,23 +13,5 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec String { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn sanitize_keeps_alphanumeric() { - assert_eq!(sanitize("my-instance_123"), "my-instance_123"); - } - - #[test] - fn sanitize_replaces_special_chars() { - assert_eq!(sanitize("my instance!"), "my_instance_"); - assert_eq!(sanitize("path/traversal"), "path_traversal"); - } - - #[test] - #[cfg(target_os = "linux")] - fn build_content_linux() { - let content = build_content("TestPack", None); - assert!(content.contains("Name=Minecraft - TestPack")); - assert!(content.contains("Exec=rmcl instance launch \"TestPack\"")); - assert!(content.contains("Terminal=false")); - assert!(content.contains("Categories=Game;")); - } - - #[test] - #[cfg(target_os = "linux")] - fn build_content_linux_with_icon() { - let icon = PathBuf::from("/tmp/icon.png"); - let content = build_content("TestPack", Some(&icon)); - assert!(content.contains("Icon=/tmp/icon.png")); - } -} +#[path = "tests/desktop.rs"] +mod tests; diff --git a/src/instance/import/mmc.rs b/src/instance/import/mmc.rs index e53e8eb..0c9438b 100644 --- a/src/instance/import/mmc.rs +++ b/src/instance/import/mmc.rs @@ -4,9 +4,9 @@ use std::path::Path; +use crate::feedback::progress; use crate::instance::manager::InstanceManager; use crate::instance::models::ModLoader; -use crate::tui::progress; use super::{ImportSummary, PackFormat}; use serde::Deserialize; @@ -302,113 +302,5 @@ fn count_content_files(path: &Path) -> Result<(usize, usize), String> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_mmc_pack_json() { - let json = r#"{ - "formatVersion": 1, - "components": [ - { - "uid": "net.minecraft", - "version": "1.7.10", - "cachedName": "Minecraft" - }, - { - "uid": "net.minecraftforge", - "version": "10.13.4.1614", - "cachedName": "Forge" - } - ] - }"#; - let pack: MmcPack = serde_json::from_str(json).unwrap(); - assert_eq!(pack.game_version(), Some("1.7.10".to_string())); - let (loader, version) = pack.loader(); - assert_eq!(loader, Some(ModLoader::Forge)); - assert_eq!(version, Some("10.13.4.1614".to_string())); - } - - #[test] - fn parse_mmc_pack_vanilla() { - let json = r#"{ - "formatVersion": 1, - "components": [ - {"uid": "net.minecraft", "version": "1.21.4"} - ] - }"#; - let pack: MmcPack = serde_json::from_str(json).unwrap(); - assert!(pack.loader().0.is_none()); - } - - // builds an in-memory mmc-style pack zip and verifies that - // extract_mmc_archive copies only the .minecraft/ subtree into the - // destination, preserving relative paths and skipping siblings. - #[test] - fn extract_mmc_archive_copies_minecraft_subtree() { - use std::io::Write; - - let tmp = tempfile::tempdir().unwrap(); - let archive_path = tmp.path().join("pack.zip"); - let dest = tmp.path().join("instance/.minecraft"); - std::fs::create_dir_all(&dest).unwrap(); - - // Pack/ is the prefix; only .minecraft/ entries should land in dest. - // mmc-style pack: a root dir "Pack/" wrapping the .minecraft tree - // plus a sibling mmc-pack.json that should NOT be extracted. - { - let file = std::fs::File::create(&archive_path).unwrap(); - let mut zip = zip::ZipWriter::new(file); - let opts: zip::write::SimpleFileOptions = Default::default(); - - zip.start_file("Pack/mmc-pack.json", opts).unwrap(); - zip.write_all(b"{}").unwrap(); - - zip.start_file("Pack/.minecraft/options.txt", opts).unwrap(); - zip.write_all(b"lang:en_us").unwrap(); - - zip.start_file("Pack/.minecraft/mods/test-mod.jar", opts) - .unwrap(); - zip.write_all(b"jar-bytes").unwrap(); - - zip.finish().unwrap(); - } - - extract_mmc_archive(&archive_path, &dest).expect("extract"); - - // .minecraft/ entries must have been copied with their relative paths - let options = std::fs::read(dest.join("options.txt")).expect("options.txt"); - assert_eq!(options, b"lang:en_us"); - let modjar = std::fs::read(dest.join("mods/test-mod.jar")).expect("mods/test-mod.jar"); - assert_eq!(modjar, b"jar-bytes"); - - // and the sibling outside .minecraft/ must not have been copied - assert!( - !dest.join("mmc-pack.json").exists(), - "mmc-pack.json should not land in the instance dir" - ); - } - - #[test] - fn extract_mmc_archive_rejects_path_traversal() { - use std::io::Write; - - let tmp = tempfile::tempdir().unwrap(); - let archive_path = tmp.path().join("pack.zip"); - let dest = tmp.path().join("instance/minecraft"); - let file = std::fs::File::create(&archive_path).unwrap(); - let mut zip = zip::ZipWriter::new(file); - let options: zip::write::SimpleFileOptions = Default::default(); - zip.start_file("Pack/mmc-pack.json", options).unwrap(); - zip.write_all(b"{}").unwrap(); - zip.start_file("Pack/.minecraft/../../escaped.txt", options) - .unwrap(); - zip.write_all(b"escaped").unwrap(); - zip.finish().unwrap(); - - let error = extract_mmc_archive(&archive_path, &dest).unwrap_err(); - - assert!(error.to_string().contains("archive path")); - assert!(!tmp.path().join("escaped.txt").exists()); - } -} +#[path = "../tests/import/mmc.rs"] +mod tests; diff --git a/src/instance/import/mod.rs b/src/instance/import/mod.rs index 4ae6626..ae7d285 100644 --- a/src/instance/import/mod.rs +++ b/src/instance/import/mod.rs @@ -171,7 +171,7 @@ pub async fn execute_import( } fn cleanup_failed_import(manager: &InstanceManager, name: &str) { - crate::tui::progress::clear(); + crate::feedback::progress::clear(); let instance_dir = manager.instances_dir.join(name); if let Err(error) = std::fs::remove_dir_all(&instance_dir) && error.kind() != std::io::ErrorKind::NotFound @@ -185,177 +185,5 @@ fn cleanup_failed_import(manager: &InstanceManager, name: &str) { } #[cfg(test)] -mod tests { - use super::*; - use std::io::Write; - - fn make_pack_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> std::path::PathBuf { - let path = tmp.join(name); - let file = std::fs::File::create(&path).unwrap(); - let mut zip = zip::ZipWriter::new(file); - let opts: zip::write::SimpleFileOptions = Default::default(); - for (filename, bytes) in entries { - zip.start_file(*filename, opts).unwrap(); - zip.write_all(bytes).unwrap(); - } - zip.finish().unwrap(); - path - } - - #[test] - fn detect_format_recognises_mrpack() { - let tmp = tempfile::tempdir().unwrap(); - let path = make_pack_zip(tmp.path(), "pack.mrpack", &[("modrinth.index.json", b"{}")]); - assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack)); - } - - #[test] - fn detect_format_recognises_mmc_flat() { - // mmc-pack.json at the zip root - the flat layout that some mmc - // archives use. - let tmp = tempfile::tempdir().unwrap(); - let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]); - assert_eq!(detect_format(&path), Ok(PackFormat::Mmc)); - } - - #[test] - fn detect_format_recognises_mmc_nested() { - // mmc-pack.json one directory deep - the more common layout where - // the archive wraps everything in a named directory. - let tmp = tempfile::tempdir().unwrap(); - let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]); - assert_eq!(detect_format(&path), Ok(PackFormat::Mmc)); - } - - #[test] - fn detect_format_prefers_mrpack_when_both_markers_present() { - // a zip with both markers should resolve to Mrpack since the - // detector checks modrinth.index.json first. - let tmp = tempfile::tempdir().unwrap(); - let path = make_pack_zip( - tmp.path(), - "weird.zip", - &[("modrinth.index.json", b"{}"), ("mmc-pack.json", b"{}")], - ); - assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack)); - } - - #[test] - fn detect_format_errors_on_unknown_archive() { - let tmp = tempfile::tempdir().unwrap(); - let path = make_pack_zip(tmp.path(), "random.zip", &[("readme.txt", b"hello")]); - let err = detect_format(&path).unwrap_err(); - assert!( - err.contains("Unknown pack format"), - "expected unknown format error, got: {err}" - ); - } - - #[test] - fn detect_format_errors_on_missing_file() { - let tmp = tempfile::tempdir().unwrap(); - let err = detect_format(&tmp.path().join("missing.zip")).unwrap_err(); - assert!(err.contains("Cannot open"), "got: {err}"); - } - - #[test] - fn unique_name_no_collision() { - let tmp = tempfile::tempdir().unwrap(); - let name = unique_instance_name("TestPack", tmp.path()); - assert_eq!(name, "TestPack"); - } - - #[test] - fn unique_name_with_collision() { - let tmp = tempfile::tempdir().unwrap(); - let dir = tmp.path().join("TestPack"); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("instance.json"), "{}").unwrap(); - let name = unique_instance_name("TestPack", tmp.path()); - assert_eq!(name, "TestPack (2)"); - } - - #[test] - fn unique_name_multiple_collisions() { - let tmp = tempfile::tempdir().unwrap(); - for suffix in ["", " (2)", " (3)"] { - let dir = tmp.path().join(format!("TestPack{suffix}")); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("instance.json"), "{}").unwrap(); - } - let name = unique_instance_name("TestPack", tmp.path()); - assert_eq!(name, "TestPack (4)"); - } - - #[test] - fn parse_project_url() { - assert_eq!( - parse_import_input("https://modrinth.com/modpack/fabulously-optimized"), - ImportInput::ProjectSlug("fabulously-optimized".to_string()) - ); - } - - #[test] - fn parse_version_url() { - assert_eq!( - parse_import_input("https://modrinth.com/modpack/fabulously-optimized/version/abc123"), - ImportInput::VersionId { - slug: "fabulously-optimized".to_string(), - version_id: "abc123".to_string(), - } - ); - } - - #[test] - fn parse_local_mrpack() { - assert_eq!( - parse_import_input("/home/user/pack.mrpack"), - ImportInput::LocalFile("/home/user/pack.mrpack".to_string()) - ); - } - - #[test] - fn parse_local_zip() { - assert_eq!( - parse_import_input("GT_New_Horizons.zip"), - ImportInput::LocalFile("GT_New_Horizons.zip".to_string()) - ); - } - - #[test] - fn parse_tilde_path() { - assert_eq!( - parse_import_input("~/Downloads/pack.mrpack"), - ImportInput::LocalFile("~/Downloads/pack.mrpack".to_string()) - ); - } - - #[test] - fn parse_bare_slug() { - assert_eq!( - parse_import_input("fabulously-optimized"), - ImportInput::ProjectSlug("fabulously-optimized".to_string()) - ); - } - - #[test] - fn parse_input_trims_whitespace() { - assert_eq!( - parse_import_input(" fabulously-optimized "), - ImportInput::ProjectSlug("fabulously-optimized".to_string()) - ); - } - - #[test] - fn failed_import_cleanup_removes_the_partial_instance() { - let tmp = tempfile::tempdir().unwrap(); - let manager = InstanceManager::new(tmp.path().join("instances"), tmp.path().join("meta")); - let instance_dir = manager.instances_dir.join("Broken"); - std::fs::create_dir_all(&instance_dir).unwrap(); - std::fs::write(instance_dir.join("partial"), b"data").unwrap(); - - cleanup_failed_import(&manager, "Broken"); - - assert!(!instance_dir.exists()); - } -} +#[path = "../tests/import/format_detection.rs"] +mod tests; diff --git a/src/instance/import/mrpack.rs b/src/instance/import/mrpack.rs index 934a5b6..2b1b604 100644 --- a/src/instance/import/mrpack.rs +++ b/src/instance/import/mrpack.rs @@ -6,9 +6,9 @@ use std::path::Path; use serde::Deserialize; +use crate::feedback::progress; use crate::instance::manager::InstanceManager; use crate::instance::models::ModLoader; -use crate::tui::progress; use super::{ImportSummary, PackFormat}; @@ -364,4 +364,5 @@ fn extract_overrides( } #[cfg(test)] +#[path = "../tests/import/mrpack.rs"] mod tests; diff --git a/src/instance/java.rs b/src/instance/java.rs new file mode 100644 index 0000000..adbe7c8 --- /dev/null +++ b/src/instance/java.rs @@ -0,0 +1,31 @@ +// java runtime discovery shared by launching, loader installation, and settings. + +#[must_use] +pub fn detect_java_path() -> String { + if let Ok(java_home) = std::env::var("JAVA_HOME") { + 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::trace!("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::trace!("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() + } + } +} diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index e2954ef..e7085d8 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -433,8 +433,9 @@ pub async fn build_launch_invocation( .as_ref() .and_then(|d| d.artifact.as_ref()) .map(|a| PathBuf::from(&a.path)) - .or_else(|| crate::net::maven_coord_to_path(&lib.name).map(PathBuf::from)) - { + .or_else(|| { + crate::instance::loader::maven::maven_coord_to_path(&lib.name).map(PathBuf::from) + }) { Some(p) => p, None => continue, }; @@ -487,7 +488,7 @@ pub async fn build_launch_invocation( .effective_java_path() .map(str::to_owned) }) - .unwrap_or_else(crate::net::detect_java_path); + .unwrap_or_else(crate::instance::java::detect_java_path); check_java_version( &java, @@ -632,8 +633,8 @@ pub async fn launch( )?; let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>(); - crate::running::register_kill(&name, kill_tx); - crate::running::set_state(&name, crate::running::RunState::Starting); + crate::instance::runtime::register_kill(&name, kill_tx); + crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Starting); tracing::info!( "[{}] Starting Minecraft ({} {})", name, @@ -668,17 +669,17 @@ pub async fn launch( let mut child = match cmd.spawn() { Ok(c) => c, Err(e) => { - crate::running::cleanup_kill_sender(&name); - crate::running::remove(&name); + crate::instance::runtime::cleanup_kill_sender(&name); + crate::instance::runtime::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); + crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Running); - let log_file_path = crate::instance::log_files::create_log_file(instances_dir, &name); + let log_file_path = crate::instance::logs::files::create_log_file(instances_dir, &name); match &log_file_path { Some(path) => tracing::debug!( "[{}] Writing Minecraft process log to {}", @@ -803,15 +804,18 @@ pub async fn launch( tracing::warn!("Failed to sync config for '{}': {}", name_for_task, e); } if code == Some(0) || killed_by_user { - crate::running::remove(&name_for_task); + crate::instance::runtime::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 { + crate::instance::runtime::set_state( + &name_for_task, + crate::instance::runtime::RunState::Crashed(code), + ); + crate::feedback::errors::push_error(crate::feedback::errors::ErrorEvent { id: 0, level: tracing::Level::ERROR, message: match code { @@ -832,8 +836,8 @@ pub async fn launch( e ); } - crate::running::push_last_played(&name_for_task, chrono::Utc::now()); - crate::running::cleanup_kill_sender(&name_for_task); + crate::instance::runtime::push_last_played(&name_for_task, chrono::Utc::now()); + crate::instance::runtime::cleanup_kill_sender(&name_for_task); }); Ok(()) @@ -861,241 +865,9 @@ fn emit_parsed_instance_log( tracing::trace!(target: "mc_instance", "[{}] {}", instance_name, text); } } - crate::instance_logs::push_event(instance_name, event); + crate::instance::logs::live::push_event(instance_name, event); } #[cfg(test)] -mod tests { - use super::*; - - #[rstest::rstest] - #[case("openjdk version \"25.0.3\" 2026-04-21", Some(25))] - #[case("openjdk version \"21.0.11\" 2026-04-21", Some(21))] - #[case("java version \"1.8.0_402\"", Some(8))] - #[case("garbage", None)] - fn parse_java_major_version_handles_common_outputs( - #[case] output: &str, - #[case] expected: Option, - ) { - assert_eq!(parse_java_major_version(output), expected); - } - - #[test] - fn build_game_args_renders_upstream_arguments() { - use crate::launch_profile::model::{Argument, Arguments, LaunchProfile}; - use crate::launch_profile::rules::{FeatureSet, RuleContext}; - use TemplateContext; - use std::path::PathBuf; - - let lib = PathBuf::from("/m/libraries"); - let nat = PathBuf::from("/m/natives"); - let game_dir = PathBuf::from("/i/.minecraft"); - let assets = PathBuf::from("/m/assets"); - - let template_ctx = TemplateContext { - library_directory: &lib, - classpath_separator: ":", - version_name: "1.20.1", - natives_directory: &nat, - classpath: "a.jar:b.jar", - game_directory: &game_dir, - assets_root: &assets, - assets_index_name: "5", - auth_player_name: "Player", - auth_uuid: "00000000-0000-0000-0000-000000000000", - auth_access_token: "token", - auth_xuid: "0", - user_type: "msa", - user_properties: "{}", - launcher_name: "rmcl", - launcher_version: "test", - clientid: "0", - version_type: "release", - }; - let features = FeatureSet::default(); - let rule_ctx = RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &features, - }; - - let profile = LaunchProfile { - id: "1.20.1".into(), - inherits_from: None, - main_class: Some("net.minecraft.client.main.Main".into()), - libraries: Vec::new(), - arguments: Some(Arguments { - game: vec![ - Argument::Literal("--username".into()), - Argument::Literal("${auth_player_name}".into()), - ], - jvm: vec![Argument::Literal( - "-Djava.library.path=${natives_directory}".into(), - )], - }), - ..Default::default() - }; - - let (jvm, game_args) = build_game_args(&profile, &rule_ctx, &template_ctx).unwrap(); - assert_eq!(jvm, vec!["-Djava.library.path=/m/natives"]); - assert_eq!(game_args, vec!["--username", "Player"]); - } - - // exercises the early-return branch of migrate_legacy_meta_if_needed. - // a profile with either arguments or minecraftArguments is not legacy - // and must produce Ok(None) without touching the network. covers both - // shapes in one parameterised test so a regression that drops one of - // the two predicate conditions is caught. - #[rstest::rstest] - #[case::modern_arguments(true, false)] - #[case::legacy_minecraft_arguments(false, true)] - #[tokio::test] - async fn migrate_legacy_meta_skips_when_arguments_present( - #[case] modern: bool, - #[case] legacy: bool, - ) { - use crate::launch_profile::model::{Arguments, LaunchProfile}; - use tempfile::TempDir; - - let tmp = TempDir::new().unwrap(); - let meta_path = tmp.path().join("meta.json"); - std::fs::write(&meta_path, b"{}").unwrap(); - - let profile = LaunchProfile { - id: "1.20.1".into(), - main_class: Some("net.test.Main".into()), - arguments: modern.then(Arguments::default), - minecraft_arguments: legacy.then(|| "--username Player".into()), - ..Default::default() - }; - - let result = migrate_legacy_meta_if_needed(&meta_path, &profile, "1.20.1").await; - assert!( - matches!(result, Ok(None)), - "expected Ok(None) for non-legacy profile, got {result:?}" - ); - } - - // each loader maps to a distinct directory-naming branch. one rstest - // exercises every variant so a regression that misorders the match - // arms in installer_version_dir_name is caught. - #[rstest::rstest] - #[case::forge(ModLoader::Forge, "1.20.1", "47.2.0", Some("1.20.1-forge-47.2.0"))] - #[case::neoforge(ModLoader::NeoForge, "1.21.1", "21.1.0", Some("neoforge-21.1.0"))] - #[case::vanilla(ModLoader::Vanilla, "1.20.1", "v", None)] - #[case::fabric(ModLoader::Fabric, "1.20.1", "0.14.21", None)] - #[case::quilt(ModLoader::Quilt, "1.20.1", "0.20.0", None)] - fn installer_version_dir_name_per_loader( - #[case] loader: ModLoader, - #[case] game_version: &str, - #[case] loader_version: &str, - #[case] expected: Option<&str>, - ) { - assert_eq!( - installer_version_dir_name(loader, game_version, loader_version), - expected.map(str::to_owned) - ); - } - - // exercises the modern-profile early-return in - // migrate_legacy_loader_profile_if_needed. any of inheritsFrom, - // arguments, minecraftArguments present (or game_arguments absent) - // means "not legacy" and the function must return Ok(None) without - // touching the installer JSON path. - #[tokio::test] - async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() { - use LaunchProfile; - use chrono::Utc; - use tempfile::TempDir; - - let tmp = TempDir::new().unwrap(); - let instance_dir = tmp.path().join("instance"); - std::fs::create_dir_all(&instance_dir).unwrap(); - let profile_path = tmp.path().join("forge-1.20.1-47.2.0.json"); - std::fs::write(&profile_path, b"{}").unwrap(); - - let modern = LaunchProfile { - id: "1.20.1-forge-47.2.0".into(), - inherits_from: Some("1.20.1".into()), - main_class: Some("cpw.mods.bootstraplauncher.BootstrapLauncher".into()), - ..Default::default() - }; - - let config = InstanceConfig { - name: "test".into(), - game_version: "1.20.1".into(), - loader: ModLoader::Forge, - loader_version: Some("47.2.0".into()), - created: Utc::now(), - last_played: None, - java_path: None, - memory_max: None, - memory_min: None, - jvm_args: Vec::new(), - resolution: None, - config_sync_profile: None, - }; - - let result = - migrate_legacy_loader_profile_if_needed(&profile_path, &modern, &config, &instance_dir) - .await; - assert!( - matches!(result, Ok(None)), - "expected Ok(None), got {result:?}" - ); - } - - #[tokio::test] - async fn migrate_legacy_loader_profile_skips_fabric() { - // a fresh upstream Fabric profile happens to match the "legacy" - // shape (no inheritsFrom, no arguments, no minecraftArguments). - // make sure the migration helper recognises this is Fabric and - // returns Ok(None) instead of erroring with "reinstall Fabric". - use LaunchProfile; - use chrono::Utc; - use tempfile::TempDir; - - let tmp = TempDir::new().unwrap(); - let instance_dir = tmp.path().join("instance"); - std::fs::create_dir_all(&instance_dir).unwrap(); - let profile_path = tmp.path().join("fabric-1.20.1-0.14.21.json"); - std::fs::write(&profile_path, b"{}").unwrap(); - - let upstream_fabric_shape = LaunchProfile { - id: "fabric-loader-0.14.21-1.20.1".into(), - inherits_from: None, - main_class: Some("net.fabricmc.loader.impl.launch.knot.KnotClient".into()), - libraries: Vec::new(), - ..Default::default() - }; - - let config = InstanceConfig { - name: "test".into(), - game_version: "1.20.1".into(), - loader: ModLoader::Fabric, - loader_version: Some("0.14.21".into()), - created: Utc::now(), - last_played: None, - java_path: None, - memory_max: None, - memory_min: None, - jvm_args: Vec::new(), - resolution: None, - config_sync_profile: None, - }; - - let result = migrate_legacy_loader_profile_if_needed( - &profile_path, - &upstream_fabric_shape, - &config, - &instance_dir, - ) - .await; - - assert!( - matches!(result, Ok(None)), - "expected Ok(None), got {result:?}" - ); - } -} +#[path = "../tests/launch/pipeline.rs"] +mod tests; diff --git a/src/instance/launch/parser.rs b/src/instance/launch/parser.rs index adb0769..5e04b0a 100644 --- a/src/instance/launch/parser.rs +++ b/src/instance/launch/parser.rs @@ -319,107 +319,5 @@ fn level_priority(level: LogLevel) -> u8 { } #[cfg(test)] -mod tests { - use super::*; - - fn parse_all(lines: &[(LogStream, &str)]) -> Vec { - let mut parser = MinecraftLogParser::new(); - let mut events = Vec::new(); - for (stream, line) in lines { - events.extend(parser.push_line(*stream, *line)); - } - events.extend(parser.flush()); - events - } - - #[test] - fn classifies_minecraft_headers() { - let events = parse_all(&[ - (LogStream::Stdout, "[Render thread/INFO]: hello"), - (LogStream::Stdout, "[Render thread/WARN]: careful"), - (LogStream::Stdout, "[Render thread/ERROR]: broken"), - (LogStream::Stdout, "[Render thread/DEBUG]: noisy"), - (LogStream::Stdout, "[Render thread/TRACE]: tiny"), - ]); - - assert_eq!(events.len(), 5); - assert_eq!(events[0].level, LogLevel::Info); - assert_eq!(events[1].level, LogLevel::Warn); - assert_eq!(events[2].level, LogLevel::Error); - assert_eq!(events[3].level, LogLevel::Debug); - assert_eq!(events[4].level, LogLevel::Trace); - } - - #[test] - fn explicit_stderr_info_stays_info() { - let events = parse_all(&[(LogStream::Stderr, "[Render thread/INFO]: hello")]); - - assert_eq!(events[0].level, LogLevel::Info); - } - - #[test] - fn unstructured_stderr_falls_back_to_error() { - let events = parse_all(&[(LogStream::Stderr, "native library failed")]); - - assert_eq!(events[0].level, LogLevel::Error); - } - - #[test] - fn groups_java_stacktrace() { - let events = parse_all(&[ - ( - LogStream::Stderr, - "Exception in thread \"main\" java.lang.RuntimeException: boom", - ), - ( - LogStream::Stderr, - "\tat net.minecraft.client.Main.main(Main.java:42)", - ), - ( - LogStream::Stderr, - "Caused by: java.lang.IllegalStateException: bad", - ), - (LogStream::Stderr, "\tat example.Mod.load(Mod.java:7)"), - (LogStream::Stdout, "[Render thread/INFO]: after"), - ]); - - assert_eq!(events.len(), 2); - assert_eq!(events[0].level, LogLevel::Error); - assert_eq!(events[0].lines.len(), 4); - assert!( - events[0] - .java - .as_ref() - .is_some_and(|java| java.has_stacktrace) - ); - assert_eq!(events[1].level, LogLevel::Info); - } - - #[test] - fn groups_jvm_startup_failure_burst() { - let events = parse_all(&[ - (LogStream::Stderr, "Unrecognized option: --bad"), - ( - LogStream::Stderr, - "Could not create the Java Virtual Machine.", - ), - ( - LogStream::Stderr, - "A fatal exception has occurred. Program will exit.", - ), - ]); - - assert_eq!(events.len(), 1); - assert_eq!(events[0].level, LogLevel::Error); - assert_eq!(events[0].lines.len(), 3); - } - - #[test] - fn colored_header_classifies_but_keeps_original_text() { - let line = "\u{1b}[31m[Render thread/ERROR]: red\u{1b}[0m"; - let events = parse_all(&[(LogStream::Stdout, line)]); - - assert_eq!(events[0].level, LogLevel::Error); - assert_eq!(events[0].lines[0], line); - } -} +#[path = "../tests/launch/parser.rs"] +mod tests; diff --git a/src/instance/launch/patches.rs b/src/instance/launch/patches.rs index 9e5da00..cc50cf2 100644 --- a/src/instance/launch/patches.rs +++ b/src/instance/launch/patches.rs @@ -326,141 +326,5 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) { } #[cfg(test)] -mod tests { - use super::*; - use std::io::Write; - - // builds an in-memory zip with the given entries, writes it to tmp, and - // returns the path. shared by parse_add_opens tests. - fn make_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf { - let path = tmp.join(name); - let file = std::fs::File::create(&path).unwrap(); - let mut zip = zip::ZipWriter::new(file); - let opts: zip::write::SimpleFileOptions = Default::default(); - for (filename, bytes) in entries { - zip.start_file(*filename, opts).unwrap(); - zip.write_all(bytes).unwrap(); - } - zip.finish().unwrap(); - path - } - - #[test] - fn strip_replaced_libs_removes_dominated_prefixes() { - let mut classpath = vec![ - PathBuf::from("/libs/launchwrapper-1.12.jar"), - PathBuf::from("/libs/asm-all-5.0.3.jar"), - PathBuf::from("/libs/lwjgl-2.9.4.jar"), - PathBuf::from("/libs/lwjgl_util-2.9.4.jar"), - PathBuf::from("/libs/commons-compress-1.4.1.jar"), - PathBuf::from("/libs/commons-io-2.4.jar"), - PathBuf::from("/libs/guava-15.0.jar"), - // these stay - PathBuf::from("/libs/log4j-core-2.0.jar"), - PathBuf::from("/libs/guava-21.0.jar"), - ]; - strip_replaced_libs(&mut classpath); - assert_eq!( - classpath, - vec![ - PathBuf::from("/libs/log4j-core-2.0.jar"), - PathBuf::from("/libs/guava-21.0.jar"), - ] - ); - } - - #[test] - fn strip_replaced_libs_keeps_unrelated_entries() { - let mut classpath = vec![ - PathBuf::from("/libs/log4j-core-2.0.jar"), - PathBuf::from("/libs/mixin-0.8.5.jar"), - ]; - let original = classpath.clone(); - strip_replaced_libs(&mut classpath); - assert_eq!(classpath, original); - } - - #[test] - fn parse_add_opens_extracts_module_args() { - let tmp = tempfile::tempdir().unwrap(); - let manifest = - b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n"; - let zip_path = make_zip( - tmp.path(), - "patches.zip", - &[("META-INF/MANIFEST.MF", manifest)], - ); - let args = parse_add_opens(&zip_path).expect("parsed"); - assert_eq!( - args, - vec![ - "--add-opens", - "java.base/java.lang=ALL-UNNAMED", - "--add-opens", - "java.base/java.util=ALL-UNNAMED", - ] - ); - } - - #[test] - fn parse_add_opens_handles_continuation_lines() { - // jar manifests wrap long lines: the line ends with a trailing space, - // then the next physical line starts with a leading space marker. - // when joined per the MANIFEST.MF spec, the trailing space remains - // and the leading space marker is consumed, so the two values stay - // separated by exactly one space when split_whitespace runs. - let tmp = tempfile::tempdir().unwrap(); - let manifest = - b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang \n java.base/sun.security.util\n"; - let zip_path = make_zip( - tmp.path(), - "patches-continuation.zip", - &[("META-INF/MANIFEST.MF", manifest)], - ); - let args = parse_add_opens(&zip_path).expect("parsed"); - assert_eq!( - args, - vec![ - "--add-opens", - "java.base/java.lang=ALL-UNNAMED", - "--add-opens", - "java.base/sun.security.util=ALL-UNNAMED", - ] - ); - } - - #[test] - fn parse_add_opens_returns_none_when_manifest_missing() { - let tmp = tempfile::tempdir().unwrap(); - let zip_path = make_zip(tmp.path(), "no-manifest.zip", &[("other.txt", b"x")]); - assert!(parse_add_opens(&zip_path).is_none()); - } - - #[test] - fn parse_add_opens_returns_none_for_missing_file() { - let tmp = tempfile::tempdir().unwrap(); - assert!(parse_add_opens(&tmp.path().join("missing.zip")).is_none()); - } - - #[test] - fn add_lwjgl3_inserts_only_jars_that_exist() { - let tmp = tempfile::tempdir().unwrap(); - let lib_dir = tmp.path(); - - // pre-create only the lwjgl core jar; everything else absent so the - // function should skip them silently. proves we don't insert paths - // for jars that aren't there. - let core_jar = lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar"); - std::fs::create_dir_all(core_jar.parent().unwrap()).unwrap(); - std::fs::write(&core_jar, b"jar").unwrap(); - - let mut classpath = vec![PathBuf::from("/leading/forge-patches.jar")]; - add_lwjgl3(lib_dir, &mut classpath); - - // forge-patches stays at index 0; lwjgl core is inserted at index 1. - // none of the other modules existed so nothing else was added. - assert_eq!(classpath[0], PathBuf::from("/leading/forge-patches.jar")); - assert_eq!(classpath[1], core_jar); - assert_eq!(classpath.len(), 2); - } -} +#[path = "../tests/launch/patches.rs"] +mod tests; diff --git a/src/instance/loader/forge.rs b/src/instance/loader/forge.rs index 02f8ed2..85ad18a 100644 --- a/src/instance/loader/forge.rs +++ b/src/instance/loader/forge.rs @@ -6,9 +6,10 @@ use std::path::Path; use async_trait::async_trait; -use super::{GameVersion, InstallError, ModLoaderInstaller}; +use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller}; +use crate::feedback::progress::{set_action, set_sub_action}; use crate::instance::models::ModLoader; -use crate::net::{HttpClient, NetError, forge as forge_api}; +use crate::net::{HttpClient, NetError, download_file, forge as forge_api}; pub struct ForgeInstaller; @@ -60,16 +61,12 @@ impl ModLoaderInstaller for ForgeInstaller { let profile_filename = format!("forge-{game_version}-{loader_version}.json"); - if forge_api::has_legacy_install_profile(&installer_jar) { + if 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, - meta_dir, - &profile_filename, - ) - .await + if let Err(e) = + install_forge_from_profile(client, &installer_jar, meta_dir, &profile_filename) + .await { let _ = tokio::fs::remove_file(&installer_jar).await; return Err(e); @@ -80,11 +77,9 @@ impl ModLoaderInstaller for ForgeInstaller { .paths .effective_java_path() .map(str::to_owned) - .unwrap_or_else(crate::net::detect_java_path); + .unwrap_or_else(crate::instance::java::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 - { + if let Err(e) = run_forge_installer(&installer_jar, instance_dir, &java_path).await { let _ = tokio::fs::remove_file(&installer_jar).await; return Err(InstallError::Installer(e)); } @@ -107,6 +102,246 @@ impl ModLoaderInstaller for ForgeInstaller { } } +pub async fn run_forge_installer( + installer_path: &Path, + instance_dir: &Path, + java_path: &str, +) -> Result<(), InstallerError> { + use tokio::process::Command; + + set_action("Running Forge installer..."); + + let output = match Command::new(java_path) + .arg("-jar") + .arg(installer_path) + .arg("--installClient") + .current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)) + .output() + .await + { + Ok(o) => o, + Err(e) => { + tracing::debug!( + "Failed to spawn Forge installer {} with Java {}: {}", + installer_path.display(), + java_path, + e + ); + return Err(InstallerError::Io(e)); + } + }; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let detail = if stderr.trim().is_empty() { + format!("exit code {:?}", output.status.code()) + } else { + stderr.lines().last().unwrap_or("unknown error").to_string() + }; + tracing::debug!( + "Forge installer {} failed with status {:?}: {}", + installer_path.display(), + output.status.code(), + detail + ); + return Err(InstallerError::ProcessFailed(detail)); + } + + tracing::debug!("Forge installer completed successfully"); + Ok(()) +} + +// old forge installers have an install_profile.json with a "versionInfo" key +// containing everything needed. modern ones don't have this structure. +pub(crate) fn has_legacy_install_profile(installer_path: &Path) -> bool { + let file = match std::fs::File::open(installer_path) { + Ok(f) => f, + Err(_) => return false, + }; + let mut archive = match zip::ZipArchive::new(file) { + Ok(a) => a, + Err(_) => return false, + }; + let entry = match archive.by_name("install_profile.json") { + Ok(e) => e, + Err(_) => return false, + }; + let value: serde_json::Value = match serde_json::from_reader(entry) { + Ok(v) => v, + Err(_) => return false, + }; + value.get("versionInfo").is_some() +} + +// handles old-style forge installation by extracting the universal jar and +// library info directly from the installer, bypassing the GUI-only installer +pub(crate) async fn install_forge_from_profile( + client: &HttpClient, + installer_path: &Path, + meta_dir: &Path, + profile_filename: &str, +) -> Result<(), InstallError> { + use std::io::Read; + + set_action("Installing legacy Forge from profile..."); + tracing::debug!( + "Installing legacy Forge from {} into {}", + installer_path.display(), + meta_dir.display() + ); + + let file = std::fs::File::open(installer_path) + .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; + let mut archive = zip::ZipArchive::new(file).map_err(|e| { + InstallError::Installer(InstallerError::Profile(format!( + "Failed to open installer as ZIP: {e}" + ))) + })?; + + let profile_data: serde_json::Value = { + let entry = archive.by_name("install_profile.json").map_err(|e| { + InstallError::Installer(InstallerError::Profile(format!( + "install_profile.json not found in installer: {e}" + ))) + })?; + serde_json::from_reader(entry).map_err(|e| { + InstallError::Installer(InstallerError::Profile(format!( + "Failed to parse install_profile.json: {e}" + ))) + })? + }; + + let version_info = profile_data.get("versionInfo").ok_or_else(|| { + InstallError::Installer(InstallerError::Profile( + "install_profile.json missing versionInfo".into(), + )) + })?; + let install_info = profile_data.get("install").ok_or_else(|| { + InstallError::Installer(InstallerError::Profile( + "install_profile.json missing install section".into(), + )) + })?; + + let libraries = version_info + .get("libraries") + .and_then(|v| v.as_array()) + .ok_or_else(|| { + InstallError::Installer(InstallerError::Profile( + "missing versionInfo.libraries".into(), + )) + })?; + + let file_path = install_info + .get("filePath") + .and_then(|v| v.as_str()) + .ok_or_else(|| { + InstallError::Installer(InstallerError::Profile("missing install.filePath".into())) + })?; + + let install_path_coord = install_info + .get("path") + .and_then(|v| v.as_str()) + .ok_or_else(|| { + InstallError::Installer(InstallerError::Profile("missing install.path".into())) + })?; + + // extract the universal jar to the correct maven location + let universal_maven_path = crate::instance::loader::maven::maven_coord_to_path( + install_path_coord, + ) + .ok_or_else(|| { + InstallError::Installer(InstallerError::Profile(format!( + "Invalid maven coord in install.path: {install_path_coord}" + ))) + })?; + + set_sub_action("Extracting universal JAR..."); + let universal_dest = crate::storage::MetadataPaths::new(meta_dir) + .libraries() + .join(&universal_maven_path); + if let Some(parent) = universal_dest.parent() { + std::fs::create_dir_all(parent) + .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; + } + + { + let mut entry = archive.by_name(file_path).map_err(|e| { + InstallError::Installer(InstallerError::Profile(format!( + "Universal JAR '{file_path}' not found in installer: {e}" + ))) + })?; + let mut buf = Vec::new(); + entry + .read_to_end(&mut buf) + .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; + std::fs::write(&universal_dest, &buf) + .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; + tracing::debug!( + "Extracted legacy Forge universal JAR to {} ({} bytes)", + universal_dest.display(), + buf.len() + ); + } + + // download libraries needed by this forge version. libs with a url field + // are forge-hosted, libs without one are typically from mojang's library + // server. old forge versions reference libs like launchwrapper that aren't + // in mojang's modern version metadata, so we fetch those too. + let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries(); + for lib in libraries { + let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default(); + + let maven_path = match crate::instance::loader::maven::maven_coord_to_path(name) { + Some(p) => p, + None => { + return Err(InstallError::Installer(InstallerError::Profile(format!( + "Invalid Maven coordinate: {name}" + )))); + } + }; + + let dest = libraries_dir.join(&maven_path); + if dest.exists() { + tracing::trace!("Legacy Forge library already cached: {}", name); + continue; + } + + let base_url = lib + .get("url") + .and_then(|v| v.as_str()) + .unwrap_or("https://libraries.minecraft.net/") + .trim_end_matches('/'); + 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?; + } + + set_action("Saving Forge profile..."); + // write the installer's versionInfo as compact JSON. it already has the + // mainClass, the full library list (with name + url for forge-hosted + // libs), and minecraftArguments (the legacy --tweakClass etc). the + // launch flow parses this as a LaunchProfile and - if there's no + // inheritsFrom field - implicitly inherits from the configured game + // version so vanilla libraries layer in via resolve(). + // + // we use serde_json::to_vec (not the pretty-print variant via + // save_profile_json) so the written file is content-faithful: every + // field present in the installer's versionInfo round-trips. key order + // and whitespace may differ from the original installer JSON because + // the source is a serde_json::Value (which doesn't preserve order), + // but no field is silently dropped. + let serialized = serde_json::to_vec(version_info).map_err(|e| { + InstallError::Installer(InstallerError::Profile(format!( + "Failed to serialize Forge profile: {e}" + ))) + })?; + crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized) + .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; + Ok(()) +} + fn save_forge_profile( instance_dir: &Path, meta_dir: &Path, @@ -117,3 +352,7 @@ fn save_forge_profile( let profile_filename = format!("forge-{game_version}-{loader_version}.json"); super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename) } + +#[cfg(test)] +#[path = "../tests/loader/forge.rs"] +mod tests; diff --git a/src/instance/loader/maven.rs b/src/instance/loader/maven.rs new file mode 100644 index 0000000..7e93d6b --- /dev/null +++ b/src/instance/loader/maven.rs @@ -0,0 +1,27 @@ +// maven coordinate handling shared by loader installation and launch profiles. + +#[must_use] +pub fn maven_coord_to_path(coord: &str) -> Option { + let parts: Vec<&str> = coord.split(':').collect(); + match parts.as_slice() { + [group, artifact, version] => { + let group_path = group.replace('.', "/"); + Some(format!( + "{}/{}/{}/{}-{}.jar", + group_path, artifact, version, artifact, version + )) + } + [group, artifact, version, classifier] => { + let group_path = group.replace('.', "/"); + Some(format!( + "{}/{}/{}/{}-{}-{}.jar", + group_path, artifact, version, artifact, version, classifier + )) + } + _ => None, + } +} + +#[cfg(test)] +#[path = "../tests/loader/maven.rs"] +mod tests; diff --git a/src/instance/loader/mod.rs b/src/instance/loader/mod.rs index 6bb723e..18ed166 100644 --- a/src/instance/loader/mod.rs +++ b/src/instance/loader/mod.rs @@ -4,8 +4,9 @@ // though (fabric/quilt just download jars, forge/neoforge run a whole java installer). mod fabric; -mod forge; -mod neoforge; +pub mod forge; +pub mod maven; +pub mod neoforge; mod quilt; mod vanilla; @@ -138,149 +139,5 @@ pub fn get_installer(loader: ModLoader) -> Box Result<(), InstallerError> { + use tokio::process::Command; + + set_action("Running NeoForge installer..."); + + let output = match Command::new(java_path) + .arg(format!("-Duser.home={}", instance_dir.display())) + .arg("-jar") + .arg(installer_path) + .arg("--installClient") + .current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)) + .output() + .await + { + Ok(o) => o, + Err(e) => { + tracing::debug!( + "Failed to spawn NeoForge installer {} with Java {}: {}", + installer_path.display(), + java_path, + e + ); + return Err(InstallerError::Io(e)); + } + }; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let detail = stderr.lines().last().unwrap_or("").trim(); + tracing::debug!( + "NeoForge installer {} failed with status {:?}: {}", + installer_path.display(), + output.status.code(), + detail + ); + return Err(InstallerError::ProcessFailed(format!( + "NeoForge installer exited with {:?}", + output.status.code() + ))); + } + + tracing::debug!("NeoForge installer completed successfully"); + Ok(()) +} + fn save_neoforge_profile( instance_dir: &Path, meta_dir: &Path, diff --git a/src/instance/loader/vanilla.rs b/src/instance/loader/vanilla.rs index 3b56d6e..aeed8e5 100644 --- a/src/instance/loader/vanilla.rs +++ b/src/instance/loader/vanilla.rs @@ -55,38 +55,5 @@ fn game_versions_from_manifest(manifest: mojang::VersionManifest) -> Vec Vec { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn log_dir_builds_correct_path() { - let p = log_dir(Path::new("/instances"), "my-world"); - assert_eq!( - p, - PathBuf::from("/instances/my-world/minecraft/logs/launches") - ); - } -} +#[path = "../tests/logs/files.rs"] +mod tests; diff --git a/src/instance_logs.rs b/src/instance/logs/live.rs similarity index 61% rename from src/instance_logs.rs rename to src/instance/logs/live.rs index f0038e8..dfe72c1 100644 --- a/src/instance_logs.rs +++ b/src/instance/logs/live.rs @@ -68,52 +68,5 @@ pub fn clear(name: &str) { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn push_and_get_all() { - let name = "test_push_get"; - push(name, "line1"); - push(name, "line2"); - let lines = get_all(name); - assert!(lines.contains(&"line1".to_string())); - assert!(lines.contains(&"line2".to_string())); - } - - #[test] - fn get_all_missing_instance_returns_empty() { - let lines = get_all("nonexistent_instance_xyz"); - assert!(lines.is_empty()); - } - - #[test] - fn clear_removes_instance() { - let name = "test_clear"; - push(name, "data"); - assert!(!get_all(name).is_empty()); - clear(name); - assert!(get_all(name).is_empty()); - } - - #[test] - fn clear_nonexistent_is_noop() { - clear("never_existed_xyz"); - } - - #[test] - fn buffer_respects_max_lines() { - let name = "test_max_lines"; - for i in 0..(MAX_LINES + 100) { - push(name, format!("line-{i}")); - } - let lines = get_all(name); - assert_eq!(lines.len(), MAX_LINES); - assert!( - lines - .last() - .unwrap() - .contains(&format!("{}", MAX_LINES + 99)) - ); - } -} +#[path = "../tests/logs/live.rs"] +mod tests; diff --git a/src/instance/logs/mod.rs b/src/instance/logs/mod.rs new file mode 100644 index 0000000..57fac3a --- /dev/null +++ b/src/instance/logs/mod.rs @@ -0,0 +1,2 @@ +pub mod files; +pub mod live; diff --git a/src/instance/manager.rs b/src/instance/manager.rs index 82d6b0f..dcf0da6 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -277,12 +277,12 @@ impl InstanceManager { self.save(&config)?; tracing::info!("Created instance '{}'", name); - crate::tui::progress::clear(); + crate::feedback::progress::clear(); Ok(config) } pub async fn repair_runtime_cache(&self, config: &InstanceConfig) -> Result<(), InstanceError> { - let task = crate::tui::progress::ProgressTask::start(format!( + let task = crate::feedback::progress::ProgressTask::start(format!( "Rebuilding runtime for '{}'", config.name )); @@ -589,171 +589,5 @@ fn validate_name(name: &str) -> Result<(), InstanceError> { } #[cfg(test)] -mod tests { - use super::*; - use crate::instance::models::ModLoader; - use tempfile::TempDir; - - // tmp owns the temp directory; its Drop impl cleans up everything when - // the test ends. the returned InstanceManager points at tmp.path() so - // tests can join("name") off of either to refer to the same locations. - fn test_manager() -> (InstanceManager, TempDir) { - let tmp = tempfile::tempdir().unwrap(); - let meta = tmp.path().join("meta"); - std::fs::create_dir_all(&meta).unwrap(); - (InstanceManager::new(tmp.path().to_path_buf(), meta), tmp) - } - - fn dummy_config(name: &str) -> InstanceConfig { - InstanceConfig { - name: name.to_string(), - game_version: "1.20.1".to_string(), - loader: ModLoader::Vanilla, - loader_version: None, - created: chrono::Utc::now(), - last_played: None, - java_path: None, - memory_max: None, - memory_min: None, - jvm_args: vec![], - resolution: None, - config_sync_profile: None, - } - } - - #[test] - fn validate_name_accepts_safe_names() { - assert!(validate_name("my-instance").is_ok()); - assert!(validate_name("test_world").is_ok()); - } - - #[test] - fn validate_name_rejects_empty_traversal_and_hidden() { - assert!(validate_name("").is_err()); - assert!(validate_name("path/traversal").is_err()); - assert!(validate_name(".hidden").is_err()); - } - - #[test] - fn delete_missing_instance_returns_not_found() { - let (manager, _tmp) = test_manager(); - let result = manager.delete("ghost-instance"); - assert!(matches!(result, Err(InstanceError::NotFound(_)))); - } - - #[test] - fn save_then_load_all_round_trips_config() { - let (manager, tmp) = test_manager(); - std::fs::create_dir_all(tmp.path().join("test-save")).unwrap(); - manager.save(&dummy_config("test-save")).expect("save"); - - let all = manager.load_all(); - assert_eq!(all.len(), 1); - assert_eq!(all[0].name, "test-save"); - assert_eq!(all[0].game_version, "1.20.1"); - } - - #[test] - fn load_all_accepts_numeric_memory() { - let (manager, tmp) = test_manager(); - let instance_dir = tmp.path().join("test-memory"); - std::fs::create_dir_all(&instance_dir).unwrap(); - std::fs::write( - instance_dir.join("instance.json"), - r#"{ - "name": "test-memory", - "game_version": "1.7.10", - "loader": "forge", - "loader_version": "10.13.4.1614", - "created": "2026-04-20T18:04:25.567993893Z", - "memory_max": 8, - "memory_min": 512 -}"#, - ) - .expect("write config"); - - let all = manager.load_all(); - assert_eq!(all.len(), 1); - assert_eq!(all[0].memory_max.as_deref(), Some("8G")); - assert_eq!(all[0].memory_min.as_deref(), Some("512M")); - } - - #[test] - fn load_one_missing_returns_not_found() { - let (manager, _tmp) = test_manager(); - let result = manager.load_one("ghost-instance"); - assert!(matches!(result, Err(InstanceError::NotFound(_)))); - } - - #[test] - fn rename_moves_dir_and_updates_config_name() { - let (manager, tmp) = test_manager(); - let old_dir = tmp.path().join("old-name"); - std::fs::create_dir_all(&old_dir).unwrap(); - manager.save(&dummy_config("old-name")).expect("save"); - - manager.rename("old-name", "new-name").expect("rename"); - - assert!(!old_dir.exists(), "old dir should be gone"); - let new_dir = tmp.path().join("new-name"); - assert!(new_dir.exists(), "new dir should exist"); - let reloaded = manager.load_one("new-name").expect("load_one new-name"); - assert_eq!(reloaded.name, "new-name"); - } - - #[test] - fn rename_to_same_name_is_noop() { - let (manager, tmp) = test_manager(); - let dir = tmp.path().join("same"); - std::fs::create_dir_all(&dir).unwrap(); - manager.save(&dummy_config("same")).expect("save"); - manager.rename("same", "same").expect("noop rename"); - assert!(dir.exists()); - } - - #[test] - fn rename_empty_target_rejects() { - let (manager, tmp) = test_manager(); - std::fs::create_dir_all(tmp.path().join("orig")).unwrap(); - manager.save(&dummy_config("orig")).expect("save"); - let err = manager.rename("orig", " ").unwrap_err(); - assert!(matches!(err, InstanceError::InvalidName(_))); - } - - #[test] - fn rename_missing_source_errors() { - let (manager, _tmp) = test_manager(); - let err = manager.rename("ghost", "anything").unwrap_err(); - assert!(matches!(err, InstanceError::NotFound(_))); - } - - #[test] - fn rename_target_exists_errors() { - let (manager, tmp) = test_manager(); - std::fs::create_dir_all(tmp.path().join("source")).unwrap(); - std::fs::create_dir_all(tmp.path().join("collision")).unwrap(); - manager.save(&dummy_config("source")).expect("save src"); - manager.save(&dummy_config("collision")).expect("save dst"); - let err = manager.rename("source", "collision").unwrap_err(); - assert!(matches!(err, InstanceError::AlreadyExists(_))); - } - - #[test] - fn touch_last_played_updates_field() { - let (manager, tmp) = test_manager(); - std::fs::create_dir_all(tmp.path().join("ticker")).unwrap(); - manager.save(&dummy_config("ticker")).expect("save"); - assert!(manager.load_one("ticker").unwrap().last_played.is_none()); - - manager.touch_last_played("ticker").expect("touch"); - let reloaded = manager.load_one("ticker").unwrap(); - let stamp = reloaded - .last_played - .expect("last_played should be Some now"); - let age = chrono::Utc::now() - stamp; - assert!( - age.num_seconds().abs() < 5, - "last_played should be roughly now, got age {age:?}" - ); - } -} +#[path = "tests/manager.rs"] +mod tests; diff --git a/src/instance/mod.rs b/src/instance/mod.rs index 45a5018..50c620e 100644 --- a/src/instance/mod.rs +++ b/src/instance/mod.rs @@ -5,13 +5,17 @@ pub mod config_sync; pub mod content; pub mod desktop; pub mod import; +pub mod java; pub mod launch; pub mod loader; -pub mod log_files; +pub mod logs; pub mod manager; pub mod models; +pub mod runtime; pub mod screenshots; +pub use logs::files as log_files; + pub use content::manifest::{ ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution, }; diff --git a/src/instance/models.rs b/src/instance/models.rs index 05b2273..34bbf37 100644 --- a/src/instance/models.rs +++ b/src/instance/models.rs @@ -122,84 +122,5 @@ fn memory_number_to_string(value: u64) -> Option { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn instance_config_roundtrips_through_json() { - let config = InstanceConfig { - name: "test".to_string(), - game_version: "1.20.1".to_string(), - loader: ModLoader::Fabric, - loader_version: Some("0.15.0".to_string()), - created: Utc::now(), - last_played: None, - java_path: None, - memory_max: Some("4G".to_string()), - memory_min: Some("512M".to_string()), - jvm_args: vec![], - resolution: Some((1920, 1080)), - config_sync_profile: None, - }; - let json = serde_json::to_string_pretty(&config).expect("serialize"); - let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize"); - assert_eq!(parsed.name, config.name); - assert_eq!(parsed.game_version, config.game_version); - assert_eq!(parsed.loader, config.loader); - assert_eq!(parsed.resolution, config.resolution); - } - - #[test] - fn instance_config_accepts_numeric_memory() { - let json = r#" - { - "name": "test", - "game_version": "1.7.10", - "loader": "forge", - "loader_version": "10.13.4.1614", - "created": "2026-04-20T18:04:25.567993893Z", - "memory_max": 8, - "memory_min": 512 - } - "#; - let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize"); - assert_eq!(parsed.memory_max.as_deref(), Some("8G")); - assert_eq!(parsed.memory_min.as_deref(), Some("512M")); - } - - #[test] - fn normalize_memory_value_handles_bare_numbers() { - assert_eq!(normalize_memory_value("8").as_deref(), Some("8G")); - assert_eq!(normalize_memory_value("4096").as_deref(), Some("4096M")); - assert_eq!(normalize_memory_value("8G").as_deref(), Some("8G")); - assert_eq!(normalize_memory_value("2048m").as_deref(), Some("2048M")); - assert_eq!(normalize_memory_value(""), None); - } - - #[test] - fn instance_config_ignores_invalid_memory_values() { - let json = r#" - { - "name": "test", - "game_version": "1.7.10", - "loader": "forge", - "loader_version": "10.13.4.1614", - "created": "2026-04-20T18:04:25.567993893Z", - "memory_max": ["8G"], - "memory_min": "8GB" - } - "#; - let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize"); - assert_eq!(parsed.memory_max, None); - assert_eq!(parsed.memory_min, None); - } - - #[test] - fn normalize_memory_value_rejects_invalid_values() { - assert_eq!(normalize_memory_value("0"), None); - assert_eq!(normalize_memory_value("-1"), None); - assert_eq!(normalize_memory_value("1.5G"), None); - assert_eq!(normalize_memory_value("8GB"), None); - assert_eq!(normalize_memory_value("banana"), None); - } -} +#[path = "tests/models.rs"] +mod tests; diff --git a/src/running.rs b/src/instance/runtime.rs similarity index 54% rename from src/running.rs rename to src/instance/runtime.rs index cffab0f..c1d1055 100644 --- a/src/running.rs +++ b/src/instance/runtime.rs @@ -33,14 +33,14 @@ pub static KILL_SENDERS: LazyLock = pub fn set_state(name: &str, state: RunState) { if let Ok(mut map) = RUNNING.lock() { map.insert(name.to_string(), state); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } pub fn remove(name: &str) { if let Ok(mut map) = RUNNING.lock() { map.remove(name); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } @@ -73,7 +73,7 @@ pub fn has_active() -> bool { pub fn push_last_played(name: &str, time: DateTime) { if let Ok(mut q) = PENDING_LAST_PLAYED.lock() { q.push((name.to_string(), time)); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } @@ -108,80 +108,5 @@ pub fn cleanup_kill_sender(name: &str) { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn set_and_get_state() { - set_state("run_test_1", RunState::Starting); - assert_eq!(get("run_test_1"), Some(RunState::Starting)); - } - - #[test] - fn get_missing_returns_none() { - assert_eq!(get("run_never_set_xyz"), None); - } - - #[test] - fn remove_clears_state() { - set_state("run_test_2", RunState::Running); - remove("run_test_2"); - assert_eq!(get("run_test_2"), None); - } - - #[test] - fn set_state_overwrites() { - set_state("run_test_3", RunState::Starting); - set_state("run_test_3", RunState::Running); - assert_eq!(get("run_test_3"), Some(RunState::Running)); - } - - #[test] - fn all_returns_entries() { - set_state("run_test_all_a", RunState::Running); - let entries = all(); - assert!(entries.iter().any(|(k, _)| k == "run_test_all_a")); - } - - #[test] - fn crashed_state_stores_exit_code() { - set_state("run_test_crash", RunState::Crashed(Some(1))); - assert_eq!(get("run_test_crash"), Some(RunState::Crashed(Some(1)))); - } - - #[test] - fn push_and_drain_last_played() { - let time = Utc::now(); - push_last_played("run_test_lp", time); - let drained = drain_last_played(); - assert!(drained.iter().any(|(k, _)| k == "run_test_lp")); - } - - // Removed drain_empty_returns_empty: it relied on no other test pushing - // to LAST_PLAYED between the two drain calls, which races with the - // parallel push_and_drain_last_played test. The drain semantics are - // already covered by push_and_drain_last_played, which asserts a - // specific entry is present, and the empty-result path is exercised - // implicitly any time drain runs after that test's cleanup. - - #[test] - fn send_kill_returns_false_for_missing() { - assert!(!send_kill("run_never_registered_xyz")); - } - - #[test] - fn register_and_send_kill() { - let (tx, mut rx) = tokio::sync::oneshot::channel::<()>(); - register_kill("run_test_kill", tx); - assert!(send_kill("run_test_kill")); - let _ = rx.try_recv(); - } - - #[test] - fn cleanup_kill_sender_removes() { - let (tx, _rx) = tokio::sync::oneshot::channel::<()>(); - register_kill("run_test_cleanup", tx); - cleanup_kill_sender("run_test_cleanup"); - assert!(!send_kill("run_test_cleanup")); - } -} +#[path = "tests/runtime.rs"] +mod tests; diff --git a/src/instance/tests/config_sync.rs b/src/instance/tests/config_sync.rs new file mode 100644 index 0000000..34903f0 --- /dev/null +++ b/src/instance/tests/config_sync.rs @@ -0,0 +1,309 @@ +use super::*; + +#[test] +fn first_prepare_seeds_shared_config() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let minecraft = tmp.path().join("instance/minecraft"); + create_profile(&meta, "main").unwrap(); + std::fs::create_dir_all(minecraft.join("config/nested")).unwrap(); + std::fs::write(minecraft.join("options.txt"), "local-options").unwrap(); + std::fs::write(minecraft.join("optionsshaders.txt"), "shader-options").unwrap(); + std::fs::write(minecraft.join("config/options.txt"), "local-config").unwrap(); + std::fs::write(minecraft.join("config/nested/mod.toml"), "nested").unwrap(); + + assert!(prepare(Some("main"), &meta, &minecraft).unwrap()); + + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(), + "local-options" + ); + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/main/optionsshaders.txt")).unwrap(), + "shader-options" + ); + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/main/config/options.txt")).unwrap(), + "local-config" + ); + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/main/config/nested/mod.toml")).unwrap(), + "nested" + ); +} + +#[test] +fn prepare_mirrors_shared_config_into_instance() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let minecraft = tmp.path().join("instance/minecraft"); + std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap(); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + std::fs::write( + meta.join("state/profiles/main/options.txt"), + "shared-options", + ) + .unwrap(); + std::fs::write( + meta.join("state/profiles/main/config/shared.toml"), + "shared", + ) + .unwrap(); + std::fs::write(minecraft.join("options.txt"), "stale-options").unwrap(); + std::fs::write(minecraft.join("config/local.toml"), "stale").unwrap(); + + assert!(prepare(Some("main"), &meta, &minecraft).unwrap()); + + assert_eq!( + std::fs::read_to_string(minecraft.join("options.txt")).unwrap(), + "shared-options" + ); + assert_eq!( + std::fs::read_to_string(minecraft.join("config/shared.toml")).unwrap(), + "shared" + ); + assert!(!minecraft.join("config/local.toml").exists()); +} + +#[test] +fn finish_mirrors_instance_config_back_to_shared() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let minecraft = tmp.path().join("instance/minecraft"); + std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap(); + std::fs::write(meta.join("state/profiles/main/config/old.toml"), "old").unwrap(); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + std::fs::write(minecraft.join("options.txt"), "new-options").unwrap(); + std::fs::write(minecraft.join("config/new.toml"), "new").unwrap(); + + finish(Some("main"), &meta, &minecraft).unwrap(); + + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(), + "new-options" + ); + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/main/config/new.toml")).unwrap(), + "new" + ); + assert!(!meta.join("state/profiles/main/config/old.toml").exists()); +} + +#[test] +fn prepare_releases_lock_for_another_instance() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let minecraft = tmp.path().join("instance/minecraft"); + create_profile(&meta, "main").unwrap(); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + + assert!(prepare(Some("main"), &meta, &minecraft).unwrap()); + let second = tmp.path().join("second/minecraft"); + std::fs::create_dir_all(second.join("config")).unwrap(); + + assert!(prepare(Some("main"), &meta, &second).unwrap()); +} + +#[test] +fn profile_rejects_path_traversal() { + let tmp = tempfile::tempdir().unwrap(); + let err = prepare(Some("../bad"), tmp.path(), tmp.path()).unwrap_err(); + + assert!(matches!(err, ConfigSyncError::InvalidProfile(_))); +} + +#[test] +fn profile_rejects_builtin_names() { + for profile in [ + "none", + "default", + "local", + "instance default", + "local default", + ] { + let err = validate_profile(profile).unwrap_err(); + assert!(matches!(err, ConfigSyncError::InvalidProfile(_))); + } +} + +#[test] +fn prepare_ignores_deleted_profile() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let minecraft = tmp.path().join("instance/minecraft"); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + + let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap(); + + assert!(!lock); + assert!(!meta.join("state/profiles/deleted").exists()); +} + +#[test] +fn create_profile_trims_and_lists_profiles() { + let tmp = tempfile::tempdir().unwrap(); + + let profile = create_profile(tmp.path(), " main ").unwrap(); + let profiles = list_profiles(tmp.path()).unwrap(); + + assert_eq!(profile, "main"); + assert_eq!(profiles, vec!["main"]); +} + +#[test] +fn delete_profile_removes_profile_dir() { + let tmp = tempfile::tempdir().unwrap(); + create_profile(tmp.path(), "main").unwrap(); + + delete_profile(tmp.path(), "main").unwrap(); + + assert!(list_profiles(tmp.path()).unwrap().is_empty()); +} + +#[test] +fn switch_to_profile_backs_up_local_config_and_restores_none() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let instance = tmp.path().join("instance"); + let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + std::fs::write(minecraft.join("options.txt"), "local-options").unwrap(); + std::fs::write(minecraft.join("config/local.txt"), "local").unwrap(); + + let selected = switch_profile("inst", None, Some("main"), &meta, &instance).unwrap(); + assert_eq!(selected.as_deref(), Some("main")); + assert_eq!( + std::fs::read_to_string(instance.join("rmcl/content/config/options.txt")).unwrap(), + "local-options" + ); + assert_eq!( + std::fs::read_to_string(instance.join("rmcl/content/config/config/local.txt")).unwrap(), + "local" + ); + + std::fs::write(minecraft.join("options.txt"), "shared-options").unwrap(); + std::fs::write(minecraft.join("config/shared.txt"), "shared").unwrap(); + let selected = switch_profile("inst", Some("main"), None, &meta, &instance).unwrap(); + + assert_eq!(selected, None); + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(), + "shared-options" + ); + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/main/config/shared.txt")).unwrap(), + "shared" + ); + assert_eq!( + std::fs::read_to_string(minecraft.join("options.txt")).unwrap(), + "local-options" + ); + assert_eq!( + std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(), + "local" + ); + assert!(!minecraft.join("config/shared.txt").exists()); +} + +#[test] +fn switch_from_deleted_profile_restores_local_without_recreating_profile() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let instance = tmp.path().join("instance"); + let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + std::fs::create_dir_all(instance.join("rmcl/content/config/config")).unwrap(); + std::fs::write(minecraft.join("options.txt"), "deleted-profile-options").unwrap(); + std::fs::write( + instance.join("rmcl/content/config/options.txt"), + "local-options", + ) + .unwrap(); + std::fs::write( + instance.join("rmcl/content/config/config/local.txt"), + "local", + ) + .unwrap(); + + let selected = switch_profile("inst", Some("deleted"), None, &meta, &instance).unwrap(); + + assert_eq!(selected, None); + assert_eq!( + std::fs::read_to_string(minecraft.join("options.txt")).unwrap(), + "local-options" + ); + assert_eq!( + std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(), + "local" + ); + assert!(!meta.join("state/profiles/deleted").exists()); +} + +#[test] +fn switch_between_profiles_saves_old_and_loads_new() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let instance = tmp.path().join("instance"); + let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + std::fs::write(minecraft.join("options.txt"), "changed-a-options").unwrap(); + std::fs::write(minecraft.join("config/a.txt"), "changed-a").unwrap(); + create_profile(&meta, "a").unwrap(); + std::fs::create_dir_all(meta.join("state/profiles/b/config")).unwrap(); + std::fs::write( + meta.join("state/profiles/b/options.txt"), + "profile-b-options", + ) + .unwrap(); + std::fs::write(meta.join("state/profiles/b/config/b.txt"), "profile-b").unwrap(); + + let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap(); + + assert_eq!(selected.as_deref(), Some("b")); + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/a/options.txt")).unwrap(), + "changed-a-options" + ); + assert_eq!( + std::fs::read_to_string(meta.join("state/profiles/a/config/a.txt")).unwrap(), + "changed-a" + ); + assert_eq!( + std::fs::read_to_string(minecraft.join("options.txt")).unwrap(), + "profile-b-options" + ); + assert_eq!( + std::fs::read_to_string(minecraft.join("config/b.txt")).unwrap(), + "profile-b" + ); + assert!(!minecraft.join("config/a.txt").exists()); +} + +#[test] +fn second_instance_uses_profile_options_saved_by_first_instance() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let first = tmp.path().join("first/minecraft"); + let second_instance = tmp.path().join("second"); + let second = second_instance.join(crate::storage::MINECRAFT_DIR_NAME); + std::fs::create_dir_all(first.join("config")).unwrap(); + std::fs::create_dir_all(second.join("config")).unwrap(); + std::fs::write(first.join("options.txt"), "first-default").unwrap(); + std::fs::write(second.join("options.txt"), "second-local").unwrap(); + create_profile(&meta, "main").unwrap(); + + assert!(prepare(Some("main"), &meta, &first).unwrap()); + std::fs::write(first.join("options.txt"), "changed-in-main").unwrap(); + finish(Some("main"), &meta, &first).unwrap(); + + switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap(); + + assert_eq!( + std::fs::read_to_string(second.join("options.txt")).unwrap(), + "changed-in-main" + ); + assert_eq!( + std::fs::read_to_string(second_instance.join("rmcl/content/config/options.txt")).unwrap(), + "second-local" + ); +} diff --git a/src/instance/tests/content/icons.rs b/src/instance/tests/content/icons.rs new file mode 100644 index 0000000..aaf16b4 --- /dev/null +++ b/src/instance/tests/content/icons.rs @@ -0,0 +1,23 @@ +use super::*; + +#[test] +fn quadrant_raster_has_requested_dimensions() { + let image = + image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(2, 2, image::Rgb([12, 34, 56]))); + let rows = make_icon_quadrants_from_image(&image, 7, 3); + + assert_eq!(rows.len(), 3); + assert!(rows.iter().all(|row| row.len() == 7)); + assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}')); +} + +#[test] +fn fallback_icon_is_square_and_contains_a_separate_question_mark_dot() { + let icon = fallback_icon(); + + assert_eq!(icon.len(), 3); + assert!(icon.iter().all(|row| row.len() == 6)); + assert_eq!(icon[2][2].bg_r, 45); + assert_eq!(icon[2][2].fg_r, 150); + assert_eq!(icon[2][3].fg_r, 150); +} diff --git a/src/instance/tests/content/manifest.rs b/src/instance/tests/content/manifest.rs new file mode 100644 index 0000000..ee07969 --- /dev/null +++ b/src/instance/tests/content/manifest.rs @@ -0,0 +1,84 @@ +use super::*; + +#[test] +fn manifest_round_trip_and_lookup_are_exact() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("rmcl/content/manifest.json"); + let record = ContentFileRecord { + relative_path: PathBuf::from("mods/fabric-api.jar"), + kind: ContentKind::Mod, + enabled: true, + fingerprint: FileFingerprint { + size: 3, + modified_ns: 4, + hashes: BTreeMap::from([("sha1".to_owned(), "abc".to_owned())]), + }, + resolution: Resolution::Resolved { + project: ProviderProject { + provider: "modrinth".to_owned(), + project_id: "P7dR8mSH".to_owned(), + version_id: "version".to_owned(), + }, + }, + }; + let mut manifest = ContentManifest::default(); + manifest.upsert(record); + manifest.save(&path).unwrap(); + + let loaded = ContentManifest::load(&path).unwrap(); + assert_eq!( + loaded.resolved_project_path("modrinth", "P7dR8mSH", Path::new("/instance/minecraft")), + Some(PathBuf::from("/instance/minecraft/mods/fabric-api.jar")) + ); + assert!( + loaded + .resolved_project_path("modrinth", "fabric-api", Path::new("/minecraft")) + .is_none() + ); +} + +#[test] +fn fingerprint_contains_both_modrinth_hashes() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("example.jar"); + std::fs::write(&path, b"abc").unwrap(); + let fingerprint = fingerprint(&path).unwrap(); + assert_eq!( + fingerprint.hash("sha1"), + Some("a9993e364706816aba3e25717850c26c9cd0d89d") + ); + assert_eq!(fingerprint.hash("sha512").unwrap().len(), 128); +} + +#[test] +fn renaming_a_record_preserves_its_resolution() { + let mut manifest = ContentManifest::default(); + manifest.upsert(ContentFileRecord { + relative_path: PathBuf::from("mods/example.jar"), + kind: ContentKind::Mod, + enabled: true, + fingerprint: FileFingerprint { + size: 3, + modified_ns: 4, + hashes: BTreeMap::new(), + }, + resolution: Resolution::Resolved { + project: ProviderProject { + provider: "modrinth".to_owned(), + project_id: "project".to_owned(), + version_id: "version".to_owned(), + }, + }, + }); + + assert!(manifest.rename_record( + Path::new("mods/example.jar"), + Path::new("mods/example.jar.disabled"), + false, + )); + let record = manifest + .record(Path::new("mods/example.jar.disabled")) + .unwrap(); + assert!(!record.enabled); + assert!(matches!(record.resolution, Resolution::Resolved { .. })); +} diff --git a/src/instance/tests/content/mods.rs b/src/instance/tests/content/mods.rs new file mode 100644 index 0000000..8b5a088 --- /dev/null +++ b/src/instance/tests/content/mods.rs @@ -0,0 +1,367 @@ +use super::*; +use std::path::PathBuf; + +fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf { + let dir = tmp + .join(instance) + .join(crate::storage::MINECRAFT_DIR_NAME) + .join("mods"); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn scan_mods_empty_dir() { + let tmp = tempfile::tempdir().unwrap(); + setup_mods_dir(tmp.path(), "inst"); + let mods = scan_mods(tmp.path(), "inst"); + assert!(mods.is_empty()); +} + +#[test] +fn scan_mods_missing_dir_returns_empty() { + let tmp = tempfile::tempdir().unwrap(); + let mods = scan_mods(tmp.path(), "ghost"); + assert!(mods.is_empty()); +} + +#[test] +fn scan_mods_enabled_disabled_flags() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + std::fs::write(dir.join("active.jar"), b"PK\x03\x04").unwrap(); + std::fs::write(dir.join("inactive.jar.disabled"), b"PK\x03\x04").unwrap(); + let mods = scan_mods(tmp.path(), "inst"); + let active = mods.iter().find(|m| m.file_stem == "active").unwrap(); + let inactive = mods.iter().find(|m| m.file_stem == "inactive").unwrap(); + assert!(active.enabled); + assert!(!inactive.enabled); +} + +#[test] +fn scan_mods_ignores_non_jar() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + std::fs::write(dir.join("readme.txt"), "not a mod").unwrap(); + std::fs::write(dir.join("config.json"), "{}").unwrap(); + std::fs::write(dir.join("real.jar"), b"PK\x03\x04").unwrap(); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods.len(), 1); +} + +#[test] +fn scan_mods_sorted_case_insensitive() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + std::fs::write(dir.join("Zebra.jar"), b"PK\x03\x04").unwrap(); + std::fs::write(dir.join("alpha.jar"), b"PK\x03\x04").unwrap(); + std::fs::write(dir.join("Beta.jar"), b"PK\x03\x04").unwrap(); + let mods = scan_mods(tmp.path(), "inst"); + let names: Vec<&str> = mods.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(names, vec!["alpha", "Beta", "Zebra"]); +} + +#[test] +fn toggle_entry_enable() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let disabled_path = dir.join("mymod.jar.disabled"); + std::fs::write(&disabled_path, b"PK\x03\x04").unwrap(); + + let entry = ContentEntry { + file_stem: "mymod".to_string(), + name: "mymod".to_string(), + source_slug: None, + installed_path: None, + provider_project: None, + title_suffix: None, + footer_label: None, + description: String::new(), + enabled: false, + icon_bytes: None, + provider_icon: false, + provider_description: false, + path: disabled_path.clone(), + icon_lines: None, + }; + + toggle_entry(&entry).unwrap(); + assert!(!disabled_path.exists()); + assert!(dir.join("mymod.jar").exists()); +} + +use std::io::Write as _; + +fn make_jar(dir: &Path, name: &str, entries: &[(&str, &[u8])]) { + let path = dir.join(name); + let file = std::fs::File::create(&path).unwrap(); + let mut zip = zip::ZipWriter::new(file); + let options: zip::write::FileOptions<()> = + zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored); + for (entry_name, data) in entries { + zip.start_file(*entry_name, options).unwrap(); + zip.write_all(data).unwrap(); + } + zip.finish().unwrap(); +} + +#[test] +fn scan_mods_reads_fabric_metadata() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let meta = r#"{"name":"Fabric Mod","description":"A fabric mod","icon":"icon.png"}"#; + make_jar( + &dir, + "fabric-mod.jar", + &[("fabric.mod.json", meta.as_bytes())], + ); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods.len(), 1); + assert_eq!(mods[0].name, "Fabric Mod"); + assert_eq!(mods[0].description, "A fabric mod"); +} + +#[test] +fn scan_mods_reads_quilt_metadata() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let meta = r#"{"quilt_loader":{"metadata":{"name":"Quilt Mod","description":"A quilt mod"}}}"#; + make_jar( + &dir, + "quilt-mod.jar", + &[("quilt.mod.json", meta.as_bytes())], + ); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods.len(), 1); + assert_eq!(mods[0].name, "Quilt Mod"); + assert_eq!(mods[0].description, "A quilt mod"); +} + +#[test] +fn scan_mods_reads_forge_toml_metadata() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let meta = r#" +logoFile = "logo.png" + +[[mods]] +displayName = "Forge Mod" +description = "A forge mod" +"#; + make_jar( + &dir, + "forge-mod.jar", + &[("META-INF/mods.toml", meta.as_bytes())], + ); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods.len(), 1); + assert_eq!(mods[0].name, "Forge Mod"); + assert_eq!(mods[0].description, "A forge mod"); +} + +#[test] +fn scan_mods_reads_neoforge_toml_metadata() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let meta = r#" +logoFile = "logo.png" + +[[mods]] +displayName = "NeoForge Mod" +description = "A neoforge mod" +"#; + make_jar( + &dir, + "neoforge-mod.jar", + &[("META-INF/neoforge.mods.toml", meta.as_bytes())], + ); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods.len(), 1); + assert_eq!(mods[0].name, "NeoForge Mod"); + assert_eq!(mods[0].description, "A neoforge mod"); +} + +#[test] +fn scan_mods_reads_mcmod_info_array() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let meta = r#"[{"name":"Legacy Mod","description":"An old forge mod"}]"#; + make_jar(&dir, "legacy-mod.jar", &[("mcmod.info", meta.as_bytes())]); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods.len(), 1); + assert_eq!(mods[0].name, "Legacy Mod"); + assert_eq!(mods[0].description, "An old forge mod"); +} + +#[test] +fn scan_mods_reads_mcmod_info_modlist() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let meta = r#"{"modList":[{"name":"Wrapped Mod","description":"Has modList wrapper"}]}"#; + make_jar(&dir, "wrapped-mod.jar", &[("mcmod.info", meta.as_bytes())]); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods.len(), 1); + assert_eq!(mods[0].name, "Wrapped Mod"); + assert_eq!(mods[0].description, "Has modList wrapper"); +} + +#[test] +fn scan_mods_prefers_fabric_over_forge() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let fabric = r#"{"name":"Fabric Name","description":"fabric desc"}"#; + let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n"; + make_jar( + &dir, + "multi.jar", + &[ + ("fabric.mod.json", fabric.as_bytes()), + ("META-INF/mods.toml", forge.as_bytes()), + ], + ); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods[0].name, "Fabric Name"); +} + +#[test] +fn scan_mods_prefers_quilt_over_forge() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let quilt = r#"{"quilt_loader":{"id":"x","version":"1","metadata":{"name":"Quilt Name","description":"quilt desc"}}}"#; + let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n"; + make_jar( + &dir, + "quilt-over-forge.jar", + &[ + ("quilt.mod.json", quilt.as_bytes()), + ("META-INF/mods.toml", forge.as_bytes()), + ], + ); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods[0].name, "Quilt Name"); +} + +#[test] +fn scan_mods_prefers_forge_toml_over_mcmod_info() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n"; + let mcmod = r#"[{"modid":"legacy","name":"Legacy Name","description":"legacy desc"}]"#; + make_jar( + &dir, + "forge-over-legacy.jar", + &[ + ("META-INF/mods.toml", forge.as_bytes()), + ("mcmod.info", mcmod.as_bytes()), + ], + ); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods[0].name, "Forge Name"); +} + +// when both neoforge.mods.toml and mods.toml exist in the same jar (the +// shape a dual-format mod might ship), the neoforge one wins because +// read_forge_toml_meta tries it first via .or_else. +#[test] +fn scan_mods_prefers_neoforge_toml_over_forge_toml() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let neoforge = "[[mods]]\ndisplayName = \"NeoForge Name\"\ndescription = \"neoforge desc\"\n"; + let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n"; + make_jar( + &dir, + "neoforge-over-forge.jar", + &[ + ("META-INF/neoforge.mods.toml", neoforge.as_bytes()), + ("META-INF/mods.toml", forge.as_bytes()), + ], + ); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods[0].name, "NeoForge Name"); +} + +// a mods.toml with logoFile but no [[mods]] array (e.g. a dependency-only +// library jar) should still surface as a scanned mod with empty name + +// description but with the icon resolved. +#[test] +fn scan_mods_reads_mods_toml_without_mods_array() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let mods_toml = "logoFile = \"icon.png\"\n"; + let png_bytes = b"\x89PNG fake icon"; + make_jar( + &dir, + "lib-only.jar", + &[ + ("META-INF/mods.toml", mods_toml.as_bytes()), + ("icon.png", png_bytes), + ], + ); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods.len(), 1); + // file-stem fallback when metadata name is empty - covered here + // because no other test exercises an empty-name + present-logo combo. + assert_eq!(mods[0].name, "lib-only"); + assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice())); +} + +#[test] +fn scan_mods_fallback_icon_paths() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let png_bytes = b"\x89PNG fake"; + make_jar(&dir, "no-meta.jar", &[("logo.png", png_bytes)]); + let mods = scan_mods(tmp.path(), "inst"); + assert_eq!(mods.len(), 1); + assert_eq!(mods[0].name, "no-meta"); + assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice())); +} + +#[test] +fn icon_path_from_value_string() { + let val = serde_json::json!("assets/icon.png"); + assert_eq!(icon_path_from_value(&val), "assets/icon.png"); +} + +#[test] +fn icon_path_from_value_map() { + // serde_json::Map is a BTreeMap, so iteration is sorted by key. + // "128" sorts before "64" lexicographically, so the first value wins. + let val = serde_json::json!({"64": "icon_64.png", "128": "icon_128.png"}); + assert_eq!(icon_path_from_value(&val), "icon_128.png"); +} + +#[test] +fn icon_path_from_value_null() { + let val = serde_json::Value::Null; + assert_eq!(icon_path_from_value(&val), ""); +} + +#[test] +fn toggle_entry_disable() { + let tmp = tempfile::tempdir().unwrap(); + let dir = setup_mods_dir(tmp.path(), "inst"); + let enabled_path = dir.join("mymod.jar"); + std::fs::write(&enabled_path, b"PK\x03\x04").unwrap(); + + let entry = ContentEntry { + file_stem: "mymod".to_string(), + name: "mymod".to_string(), + source_slug: None, + installed_path: None, + provider_project: None, + title_suffix: None, + footer_label: None, + description: String::new(), + enabled: true, + icon_bytes: None, + provider_icon: false, + provider_description: false, + path: enabled_path.clone(), + icon_lines: None, + }; + + toggle_entry(&entry).unwrap(); + assert!(!enabled_path.exists()); + assert!(dir.join("mymod.jar.disabled").exists()); +} diff --git a/src/instance/tests/content/provider.rs b/src/instance/tests/content/provider.rs new file mode 100644 index 0000000..6b1fea4 --- /dev/null +++ b/src/instance/tests/content/provider.rs @@ -0,0 +1,7 @@ +use super::*; + +#[test] +fn registry_falls_back_to_first_capable_provider() { + let registry = ProviderRegistry::modrinth(crate::net::HttpClient::new()); + assert_eq!(registry.preferred("unknown").unwrap().id(), "modrinth"); +} diff --git a/src/instance/tests/content/reconcile.rs b/src/instance/tests/content/reconcile.rs new file mode 100644 index 0000000..76baa14 --- /dev/null +++ b/src/instance/tests/content/reconcile.rs @@ -0,0 +1,114 @@ +use super::*; + +struct NoopProgress; + +impl InventoryProgress for NoopProgress { + fn set_sub_action(&self, _text: &str) {} + + fn set_progress(&self, _current: u64, _total: u64) {} +} + +fn job(name: &str) -> ReconcileJob { + ReconcileJob { + instance: InstanceConfig { + name: name.to_owned(), + game_version: "1.21.1".to_owned(), + loader: crate::instance::ModLoader::Fabric, + loader_version: None, + created: chrono::Utc::now(), + last_played: None, + java_path: None, + memory_max: None, + memory_min: None, + jvm_args: Vec::new(), + resolution: None, + config_sync_profile: None, + }, + instances_dir: PathBuf::new(), + client: crate::net::HttpClient::new(), + } +} + +#[test] +fn coordinator_queues_instances_once_and_preserves_order() { + let mut coordinator = ReconcileCoordinator::default(); + assert!(coordinator.enqueue(job("one"), false)); + assert!(!coordinator.enqueue(job("two"), false)); + assert!(!coordinator.enqueue(job("one"), false)); + assert!(!coordinator.rerun.contains("one")); + assert!(!coordinator.enqueue(job("one"), true)); + assert_eq!(coordinator.queue.len(), 2); + assert!(coordinator.rerun.contains("one")); + assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "one"); + assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "two"); +} + +#[test] +fn oversized_content_is_kept_without_hashing_or_provider_query() { + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join("minecraft"); + let resource_packs = minecraft.join("resourcepacks"); + std::fs::create_dir_all(&resource_packs).unwrap(); + let pack = resource_packs.join("large.zip"); + let file = std::fs::File::create(&pack).unwrap(); + file.set_len(2 * 1024 * 1024).unwrap(); + let manifest_path = temp.path().join("manifest.json"); + + let inventory = reconcile_inventory(&manifest_path, &minecraft, 24, 1, &NoopProgress).unwrap(); + + assert!(inventory.queries.is_empty()); + assert_eq!(inventory.manifest.files.len(), 1); + assert!(inventory.manifest.files[0].fingerprint.hashes.is_empty()); + assert!(matches!( + inventory.manifest.files[0].resolution, + Resolution::Unmatched { .. } + )); +} + +#[test] +fn unchanged_saved_index_reuses_fingerprint_and_skips_provider_query() { + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join("minecraft"); + let mods = minecraft.join("mods"); + std::fs::create_dir_all(&mods).unwrap(); + std::fs::write(mods.join("example.jar"), b"example").unwrap(); + let manifest_path = temp.path().join("manifest.json"); + + let mut first = + reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap(); + assert_eq!(first.queries.len(), 1); + let fingerprint = first.manifest.files[0].fingerprint.clone(); + first.manifest.files[0].resolution = Resolution::Unmatched { + checked_at: chrono::Utc::now().timestamp(), + providers: vec!["modrinth".to_owned()], + }; + first.manifest.save(&manifest_path).unwrap(); + + let second = reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap(); + assert!(second.queries.is_empty()); + assert_eq!(second.manifest.files[0].fingerprint, fingerprint); +} + +#[test] +fn directory_packs_are_indexed_without_provider_queries() { + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join("minecraft"); + let pack = minecraft.join("resourcepacks/example"); + std::fs::create_dir_all(&pack).unwrap(); + std::fs::write(pack.join("pack.mcmeta"), b"{}").unwrap(); + + let inventory = reconcile_inventory( + &temp.path().join("manifest.json"), + &minecraft, + 24, + 512, + &NoopProgress, + ) + .unwrap(); + + assert!(inventory.queries.is_empty()); + assert_eq!( + inventory.manifest.files[0].relative_path, + PathBuf::from("resourcepacks/example") + ); +} diff --git a/src/instance/tests/content/resource_packs.rs b/src/instance/tests/content/resource_packs.rs new file mode 100644 index 0000000..bfabac5 --- /dev/null +++ b/src/instance/tests/content/resource_packs.rs @@ -0,0 +1,18 @@ +use super::super::packs::extract_description; +use serde_json::json; + +// every case exercises a distinct match arm in extract_description. +#[rstest::rstest] +#[case::string(json!("Simple pack"), "Simple pack")] +#[case::object_with_text(json!({"text": "Hello world"}), "Hello world")] +#[case::object_without_text(json!({"color": "red"}), "")] +#[case::array_of_strings(json!(["Hello", " ", "world"]), "Hello world")] +#[case::array_of_objects(json!([{"text": "A"}, {"text": "B"}]), "AB")] +#[case::mixed_array(json!(["Prefix ", {"text": "suffix"}]), "Prefix suffix")] +#[case::empty_array(json!([]), "")] +#[case::null(serde_json::Value::Null, "")] +#[case::number(json!(42), "")] +#[case::bool(json!(true), "")] +fn extract_description_handles(#[case] input: serde_json::Value, #[case] expected: &str) { + assert_eq!(extract_description(&input), expected); +} diff --git a/src/instance/tests/desktop.rs b/src/instance/tests/desktop.rs new file mode 100644 index 0000000..9c97869 --- /dev/null +++ b/src/instance/tests/desktop.rs @@ -0,0 +1,30 @@ +use super::*; + +#[test] +fn sanitize_keeps_alphanumeric() { + assert_eq!(sanitize("my-instance_123"), "my-instance_123"); +} + +#[test] +fn sanitize_replaces_special_chars() { + assert_eq!(sanitize("my instance!"), "my_instance_"); + assert_eq!(sanitize("path/traversal"), "path_traversal"); +} + +#[test] +#[cfg(target_os = "linux")] +fn build_content_linux() { + let content = build_content("TestPack", None); + assert!(content.contains("Name=Minecraft - TestPack")); + assert!(content.contains("Exec=rmcl instance launch \"TestPack\"")); + assert!(content.contains("Terminal=false")); + assert!(content.contains("Categories=Game;")); +} + +#[test] +#[cfg(target_os = "linux")] +fn build_content_linux_with_icon() { + let icon = PathBuf::from("/tmp/icon.png"); + let content = build_content("TestPack", Some(&icon)); + assert!(content.contains("Icon=/tmp/icon.png")); +} diff --git a/src/instance/tests/import/format_detection.rs b/src/instance/tests/import/format_detection.rs new file mode 100644 index 0000000..99a6af9 --- /dev/null +++ b/src/instance/tests/import/format_detection.rs @@ -0,0 +1,172 @@ +use super::*; +use std::io::Write; + +fn make_pack_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> std::path::PathBuf { + let path = tmp.join(name); + let file = std::fs::File::create(&path).unwrap(); + let mut zip = zip::ZipWriter::new(file); + let opts: zip::write::SimpleFileOptions = Default::default(); + for (filename, bytes) in entries { + zip.start_file(*filename, opts).unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap(); + path +} + +#[test] +fn detect_format_recognises_mrpack() { + let tmp = tempfile::tempdir().unwrap(); + let path = make_pack_zip(tmp.path(), "pack.mrpack", &[("modrinth.index.json", b"{}")]); + assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack)); +} + +#[test] +fn detect_format_recognises_mmc_flat() { + // mmc-pack.json at the zip root - the flat layout that some mmc + // archives use. + let tmp = tempfile::tempdir().unwrap(); + let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]); + assert_eq!(detect_format(&path), Ok(PackFormat::Mmc)); +} + +#[test] +fn detect_format_recognises_mmc_nested() { + // mmc-pack.json one directory deep - the more common layout where + // the archive wraps everything in a named directory. + let tmp = tempfile::tempdir().unwrap(); + let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]); + assert_eq!(detect_format(&path), Ok(PackFormat::Mmc)); +} + +#[test] +fn detect_format_prefers_mrpack_when_both_markers_present() { + // a zip with both markers should resolve to Mrpack since the + // detector checks modrinth.index.json first. + let tmp = tempfile::tempdir().unwrap(); + let path = make_pack_zip( + tmp.path(), + "weird.zip", + &[("modrinth.index.json", b"{}"), ("mmc-pack.json", b"{}")], + ); + assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack)); +} + +#[test] +fn detect_format_errors_on_unknown_archive() { + let tmp = tempfile::tempdir().unwrap(); + let path = make_pack_zip(tmp.path(), "random.zip", &[("readme.txt", b"hello")]); + let err = detect_format(&path).unwrap_err(); + assert!( + err.contains("Unknown pack format"), + "expected unknown format error, got: {err}" + ); +} + +#[test] +fn detect_format_errors_on_missing_file() { + let tmp = tempfile::tempdir().unwrap(); + let err = detect_format(&tmp.path().join("missing.zip")).unwrap_err(); + assert!(err.contains("Cannot open"), "got: {err}"); +} + +#[test] +fn unique_name_no_collision() { + let tmp = tempfile::tempdir().unwrap(); + let name = unique_instance_name("TestPack", tmp.path()); + assert_eq!(name, "TestPack"); +} + +#[test] +fn unique_name_with_collision() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("TestPack"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("instance.json"), "{}").unwrap(); + let name = unique_instance_name("TestPack", tmp.path()); + assert_eq!(name, "TestPack (2)"); +} + +#[test] +fn unique_name_multiple_collisions() { + let tmp = tempfile::tempdir().unwrap(); + for suffix in ["", " (2)", " (3)"] { + let dir = tmp.path().join(format!("TestPack{suffix}")); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("instance.json"), "{}").unwrap(); + } + let name = unique_instance_name("TestPack", tmp.path()); + assert_eq!(name, "TestPack (4)"); +} + +#[test] +fn parse_project_url() { + assert_eq!( + parse_import_input("https://modrinth.com/modpack/fabulously-optimized"), + ImportInput::ProjectSlug("fabulously-optimized".to_string()) + ); +} + +#[test] +fn parse_version_url() { + assert_eq!( + parse_import_input("https://modrinth.com/modpack/fabulously-optimized/version/abc123"), + ImportInput::VersionId { + slug: "fabulously-optimized".to_string(), + version_id: "abc123".to_string(), + } + ); +} + +#[test] +fn parse_local_mrpack() { + assert_eq!( + parse_import_input("/home/user/pack.mrpack"), + ImportInput::LocalFile("/home/user/pack.mrpack".to_string()) + ); +} + +#[test] +fn parse_local_zip() { + assert_eq!( + parse_import_input("GT_New_Horizons.zip"), + ImportInput::LocalFile("GT_New_Horizons.zip".to_string()) + ); +} + +#[test] +fn parse_tilde_path() { + assert_eq!( + parse_import_input("~/Downloads/pack.mrpack"), + ImportInput::LocalFile("~/Downloads/pack.mrpack".to_string()) + ); +} + +#[test] +fn parse_bare_slug() { + assert_eq!( + parse_import_input("fabulously-optimized"), + ImportInput::ProjectSlug("fabulously-optimized".to_string()) + ); +} + +#[test] +fn parse_input_trims_whitespace() { + assert_eq!( + parse_import_input(" fabulously-optimized "), + ImportInput::ProjectSlug("fabulously-optimized".to_string()) + ); +} + +#[test] +fn failed_import_cleanup_removes_the_partial_instance() { + let tmp = tempfile::tempdir().unwrap(); + let manager = InstanceManager::new(tmp.path().join("instances"), tmp.path().join("meta")); + let instance_dir = manager.instances_dir.join("Broken"); + std::fs::create_dir_all(&instance_dir).unwrap(); + std::fs::write(instance_dir.join("partial"), b"data").unwrap(); + + cleanup_failed_import(&manager, "Broken"); + + assert!(!instance_dir.exists()); +} diff --git a/src/instance/tests/import/mmc.rs b/src/instance/tests/import/mmc.rs new file mode 100644 index 0000000..f5b4d74 --- /dev/null +++ b/src/instance/tests/import/mmc.rs @@ -0,0 +1,108 @@ +use super::*; + +#[test] +fn parse_mmc_pack_json() { + let json = r#"{ + "formatVersion": 1, + "components": [ + { + "uid": "net.minecraft", + "version": "1.7.10", + "cachedName": "Minecraft" + }, + { + "uid": "net.minecraftforge", + "version": "10.13.4.1614", + "cachedName": "Forge" + } + ] + }"#; + let pack: MmcPack = serde_json::from_str(json).unwrap(); + assert_eq!(pack.game_version(), Some("1.7.10".to_string())); + let (loader, version) = pack.loader(); + assert_eq!(loader, Some(ModLoader::Forge)); + assert_eq!(version, Some("10.13.4.1614".to_string())); +} + +#[test] +fn parse_mmc_pack_vanilla() { + let json = r#"{ + "formatVersion": 1, + "components": [ + {"uid": "net.minecraft", "version": "1.21.4"} + ] + }"#; + let pack: MmcPack = serde_json::from_str(json).unwrap(); + assert!(pack.loader().0.is_none()); +} + +// builds an in-memory mmc-style pack zip and verifies that +// extract_mmc_archive copies only the .minecraft/ subtree into the +// destination, preserving relative paths and skipping siblings. +#[test] +fn extract_mmc_archive_copies_minecraft_subtree() { + use std::io::Write; + + let tmp = tempfile::tempdir().unwrap(); + let archive_path = tmp.path().join("pack.zip"); + let dest = tmp.path().join("instance/.minecraft"); + std::fs::create_dir_all(&dest).unwrap(); + + // Pack/ is the prefix; only .minecraft/ entries should land in dest. + // mmc-style pack: a root dir "Pack/" wrapping the .minecraft tree + // plus a sibling mmc-pack.json that should NOT be extracted. + { + let file = std::fs::File::create(&archive_path).unwrap(); + let mut zip = zip::ZipWriter::new(file); + let opts: zip::write::SimpleFileOptions = Default::default(); + + zip.start_file("Pack/mmc-pack.json", opts).unwrap(); + zip.write_all(b"{}").unwrap(); + + zip.start_file("Pack/.minecraft/options.txt", opts).unwrap(); + zip.write_all(b"lang:en_us").unwrap(); + + zip.start_file("Pack/.minecraft/mods/test-mod.jar", opts) + .unwrap(); + zip.write_all(b"jar-bytes").unwrap(); + + zip.finish().unwrap(); + } + + extract_mmc_archive(&archive_path, &dest).expect("extract"); + + // .minecraft/ entries must have been copied with their relative paths + let options = std::fs::read(dest.join("options.txt")).expect("options.txt"); + assert_eq!(options, b"lang:en_us"); + let modjar = std::fs::read(dest.join("mods/test-mod.jar")).expect("mods/test-mod.jar"); + assert_eq!(modjar, b"jar-bytes"); + + // and the sibling outside .minecraft/ must not have been copied + assert!( + !dest.join("mmc-pack.json").exists(), + "mmc-pack.json should not land in the instance dir" + ); +} + +#[test] +fn extract_mmc_archive_rejects_path_traversal() { + use std::io::Write; + + let tmp = tempfile::tempdir().unwrap(); + let archive_path = tmp.path().join("pack.zip"); + let dest = tmp.path().join("instance/minecraft"); + let file = std::fs::File::create(&archive_path).unwrap(); + let mut zip = zip::ZipWriter::new(file); + let options: zip::write::SimpleFileOptions = Default::default(); + zip.start_file("Pack/mmc-pack.json", options).unwrap(); + zip.write_all(b"{}").unwrap(); + zip.start_file("Pack/.minecraft/../../escaped.txt", options) + .unwrap(); + zip.write_all(b"escaped").unwrap(); + zip.finish().unwrap(); + + let error = extract_mmc_archive(&archive_path, &dest).unwrap_err(); + + assert!(error.to_string().contains("archive path")); + assert!(!tmp.path().join("escaped.txt").exists()); +} diff --git a/src/instance/import/mrpack/tests.rs b/src/instance/tests/import/mrpack.rs similarity index 97% rename from src/instance/import/mrpack/tests.rs rename to src/instance/tests/import/mrpack.rs index a3e4b3d..f2df0d8 100644 --- a/src/instance/import/mrpack/tests.rs +++ b/src/instance/tests/import/mrpack.rs @@ -128,7 +128,7 @@ fn extraction_rejects_path_traversal() { #[test] fn mod_files_download_to_their_manifest_paths() { - let _guard = crate::tui::tests::UI_TEST_LOCK + let _guard = crate::tests::TEST_LOCK .lock() .unwrap_or_else(|error| error.into_inner()); let runtime = tokio::runtime::Builder::new_current_thread() @@ -180,13 +180,13 @@ fn mod_files_download_to_their_manifest_paths() { std::fs::read(tmp.path().join("resourcepacks/second.jar")).unwrap(), b"second" ); - crate::tui::progress::clear(); + crate::feedback::progress::clear(); }); } #[test] fn mod_file_without_a_download_url_fails_without_creating_a_file() { - let _guard = crate::tui::tests::UI_TEST_LOCK + let _guard = crate::tests::TEST_LOCK .lock() .unwrap_or_else(|error| error.into_inner()); let runtime = tokio::runtime::Builder::new_current_thread() @@ -210,6 +210,6 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() { assert!(download_mod_files(&index, tmp.path()).await.is_err()); assert!(!tmp.path().join("mods/missing.jar").exists()); - crate::tui::progress::clear(); + crate::feedback::progress::clear(); }); } diff --git a/src/instance/tests/launch/parser.rs b/src/instance/tests/launch/parser.rs new file mode 100644 index 0000000..bcea19f --- /dev/null +++ b/src/instance/tests/launch/parser.rs @@ -0,0 +1,102 @@ +use super::*; + +fn parse_all(lines: &[(LogStream, &str)]) -> Vec { + let mut parser = MinecraftLogParser::new(); + let mut events = Vec::new(); + for (stream, line) in lines { + events.extend(parser.push_line(*stream, *line)); + } + events.extend(parser.flush()); + events +} + +#[test] +fn classifies_minecraft_headers() { + let events = parse_all(&[ + (LogStream::Stdout, "[Render thread/INFO]: hello"), + (LogStream::Stdout, "[Render thread/WARN]: careful"), + (LogStream::Stdout, "[Render thread/ERROR]: broken"), + (LogStream::Stdout, "[Render thread/DEBUG]: noisy"), + (LogStream::Stdout, "[Render thread/TRACE]: tiny"), + ]); + + assert_eq!(events.len(), 5); + assert_eq!(events[0].level, LogLevel::Info); + assert_eq!(events[1].level, LogLevel::Warn); + assert_eq!(events[2].level, LogLevel::Error); + assert_eq!(events[3].level, LogLevel::Debug); + assert_eq!(events[4].level, LogLevel::Trace); +} + +#[test] +fn explicit_stderr_info_stays_info() { + let events = parse_all(&[(LogStream::Stderr, "[Render thread/INFO]: hello")]); + + assert_eq!(events[0].level, LogLevel::Info); +} + +#[test] +fn unstructured_stderr_falls_back_to_error() { + let events = parse_all(&[(LogStream::Stderr, "native library failed")]); + + assert_eq!(events[0].level, LogLevel::Error); +} + +#[test] +fn groups_java_stacktrace() { + let events = parse_all(&[ + ( + LogStream::Stderr, + "Exception in thread \"main\" java.lang.RuntimeException: boom", + ), + ( + LogStream::Stderr, + "\tat net.minecraft.client.Main.main(Main.java:42)", + ), + ( + LogStream::Stderr, + "Caused by: java.lang.IllegalStateException: bad", + ), + (LogStream::Stderr, "\tat example.Mod.load(Mod.java:7)"), + (LogStream::Stdout, "[Render thread/INFO]: after"), + ]); + + assert_eq!(events.len(), 2); + assert_eq!(events[0].level, LogLevel::Error); + assert_eq!(events[0].lines.len(), 4); + assert!( + events[0] + .java + .as_ref() + .is_some_and(|java| java.has_stacktrace) + ); + assert_eq!(events[1].level, LogLevel::Info); +} + +#[test] +fn groups_jvm_startup_failure_burst() { + let events = parse_all(&[ + (LogStream::Stderr, "Unrecognized option: --bad"), + ( + LogStream::Stderr, + "Could not create the Java Virtual Machine.", + ), + ( + LogStream::Stderr, + "A fatal exception has occurred. Program will exit.", + ), + ]); + + assert_eq!(events.len(), 1); + assert_eq!(events[0].level, LogLevel::Error); + assert_eq!(events[0].lines.len(), 3); +} + +#[test] +fn colored_header_classifies_but_keeps_original_text() { + let line = "\u{1b}[31m[Render thread/ERROR]: red\u{1b}[0m"; + let events = parse_all(&[(LogStream::Stdout, line)]); + + assert_eq!(events[0].level, LogLevel::Error); + assert_eq!(events[0].lines[0], line); +} diff --git a/src/instance/tests/launch/patches.rs b/src/instance/tests/launch/patches.rs new file mode 100644 index 0000000..be9eb65 --- /dev/null +++ b/src/instance/tests/launch/patches.rs @@ -0,0 +1,135 @@ +use super::*; +use std::io::Write; + +// builds an in-memory zip with the given entries, writes it to tmp, and +// returns the path. shared by parse_add_opens tests. +fn make_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf { + let path = tmp.join(name); + let file = std::fs::File::create(&path).unwrap(); + let mut zip = zip::ZipWriter::new(file); + let opts: zip::write::SimpleFileOptions = Default::default(); + for (filename, bytes) in entries { + zip.start_file(*filename, opts).unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap(); + path +} + +#[test] +fn strip_replaced_libs_removes_dominated_prefixes() { + let mut classpath = vec![ + PathBuf::from("/libs/launchwrapper-1.12.jar"), + PathBuf::from("/libs/asm-all-5.0.3.jar"), + PathBuf::from("/libs/lwjgl-2.9.4.jar"), + PathBuf::from("/libs/lwjgl_util-2.9.4.jar"), + PathBuf::from("/libs/commons-compress-1.4.1.jar"), + PathBuf::from("/libs/commons-io-2.4.jar"), + PathBuf::from("/libs/guava-15.0.jar"), + // these stay + PathBuf::from("/libs/log4j-core-2.0.jar"), + PathBuf::from("/libs/guava-21.0.jar"), + ]; + strip_replaced_libs(&mut classpath); + assert_eq!( + classpath, + vec![ + PathBuf::from("/libs/log4j-core-2.0.jar"), + PathBuf::from("/libs/guava-21.0.jar"), + ] + ); +} + +#[test] +fn strip_replaced_libs_keeps_unrelated_entries() { + let mut classpath = vec![ + PathBuf::from("/libs/log4j-core-2.0.jar"), + PathBuf::from("/libs/mixin-0.8.5.jar"), + ]; + let original = classpath.clone(); + strip_replaced_libs(&mut classpath); + assert_eq!(classpath, original); +} + +#[test] +fn parse_add_opens_extracts_module_args() { + let tmp = tempfile::tempdir().unwrap(); + let manifest = b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n"; + let zip_path = make_zip( + tmp.path(), + "patches.zip", + &[("META-INF/MANIFEST.MF", manifest)], + ); + let args = parse_add_opens(&zip_path).expect("parsed"); + assert_eq!( + args, + vec![ + "--add-opens", + "java.base/java.lang=ALL-UNNAMED", + "--add-opens", + "java.base/java.util=ALL-UNNAMED", + ] + ); +} + +#[test] +fn parse_add_opens_handles_continuation_lines() { + // jar manifests wrap long lines: the line ends with a trailing space, + // then the next physical line starts with a leading space marker. + // when joined per the MANIFEST.MF spec, the trailing space remains + // and the leading space marker is consumed, so the two values stay + // separated by exactly one space when split_whitespace runs. + let tmp = tempfile::tempdir().unwrap(); + let manifest = + b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang \n java.base/sun.security.util\n"; + let zip_path = make_zip( + tmp.path(), + "patches-continuation.zip", + &[("META-INF/MANIFEST.MF", manifest)], + ); + let args = parse_add_opens(&zip_path).expect("parsed"); + assert_eq!( + args, + vec![ + "--add-opens", + "java.base/java.lang=ALL-UNNAMED", + "--add-opens", + "java.base/sun.security.util=ALL-UNNAMED", + ] + ); +} + +#[test] +fn parse_add_opens_returns_none_when_manifest_missing() { + let tmp = tempfile::tempdir().unwrap(); + let zip_path = make_zip(tmp.path(), "no-manifest.zip", &[("other.txt", b"x")]); + assert!(parse_add_opens(&zip_path).is_none()); +} + +#[test] +fn parse_add_opens_returns_none_for_missing_file() { + let tmp = tempfile::tempdir().unwrap(); + assert!(parse_add_opens(&tmp.path().join("missing.zip")).is_none()); +} + +#[test] +fn add_lwjgl3_inserts_only_jars_that_exist() { + let tmp = tempfile::tempdir().unwrap(); + let lib_dir = tmp.path(); + + // pre-create only the lwjgl core jar; everything else absent so the + // function should skip them silently. proves we don't insert paths + // for jars that aren't there. + let core_jar = lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar"); + std::fs::create_dir_all(core_jar.parent().unwrap()).unwrap(); + std::fs::write(&core_jar, b"jar").unwrap(); + + let mut classpath = vec![PathBuf::from("/leading/forge-patches.jar")]; + add_lwjgl3(lib_dir, &mut classpath); + + // forge-patches stays at index 0; lwjgl core is inserted at index 1. + // none of the other modules existed so nothing else was added. + assert_eq!(classpath[0], PathBuf::from("/leading/forge-patches.jar")); + assert_eq!(classpath[1], core_jar); + assert_eq!(classpath.len(), 2); +} diff --git a/src/instance/tests/launch/pipeline.rs b/src/instance/tests/launch/pipeline.rs new file mode 100644 index 0000000..631f0d9 --- /dev/null +++ b/src/instance/tests/launch/pipeline.rs @@ -0,0 +1,232 @@ +use super::*; + +#[rstest::rstest] +#[case("openjdk version \"25.0.3\" 2026-04-21", Some(25))] +#[case("openjdk version \"21.0.11\" 2026-04-21", Some(21))] +#[case("java version \"1.8.0_402\"", Some(8))] +#[case("garbage", None)] +fn parse_java_major_version_handles_common_outputs( + #[case] output: &str, + #[case] expected: Option, +) { + assert_eq!(parse_java_major_version(output), expected); +} + +#[test] +fn build_game_args_renders_upstream_arguments() { + use crate::launch_profile::model::{Argument, Arguments, LaunchProfile}; + use crate::launch_profile::rules::{FeatureSet, RuleContext}; + use TemplateContext; + use std::path::PathBuf; + + let lib = PathBuf::from("/m/libraries"); + let nat = PathBuf::from("/m/natives"); + let game_dir = PathBuf::from("/i/.minecraft"); + let assets = PathBuf::from("/m/assets"); + + let template_ctx = TemplateContext { + library_directory: &lib, + classpath_separator: ":", + version_name: "1.20.1", + natives_directory: &nat, + classpath: "a.jar:b.jar", + game_directory: &game_dir, + assets_root: &assets, + assets_index_name: "5", + auth_player_name: "Player", + auth_uuid: "00000000-0000-0000-0000-000000000000", + auth_access_token: "token", + auth_xuid: "0", + user_type: "msa", + user_properties: "{}", + launcher_name: "rmcl", + launcher_version: "test", + clientid: "0", + version_type: "release", + }; + let features = FeatureSet::default(); + let rule_ctx = RuleContext { + os_name: "linux", + os_version: "6.0", + arch: "x86_64", + features: &features, + }; + + let profile = LaunchProfile { + id: "1.20.1".into(), + inherits_from: None, + main_class: Some("net.minecraft.client.main.Main".into()), + libraries: Vec::new(), + arguments: Some(Arguments { + game: vec![ + Argument::Literal("--username".into()), + Argument::Literal("${auth_player_name}".into()), + ], + jvm: vec![Argument::Literal( + "-Djava.library.path=${natives_directory}".into(), + )], + }), + ..Default::default() + }; + + let (jvm, game_args) = build_game_args(&profile, &rule_ctx, &template_ctx).unwrap(); + assert_eq!(jvm, vec!["-Djava.library.path=/m/natives"]); + assert_eq!(game_args, vec!["--username", "Player"]); +} + +// exercises the early-return branch of migrate_legacy_meta_if_needed. +// a profile with either arguments or minecraftArguments is not legacy +// and must produce Ok(None) without touching the network. covers both +// shapes in one parameterised test so a regression that drops one of +// the two predicate conditions is caught. +#[rstest::rstest] +#[case::modern_arguments(true, false)] +#[case::legacy_minecraft_arguments(false, true)] +#[tokio::test] +async fn migrate_legacy_meta_skips_when_arguments_present( + #[case] modern: bool, + #[case] legacy: bool, +) { + use crate::launch_profile::model::{Arguments, LaunchProfile}; + use tempfile::TempDir; + + let tmp = TempDir::new().unwrap(); + let meta_path = tmp.path().join("meta.json"); + std::fs::write(&meta_path, b"{}").unwrap(); + + let profile = LaunchProfile { + id: "1.20.1".into(), + main_class: Some("net.test.Main".into()), + arguments: modern.then(Arguments::default), + minecraft_arguments: legacy.then(|| "--username Player".into()), + ..Default::default() + }; + + let result = migrate_legacy_meta_if_needed(&meta_path, &profile, "1.20.1").await; + assert!( + matches!(result, Ok(None)), + "expected Ok(None) for non-legacy profile, got {result:?}" + ); +} + +// each loader maps to a distinct directory-naming branch. one rstest +// exercises every variant so a regression that misorders the match +// arms in installer_version_dir_name is caught. +#[rstest::rstest] +#[case::forge(ModLoader::Forge, "1.20.1", "47.2.0", Some("1.20.1-forge-47.2.0"))] +#[case::neoforge(ModLoader::NeoForge, "1.21.1", "21.1.0", Some("neoforge-21.1.0"))] +#[case::vanilla(ModLoader::Vanilla, "1.20.1", "v", None)] +#[case::fabric(ModLoader::Fabric, "1.20.1", "0.14.21", None)] +#[case::quilt(ModLoader::Quilt, "1.20.1", "0.20.0", None)] +fn installer_version_dir_name_per_loader( + #[case] loader: ModLoader, + #[case] game_version: &str, + #[case] loader_version: &str, + #[case] expected: Option<&str>, +) { + assert_eq!( + installer_version_dir_name(loader, game_version, loader_version), + expected.map(str::to_owned) + ); +} + +// exercises the modern-profile early-return in +// migrate_legacy_loader_profile_if_needed. any of inheritsFrom, +// arguments, minecraftArguments present (or game_arguments absent) +// means "not legacy" and the function must return Ok(None) without +// touching the installer JSON path. +#[tokio::test] +async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() { + use LaunchProfile; + use chrono::Utc; + use tempfile::TempDir; + + let tmp = TempDir::new().unwrap(); + let instance_dir = tmp.path().join("instance"); + std::fs::create_dir_all(&instance_dir).unwrap(); + let profile_path = tmp.path().join("forge-1.20.1-47.2.0.json"); + std::fs::write(&profile_path, b"{}").unwrap(); + + let modern = LaunchProfile { + id: "1.20.1-forge-47.2.0".into(), + inherits_from: Some("1.20.1".into()), + main_class: Some("cpw.mods.bootstraplauncher.BootstrapLauncher".into()), + ..Default::default() + }; + + let config = InstanceConfig { + name: "test".into(), + game_version: "1.20.1".into(), + loader: ModLoader::Forge, + loader_version: Some("47.2.0".into()), + created: Utc::now(), + last_played: None, + java_path: None, + memory_max: None, + memory_min: None, + jvm_args: Vec::new(), + resolution: None, + config_sync_profile: None, + }; + + let result = + migrate_legacy_loader_profile_if_needed(&profile_path, &modern, &config, &instance_dir) + .await; + assert!( + matches!(result, Ok(None)), + "expected Ok(None), got {result:?}" + ); +} + +#[tokio::test] +async fn migrate_legacy_loader_profile_skips_fabric() { + // a fresh upstream Fabric profile happens to match the "legacy" + // shape (no inheritsFrom, no arguments, no minecraftArguments). + // make sure the migration helper recognises this is Fabric and + // returns Ok(None) instead of erroring with "reinstall Fabric". + use LaunchProfile; + use chrono::Utc; + use tempfile::TempDir; + + let tmp = TempDir::new().unwrap(); + let instance_dir = tmp.path().join("instance"); + std::fs::create_dir_all(&instance_dir).unwrap(); + let profile_path = tmp.path().join("fabric-1.20.1-0.14.21.json"); + std::fs::write(&profile_path, b"{}").unwrap(); + + let upstream_fabric_shape = LaunchProfile { + id: "fabric-loader-0.14.21-1.20.1".into(), + inherits_from: None, + main_class: Some("net.fabricmc.loader.impl.launch.knot.KnotClient".into()), + libraries: Vec::new(), + ..Default::default() + }; + + let config = InstanceConfig { + name: "test".into(), + game_version: "1.20.1".into(), + loader: ModLoader::Fabric, + loader_version: Some("0.14.21".into()), + created: Utc::now(), + last_played: None, + java_path: None, + memory_max: None, + memory_min: None, + jvm_args: Vec::new(), + resolution: None, + config_sync_profile: None, + }; + + let result = migrate_legacy_loader_profile_if_needed( + &profile_path, + &upstream_fabric_shape, + &config, + &instance_dir, + ) + .await; + + assert!( + matches!(result, Ok(None)), + "expected Ok(None), got {result:?}" + ); +} diff --git a/src/instance/tests/loader/forge.rs b/src/instance/tests/loader/forge.rs new file mode 100644 index 0000000..36ecc09 --- /dev/null +++ b/src/instance/tests/loader/forge.rs @@ -0,0 +1,55 @@ +use super::*; + +// builds an in-memory zip in a tempdir with the given json as +// install_profile.json. lets the legacy-install-profile detector be +// tested without an actual forge installer. +fn make_installer_zip(tmp: &std::path::Path, json: &serde_json::Value) -> std::path::PathBuf { + use std::io::Write; + let path = tmp.join("installer.jar"); + let file = std::fs::File::create(&path).unwrap(); + let mut zip = zip::ZipWriter::new(file); + let opts: zip::write::SimpleFileOptions = Default::default(); + zip.start_file("install_profile.json", opts).unwrap(); + zip.write_all(serde_json::to_string(json).unwrap().as_bytes()) + .unwrap(); + zip.finish().unwrap(); + path +} + +#[test] +fn has_legacy_install_profile_true_when_version_info_present() { + let tmp = tempfile::tempdir().unwrap(); + let jar = make_installer_zip( + tmp.path(), + &serde_json::json!({ + "install": {}, + "versionInfo": { + "id": "1.7.10-Forge10.13.4.1614-1.7.10", + "mainClass": "net.minecraft.launchwrapper.Launch" + } + }), + ); + assert!(has_legacy_install_profile(&jar)); +} + +#[test] +fn has_legacy_install_profile_false_when_version_info_absent() { + let tmp = tempfile::tempdir().unwrap(); + let jar = make_installer_zip( + tmp.path(), + &serde_json::json!({ + "spec": 1, + "minecraft": "1.20.1", + "data": {} + }), + ); + assert!(!has_legacy_install_profile(&jar)); +} + +#[test] +fn has_legacy_install_profile_false_for_missing_jar() { + let tmp = tempfile::tempdir().unwrap(); + assert!(!has_legacy_install_profile( + &tmp.path().join("missing-installer.jar") + )); +} diff --git a/src/instance/tests/loader/installers.rs b/src/instance/tests/loader/installers.rs new file mode 100644 index 0000000..0da7912 --- /dev/null +++ b/src/instance/tests/loader/installers.rs @@ -0,0 +1,144 @@ +use super::*; + +// the factory maps every ModLoader variant to its concrete installer. +// covering all five arms catches a misordered match or a copy-paste typo +// that would route, say, NeoForge to the Forge installer. +#[rstest::rstest] +#[case::vanilla(ModLoader::Vanilla)] +#[case::forge(ModLoader::Forge)] +#[case::neoforge(ModLoader::NeoForge)] +#[case::fabric(ModLoader::Fabric)] +#[case::quilt(ModLoader::Quilt)] +fn get_installer_returns_matching_loader_type(#[case] loader: ModLoader) { + let installer = get_installer(loader); + assert_eq!(installer.loader_type(), loader); +} + +#[test] +fn save_installer_profile_copies_raw_bytes_verbatim() { + use tempfile::TempDir; + let tmp = TempDir::new().unwrap(); + let instance_dir = tmp.path().join("instance"); + let meta_dir = tmp.path().join("meta"); + + // a synthetic installer version JSON with the modern arguments + // object - exactly the shape we used to strip. + let installer_json = br#"{ + "id": "1.20.1-forge-47.2.0", + "inheritsFrom": "1.20.1", + "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", + "libraries": [{ "name": "net.minecraftforge:forge:47.2.0" }], + "arguments": { + "game": ["--launchTarget", "forge_client"], + "jvm": ["--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler"] + } + }"#; + + let ver_dir = instance_dir + .join(crate::storage::MINECRAFT_DIR_NAME) + .join("versions") + .join("1.20.1-forge-47.2.0"); + std::fs::create_dir_all(&ver_dir).unwrap(); + let ver_json_path = ver_dir.join("1.20.1-forge-47.2.0.json"); + std::fs::write(&ver_json_path, installer_json).unwrap(); + + save_installer_profile( + &instance_dir, + &meta_dir, + "1.20.1-forge-47.2.0", + "forge-1.20.1-47.2.0.json", + ) + .unwrap(); + + let saved = std::fs::read( + meta_dir + .join("cache/loaders/profiles") + .join("forge-1.20.1-47.2.0.json"), + ) + .unwrap(); + assert_eq!( + saved, + installer_json.to_vec(), + "saved profile should be byte-for-byte identical to installer output" + ); +} + +// shape-pinning test: a synthetic versionInfo from a 1.7.10 forge +// install_profile.json must deserialise as a LaunchProfile so the +// launch flow's render_args + resolve pipeline can consume it. no +// filesystem round-trip; serde_json directly on the literal bytes. +#[test] +fn legacy_forge_version_info_deserialises_as_launch_profile() { + let bytes = br#"{ + "id": "1.7.10-Forge10.13.4.1614-1.7.10", + "mainClass": "net.minecraft.launchwrapper.Launch", + "minecraftArguments": "--username ${auth_player_name} --tweakClass cpw.mods.fml.common.launcher.FMLTweaker", + "libraries": [ + { "name": "net.minecraftforge:forge:10.13.4.1614", "url": "http://files.minecraftforge.net/maven/" }, + { "name": "net.minecraft:launchwrapper:1.9" } + ] + }"#; + + let profile: crate::launch_profile::model::LaunchProfile = + serde_json::from_slice(bytes).unwrap(); + assert_eq!(profile.id, "1.7.10-Forge10.13.4.1614-1.7.10"); + assert_eq!( + profile.main_class.as_deref(), + Some("net.minecraft.launchwrapper.Launch") + ); + // legacy forge profiles omit inheritsFrom; the launch flow's + // implicit fallback adds it before resolve. + assert!(profile.inherits_from.is_none()); + assert!( + profile + .minecraft_arguments + .as_deref() + .unwrap() + .contains("--tweakClass") + ); + assert_eq!(profile.libraries.len(), 2); + assert_eq!( + profile.libraries[0].name, + "net.minecraftforge:forge:10.13.4.1614" + ); + assert_eq!( + profile.libraries[0].url.as_deref(), + Some("http://files.minecraftforge.net/maven/") + ); + // legacy libs typically have no downloads.artifact; they resolve + // at launch time via maven_coord_to_path(name). + assert!(profile.libraries[0].downloads.is_none()); +} + +// shape-pinning test: a synthetic upstream fabric profile (no +// inheritsFrom, no arguments, libraries with name+url) must +// deserialise as a LaunchProfile so the install path can write it +// through to disk and the launch flow can read it back. +#[test] +fn raw_fabric_profile_bytes_parse_as_launch_profile() { + let bytes = br#"{ + "id": "fabric-loader-0.14.21-1.20.1", + "mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient", + "libraries": [ + { "name": "net.fabricmc:fabric-loader:0.14.21", "url": "https://maven.fabricmc.net/" }, + { "name": "net.fabricmc:intermediary:1.20.1", "url": "https://maven.fabricmc.net/" } + ] + }"#; + + let parsed: crate::launch_profile::model::LaunchProfile = + serde_json::from_slice(bytes).unwrap(); + assert_eq!(parsed.id, "fabric-loader-0.14.21-1.20.1"); + assert_eq!( + parsed.main_class.as_deref(), + Some("net.fabricmc.loader.impl.launch.knot.KnotClient") + ); + // upstream Fabric profiles omit inheritsFrom; the launch flow's + // implicit fallback handles it before resolve. + assert!(parsed.inherits_from.is_none()); + assert!(parsed.arguments.is_none()); + assert_eq!(parsed.libraries.len(), 2); + assert_eq!( + parsed.libraries[0].url.as_deref(), + Some("https://maven.fabricmc.net/") + ); +} diff --git a/src/instance/tests/loader/maven.rs b/src/instance/tests/loader/maven.rs new file mode 100644 index 0000000..8ee237d --- /dev/null +++ b/src/instance/tests/loader/maven.rs @@ -0,0 +1,32 @@ +use super::*; + +#[test] +fn maven_3_part_coord() { + assert_eq!( + maven_coord_to_path("org.example:artifact:1.0"), + Some("org/example/artifact/1.0/artifact-1.0.jar".to_string()) + ); +} + +#[test] +fn maven_4_part_coord_with_classifier() { + assert_eq!( + maven_coord_to_path("org.example:artifact:1.0:sources"), + Some("org/example/artifact/1.0/artifact-1.0-sources.jar".to_string()) + ); +} + +#[test] +fn maven_nested_group() { + assert_eq!( + maven_coord_to_path("com.google.code.gson:gson:2.10"), + Some("com/google/code/gson/gson/2.10/gson-2.10.jar".to_string()) + ); +} + +#[test] +fn maven_invalid_coordinates() { + for coordinate in ["org.example:artifact", "a:b:c:d:e", "just-a-string", ""] { + assert_eq!(maven_coord_to_path(coordinate), None); + } +} diff --git a/src/instance/tests/loader/vanilla.rs b/src/instance/tests/loader/vanilla.rs new file mode 100644 index 0000000..b9b7d11 --- /dev/null +++ b/src/instance/tests/loader/vanilla.rs @@ -0,0 +1,33 @@ +use super::*; +use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest}; + +#[test] +fn manifest_types_map_to_stable_game_versions() { + let manifest = VersionManifest { + latest: LatestVersions { + release: "1.21.1".to_owned(), + snapshot: "24w01a".to_owned(), + }, + versions: vec![ + VersionEntry { + id: "1.21.1".to_owned(), + version_type: "release".to_owned(), + url: String::new(), + sha1: String::new(), + }, + VersionEntry { + id: "24w01a".to_owned(), + version_type: "snapshot".to_owned(), + url: String::new(), + sha1: String::new(), + }, + ], + }; + + let versions = game_versions_from_manifest(manifest); + + assert_eq!(versions[0].id, "1.21.1"); + assert!(versions[0].stable); + assert_eq!(versions[1].id, "24w01a"); + assert!(!versions[1].stable); +} diff --git a/src/instance/tests/logs/files.rs b/src/instance/tests/logs/files.rs new file mode 100644 index 0000000..22518ac --- /dev/null +++ b/src/instance/tests/logs/files.rs @@ -0,0 +1,10 @@ +use super::*; + +#[test] +fn log_dir_builds_correct_path() { + let p = log_dir(Path::new("/instances"), "my-world"); + assert_eq!( + p, + PathBuf::from("/instances/my-world/minecraft/logs/launches") + ); +} diff --git a/src/instance/tests/logs/live.rs b/src/instance/tests/logs/live.rs new file mode 100644 index 0000000..9429b3c --- /dev/null +++ b/src/instance/tests/logs/live.rs @@ -0,0 +1,47 @@ +use super::*; + +#[test] +fn push_and_get_all() { + let name = "test_push_get"; + push(name, "line1"); + push(name, "line2"); + let lines = get_all(name); + assert!(lines.contains(&"line1".to_string())); + assert!(lines.contains(&"line2".to_string())); +} + +#[test] +fn get_all_missing_instance_returns_empty() { + let lines = get_all("nonexistent_instance_xyz"); + assert!(lines.is_empty()); +} + +#[test] +fn clear_removes_instance() { + let name = "test_clear"; + push(name, "data"); + assert!(!get_all(name).is_empty()); + clear(name); + assert!(get_all(name).is_empty()); +} + +#[test] +fn clear_nonexistent_is_noop() { + clear("never_existed_xyz"); +} + +#[test] +fn buffer_respects_max_lines() { + let name = "test_max_lines"; + for i in 0..(MAX_LINES + 100) { + push(name, format!("line-{i}")); + } + let lines = get_all(name); + assert_eq!(lines.len(), MAX_LINES); + assert!( + lines + .last() + .unwrap() + .contains(&format!("{}", MAX_LINES + 99)) + ); +} diff --git a/src/instance/tests/manager.rs b/src/instance/tests/manager.rs new file mode 100644 index 0000000..a56f9a5 --- /dev/null +++ b/src/instance/tests/manager.rs @@ -0,0 +1,166 @@ +use super::*; +use crate::instance::models::ModLoader; +use tempfile::TempDir; + +// tmp owns the temp directory; its Drop impl cleans up everything when +// the test ends. the returned InstanceManager points at tmp.path() so +// tests can join("name") off of either to refer to the same locations. +fn test_manager() -> (InstanceManager, TempDir) { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + std::fs::create_dir_all(&meta).unwrap(); + (InstanceManager::new(tmp.path().to_path_buf(), meta), tmp) +} + +fn dummy_config(name: &str) -> InstanceConfig { + InstanceConfig { + name: name.to_string(), + game_version: "1.20.1".to_string(), + loader: ModLoader::Vanilla, + loader_version: None, + created: chrono::Utc::now(), + last_played: None, + java_path: None, + memory_max: None, + memory_min: None, + jvm_args: vec![], + resolution: None, + config_sync_profile: None, + } +} + +#[test] +fn validate_name_accepts_safe_names() { + assert!(validate_name("my-instance").is_ok()); + assert!(validate_name("test_world").is_ok()); +} + +#[test] +fn validate_name_rejects_empty_traversal_and_hidden() { + assert!(validate_name("").is_err()); + assert!(validate_name("path/traversal").is_err()); + assert!(validate_name(".hidden").is_err()); +} + +#[test] +fn delete_missing_instance_returns_not_found() { + let (manager, _tmp) = test_manager(); + let result = manager.delete("ghost-instance"); + assert!(matches!(result, Err(InstanceError::NotFound(_)))); +} + +#[test] +fn save_then_load_all_round_trips_config() { + let (manager, tmp) = test_manager(); + std::fs::create_dir_all(tmp.path().join("test-save")).unwrap(); + manager.save(&dummy_config("test-save")).expect("save"); + + let all = manager.load_all(); + assert_eq!(all.len(), 1); + assert_eq!(all[0].name, "test-save"); + assert_eq!(all[0].game_version, "1.20.1"); +} + +#[test] +fn load_all_accepts_numeric_memory() { + let (manager, tmp) = test_manager(); + let instance_dir = tmp.path().join("test-memory"); + std::fs::create_dir_all(&instance_dir).unwrap(); + std::fs::write( + instance_dir.join("instance.json"), + r#"{ + "name": "test-memory", + "game_version": "1.7.10", + "loader": "forge", + "loader_version": "10.13.4.1614", + "created": "2026-04-20T18:04:25.567993893Z", + "memory_max": 8, + "memory_min": 512 +}"#, + ) + .expect("write config"); + + let all = manager.load_all(); + assert_eq!(all.len(), 1); + assert_eq!(all[0].memory_max.as_deref(), Some("8G")); + assert_eq!(all[0].memory_min.as_deref(), Some("512M")); +} + +#[test] +fn load_one_missing_returns_not_found() { + let (manager, _tmp) = test_manager(); + let result = manager.load_one("ghost-instance"); + assert!(matches!(result, Err(InstanceError::NotFound(_)))); +} + +#[test] +fn rename_moves_dir_and_updates_config_name() { + let (manager, tmp) = test_manager(); + let old_dir = tmp.path().join("old-name"); + std::fs::create_dir_all(&old_dir).unwrap(); + manager.save(&dummy_config("old-name")).expect("save"); + + manager.rename("old-name", "new-name").expect("rename"); + + assert!(!old_dir.exists(), "old dir should be gone"); + let new_dir = tmp.path().join("new-name"); + assert!(new_dir.exists(), "new dir should exist"); + let reloaded = manager.load_one("new-name").expect("load_one new-name"); + assert_eq!(reloaded.name, "new-name"); +} + +#[test] +fn rename_to_same_name_is_noop() { + let (manager, tmp) = test_manager(); + let dir = tmp.path().join("same"); + std::fs::create_dir_all(&dir).unwrap(); + manager.save(&dummy_config("same")).expect("save"); + manager.rename("same", "same").expect("noop rename"); + assert!(dir.exists()); +} + +#[test] +fn rename_empty_target_rejects() { + let (manager, tmp) = test_manager(); + std::fs::create_dir_all(tmp.path().join("orig")).unwrap(); + manager.save(&dummy_config("orig")).expect("save"); + let err = manager.rename("orig", " ").unwrap_err(); + assert!(matches!(err, InstanceError::InvalidName(_))); +} + +#[test] +fn rename_missing_source_errors() { + let (manager, _tmp) = test_manager(); + let err = manager.rename("ghost", "anything").unwrap_err(); + assert!(matches!(err, InstanceError::NotFound(_))); +} + +#[test] +fn rename_target_exists_errors() { + let (manager, tmp) = test_manager(); + std::fs::create_dir_all(tmp.path().join("source")).unwrap(); + std::fs::create_dir_all(tmp.path().join("collision")).unwrap(); + manager.save(&dummy_config("source")).expect("save src"); + manager.save(&dummy_config("collision")).expect("save dst"); + let err = manager.rename("source", "collision").unwrap_err(); + assert!(matches!(err, InstanceError::AlreadyExists(_))); +} + +#[test] +fn touch_last_played_updates_field() { + let (manager, tmp) = test_manager(); + std::fs::create_dir_all(tmp.path().join("ticker")).unwrap(); + manager.save(&dummy_config("ticker")).expect("save"); + assert!(manager.load_one("ticker").unwrap().last_played.is_none()); + + manager.touch_last_played("ticker").expect("touch"); + let reloaded = manager.load_one("ticker").unwrap(); + let stamp = reloaded + .last_played + .expect("last_played should be Some now"); + let age = chrono::Utc::now() - stamp; + assert!( + age.num_seconds().abs() < 5, + "last_played should be roughly now, got age {age:?}" + ); +} diff --git a/src/instance/tests/models.rs b/src/instance/tests/models.rs new file mode 100644 index 0000000..6189ed7 --- /dev/null +++ b/src/instance/tests/models.rs @@ -0,0 +1,79 @@ +use super::*; + +#[test] +fn instance_config_roundtrips_through_json() { + let config = InstanceConfig { + name: "test".to_string(), + game_version: "1.20.1".to_string(), + loader: ModLoader::Fabric, + loader_version: Some("0.15.0".to_string()), + created: Utc::now(), + last_played: None, + java_path: None, + memory_max: Some("4G".to_string()), + memory_min: Some("512M".to_string()), + jvm_args: vec![], + resolution: Some((1920, 1080)), + config_sync_profile: None, + }; + let json = serde_json::to_string_pretty(&config).expect("serialize"); + let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(parsed.name, config.name); + assert_eq!(parsed.game_version, config.game_version); + assert_eq!(parsed.loader, config.loader); + assert_eq!(parsed.resolution, config.resolution); +} + +#[test] +fn instance_config_accepts_numeric_memory() { + let json = r#" + { + "name": "test", + "game_version": "1.7.10", + "loader": "forge", + "loader_version": "10.13.4.1614", + "created": "2026-04-20T18:04:25.567993893Z", + "memory_max": 8, + "memory_min": 512 + } + "#; + let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize"); + assert_eq!(parsed.memory_max.as_deref(), Some("8G")); + assert_eq!(parsed.memory_min.as_deref(), Some("512M")); +} + +#[test] +fn normalize_memory_value_handles_bare_numbers() { + assert_eq!(normalize_memory_value("8").as_deref(), Some("8G")); + assert_eq!(normalize_memory_value("4096").as_deref(), Some("4096M")); + assert_eq!(normalize_memory_value("8G").as_deref(), Some("8G")); + assert_eq!(normalize_memory_value("2048m").as_deref(), Some("2048M")); + assert_eq!(normalize_memory_value(""), None); +} + +#[test] +fn instance_config_ignores_invalid_memory_values() { + let json = r#" + { + "name": "test", + "game_version": "1.7.10", + "loader": "forge", + "loader_version": "10.13.4.1614", + "created": "2026-04-20T18:04:25.567993893Z", + "memory_max": ["8G"], + "memory_min": "8GB" + } + "#; + let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize"); + assert_eq!(parsed.memory_max, None); + assert_eq!(parsed.memory_min, None); +} + +#[test] +fn normalize_memory_value_rejects_invalid_values() { + assert_eq!(normalize_memory_value("0"), None); + assert_eq!(normalize_memory_value("-1"), None); + assert_eq!(normalize_memory_value("1.5G"), None); + assert_eq!(normalize_memory_value("8GB"), None); + assert_eq!(normalize_memory_value("banana"), None); +} diff --git a/src/instance/tests/runtime.rs b/src/instance/tests/runtime.rs new file mode 100644 index 0000000..8a5358d --- /dev/null +++ b/src/instance/tests/runtime.rs @@ -0,0 +1,75 @@ +use super::*; + +#[test] +fn set_and_get_state() { + set_state("run_test_1", RunState::Starting); + assert_eq!(get("run_test_1"), Some(RunState::Starting)); +} + +#[test] +fn get_missing_returns_none() { + assert_eq!(get("run_never_set_xyz"), None); +} + +#[test] +fn remove_clears_state() { + set_state("run_test_2", RunState::Running); + remove("run_test_2"); + assert_eq!(get("run_test_2"), None); +} + +#[test] +fn set_state_overwrites() { + set_state("run_test_3", RunState::Starting); + set_state("run_test_3", RunState::Running); + assert_eq!(get("run_test_3"), Some(RunState::Running)); +} + +#[test] +fn all_returns_entries() { + set_state("run_test_all_a", RunState::Running); + let entries = all(); + assert!(entries.iter().any(|(k, _)| k == "run_test_all_a")); +} + +#[test] +fn crashed_state_stores_exit_code() { + set_state("run_test_crash", RunState::Crashed(Some(1))); + assert_eq!(get("run_test_crash"), Some(RunState::Crashed(Some(1)))); +} + +#[test] +fn push_and_drain_last_played() { + let time = Utc::now(); + push_last_played("run_test_lp", time); + let drained = drain_last_played(); + assert!(drained.iter().any(|(k, _)| k == "run_test_lp")); +} + +// Removed drain_empty_returns_empty: it relied on no other test pushing +// to LAST_PLAYED between the two drain calls, which races with the +// parallel push_and_drain_last_played test. The drain semantics are +// already covered by push_and_drain_last_played, which asserts a +// specific entry is present, and the empty-result path is exercised +// implicitly any time drain runs after that test's cleanup. + +#[test] +fn send_kill_returns_false_for_missing() { + assert!(!send_kill("run_never_registered_xyz")); +} + +#[test] +fn register_and_send_kill() { + let (tx, mut rx) = tokio::sync::oneshot::channel::<()>(); + register_kill("run_test_kill", tx); + assert!(send_kill("run_test_kill")); + let _ = rx.try_recv(); +} + +#[test] +fn cleanup_kill_sender_removes() { + let (tx, _rx) = tokio::sync::oneshot::channel::<()>(); + register_kill("run_test_cleanup", tx); + cleanup_kill_sender("run_test_cleanup"); + assert!(!send_kill("run_test_cleanup")); +} diff --git a/src/launch_profile/model.rs b/src/launch_profile/model.rs index 127c3ed..94df4b7 100644 --- a/src/launch_profile/model.rs +++ b/src/launch_profile/model.rs @@ -111,171 +111,5 @@ pub struct Download { } #[cfg(test)] -mod tests { - use super::*; - use crate::launch_profile::rules::RuleAction; - - const MODERN_FIXTURE: &str = r#"{ - "id": "1.20.1", - "type": "release", - "mainClass": "net.minecraft.client.main.Main", - "assetIndex": { - "id": "5", - "url": "https://example.invalid/5.json", - "sha1": "0000000000000000000000000000000000000000" - }, - "javaVersion": { - "component": "java-runtime-gamma", - "majorVersion": 17 - }, - "libraries": [ - { - "name": "org.lwjgl:lwjgl:3.3.1", - "downloads": { - "artifact": { - "url": "https://example.invalid/lwjgl.jar", - "path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar", - "sha1": "1111111111111111111111111111111111111111", - "size": 100 - } - }, - "rules": [ - { "action": "allow", "os": { "name": "linux" } } - ] - } - ], - "arguments": { - "game": [ - "--username", "${auth_player_name}", - { - "rules": [{ "action": "allow", "features": { "is_demo_user": true } }], - "value": "--demo" - } - ], - "jvm": [ - "-Djava.library.path=${natives_directory}", - { - "rules": [{ "action": "allow", "os": { "name": "osx" } }], - "value": ["-XstartOnFirstThread"] - } - ] - } - }"#; - - const LEGACY_FIXTURE: &str = r#"{ - "id": "1.7.10", - "type": "release", - "mainClass": "net.minecraft.client.main.Main", - "minecraftArguments": "--username ${auth_player_name} --version ${version_name} --gameDir ${game_directory}", - "assetIndex": { - "id": "1.7.10", - "url": "https://example.invalid/1.7.10.json", - "sha1": "0000000000000000000000000000000000000000" - }, - "libraries": [] - }"#; - - const LOADER_FIXTURE: &str = r#"{ - "id": "1.20.1-forge-47.2.0", - "inheritsFrom": "1.20.1", - "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", - "libraries": [ - { "name": "net.minecraftforge:forge:47.2.0" } - ], - "arguments": { - "game": ["--launchTarget", "forge_client"], - "jvm": [ - "--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler", - "-DlibraryDirectory=${library_directory}" - ] - } - }"#; - - #[test] - fn parses_modern_arguments_object() { - let profile: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap(); - assert_eq!(profile.id, "1.20.1"); - assert_eq!( - profile.main_class.as_deref(), - Some("net.minecraft.client.main.Main") - ); - assert!(profile.inherits_from.is_none()); - assert!(profile.minecraft_arguments.is_none()); - - let args = profile.arguments.as_ref().expect("arguments present"); - assert_eq!(args.game.len(), 3); - assert_eq!(args.jvm.len(), 2); - - // first game arg should be a literal "--username" - match &args.game[0] { - Argument::Literal(s) => assert_eq!(s, "--username"), - _ => panic!("expected literal"), - } - // third game arg should be a conditional with a single-string value - match &args.game[2] { - Argument::Conditional { rules, value } => { - assert_eq!(rules.len(), 1); - assert_eq!(rules[0].action, RuleAction::Allow); - assert!(matches!(value, ArgumentValue::Single(_))); - } - _ => panic!("expected conditional"), - } - // second jvm arg should be a conditional with a multi-string value - match &args.jvm[1] { - Argument::Conditional { value, .. } => { - assert!(matches!(value, ArgumentValue::Multiple(_))); - } - _ => panic!("expected conditional"), - } - } - - #[test] - fn parses_legacy_minecraft_arguments_string() { - let profile: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap(); - assert_eq!(profile.id, "1.7.10"); - assert!(profile.arguments.is_none()); - assert!( - profile - .minecraft_arguments - .as_deref() - .unwrap() - .contains("${version_name}") - ); - assert!(profile.libraries.is_empty()); - } - - #[test] - fn parses_loader_profile_with_inherits_from() { - let profile: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap(); - assert_eq!(profile.id, "1.20.1-forge-47.2.0"); - assert_eq!(profile.inherits_from.as_deref(), Some("1.20.1")); - assert!(profile.asset_index.is_none()); // inherited from parent - let args = profile.arguments.as_ref().unwrap(); - assert_eq!(args.game.len(), 2); - assert_eq!(args.jvm.len(), 3); - } - - #[test] - fn modern_profile_round_trips() { - let original: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap(); - let serialized = serde_json::to_string(&original).unwrap(); - let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap(); - assert_eq!(original, reparsed); - } - - #[test] - fn loader_profile_round_trips() { - let original: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap(); - let serialized = serde_json::to_string(&original).unwrap(); - let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap(); - assert_eq!(original, reparsed); - } - - #[test] - fn legacy_profile_round_trips() { - let original: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap(); - let serialized = serde_json::to_string(&original).unwrap(); - let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap(); - assert_eq!(original, reparsed); - } -} +#[path = "tests/model.rs"] +mod tests; diff --git a/src/launch_profile/render.rs b/src/launch_profile/render.rs index 24923f2..9cfa0d3 100644 --- a/src/launch_profile/render.rs +++ b/src/launch_profile/render.rs @@ -79,283 +79,5 @@ fn push_argument( } #[cfg(test)] -mod tests { - use super::*; - use crate::launch_profile::model::Arguments; - use crate::launch_profile::rules::{FeatureSet, OsCondition, Rule, RuleAction}; - use std::path::PathBuf; - - // owns the path buffers + FeatureSet so each test just calls - // fx.template_ctx() and fx.rule_ctx() instead of declaring four PathBufs - // and a RuleContext inline. all tests use linux/x86_64; if a test needs - // a different OS it sets it explicitly. - struct Fixture { - lib: PathBuf, - nat: PathBuf, - game: PathBuf, - assets: PathBuf, - features: FeatureSet, - } - - impl Fixture { - fn new() -> Self { - Self { - lib: PathBuf::from("/m/libraries"), - nat: PathBuf::from("/m/natives"), - game: PathBuf::from("/i/.minecraft"), - assets: PathBuf::from("/m/assets"), - features: FeatureSet::default(), - } - } - - fn template_ctx(&self) -> TemplateContext<'_> { - TemplateContext { - library_directory: &self.lib, - classpath_separator: ":", - version_name: "1.20.1", - version_type: "release", - natives_directory: &self.nat, - classpath: "a.jar:b.jar", - game_directory: &self.game, - assets_root: &self.assets, - assets_index_name: "5", - auth_player_name: "Player", - auth_uuid: "00000000-0000-0000-0000-000000000000", - auth_access_token: "token", - auth_xuid: "0", - user_type: "msa", - user_properties: "{}", - launcher_name: "rmcl", - launcher_version: "0.3.0", - clientid: "0", - } - } - - fn rule_ctx(&self) -> RuleContext<'_> { - RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &self.features, - } - } - } - - fn minimal_profile() -> LaunchProfile { - LaunchProfile { - id: "test".into(), - main_class: Some("net.test.Main".into()), - ..Default::default() - } - } - - #[test] - fn legacy_minecraft_arguments_render_into_game() { - let fx = Fixture::new(); - let mut profile = minimal_profile(); - profile.minecraft_arguments = - Some("--username ${auth_player_name} --version ${version_name}".into()); - - let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); - assert_eq!(rendered.main_class, "net.test.Main"); - assert!(rendered.jvm.is_empty()); - assert_eq!( - rendered.game, - vec!["--username", "Player", "--version", "1.20.1"] - ); - } - - #[test] - fn modern_arguments_render_with_literals_and_substitutions() { - let fx = Fixture::new(); - let mut profile = minimal_profile(); - profile.arguments = Some(Arguments { - game: vec![ - Argument::Literal("--username".into()), - Argument::Literal("${auth_player_name}".into()), - ], - jvm: vec![Argument::Literal( - "-Djava.library.path=${natives_directory}".into(), - )], - }); - - let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); - assert_eq!(rendered.game, vec!["--username", "Player"]); - assert_eq!(rendered.jvm, vec!["-Djava.library.path=/m/natives"]); - } - - #[test] - fn conditional_argument_with_single_value_is_filtered_by_os_rule() { - let fx = Fixture::new(); - let osx_only = Argument::Conditional { - rules: vec![Rule { - action: RuleAction::Allow, - os: Some(OsCondition { - name: Some("osx".into()), - arch: None, - ..Default::default() - }), - features: None, - }], - value: ArgumentValue::Single("-XstartOnFirstThread".into()), - }; - - let mut profile = minimal_profile(); - profile.arguments = Some(Arguments { - game: Vec::new(), - jvm: vec![osx_only], - }); - - let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); - assert!( - rendered.jvm.is_empty(), - "osx-only arg should be skipped on linux" - ); - } - - #[test] - fn conditional_argument_with_multiple_value_pushes_all() { - let fx = Fixture::new(); - let linux_arg = Argument::Conditional { - rules: vec![Rule { - action: RuleAction::Allow, - os: Some(OsCondition { - name: Some("linux".into()), - arch: None, - ..Default::default() - }), - features: None, - }], - value: ArgumentValue::Multiple(vec![ - "--add-opens".into(), - "java.base/sun.security.util=ALL-UNNAMED".into(), - ]), - }; - - let mut profile = minimal_profile(); - profile.arguments = Some(Arguments { - game: Vec::new(), - jvm: vec![linux_arg], - }); - - let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); - assert_eq!( - rendered.jvm, - vec!["--add-opens", "java.base/sun.security.util=ALL-UNNAMED"] - ); - } - - #[test] - fn missing_main_class_returns_error() { - let fx = Fixture::new(); - let mut profile = minimal_profile(); - profile.main_class = None; - - let result = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()); - assert!(matches!(result, Err(RenderError::MissingMainClass))); - } - - #[tokio::test] - async fn end_to_end_resolve_then_render_modern_forge_shape() { - // exercises the full pipeline: load a synthetic vanilla profile - // from disk, load a synthetic loader profile with inheritsFrom, - // resolve the chain, then render args. catches integration bugs - // that unit tests of each layer would miss. - use crate::launch_profile::resolve; - use tempfile::TempDir; - - let tmp = TempDir::new().unwrap(); - let vanilla_path = tmp - .path() - .join("cache/minecraft/versions") - .join("1.20.1") - .join("meta.json"); - std::fs::create_dir_all(vanilla_path.parent().unwrap()).unwrap(); - let vanilla_json = br#"{ - "id": "1.20.1", - "mainClass": "net.minecraft.client.main.Main", - "libraries": [ - { - "name": "org.lwjgl:lwjgl:3.3.1", - "downloads": { - "artifact": { - "url": "https://example.invalid/lwjgl.jar", - "path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar", - "sha1": "1111111111111111111111111111111111111111", - "size": 100 - } - } - } - ], - "arguments": { - "game": ["--username", "${auth_player_name}", "--version", "${version_name}"], - "jvm": ["-Djava.library.path=${natives_directory}"] - } - }"#; - std::fs::write(&vanilla_path, vanilla_json).unwrap(); - - let loader_json = r#"{ - "id": "1.20.1-forge-47.2.0", - "inheritsFrom": "1.20.1", - "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", - "libraries": [ - { "name": "net.minecraftforge:forge:47.2.0" } - ], - "arguments": { - "game": ["--launchTarget", "forge_client"], - "jvm": [ - "--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler" - ] - } - }"#; - let loader_profile: LaunchProfile = serde_json::from_str(loader_json).unwrap(); - - let merged = resolve::resolve(loader_profile, tmp.path()).await.unwrap(); - - let fx = Fixture::new(); - let rendered = render_args(&merged, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); - - // child main_class wins after merge - assert_eq!( - rendered.main_class, - "cpw.mods.bootstraplauncher.BootstrapLauncher" - ); - // game args: parent first then child - assert_eq!( - rendered.game, - vec![ - "--username", - "Player", - "--version", - "1.20.1", - "--launchTarget", - "forge_client" - ] - ); - // jvm args: parent first then child - assert_eq!( - rendered.jvm, - vec![ - "-Djava.library.path=/m/natives", - "--add-opens", - "java.base/sun.security.util=cpw.mods.securejarhandler" - ] - ); - } - - #[test] - fn modern_arguments_takes_precedence_over_legacy_field() { - // a profile that somehow has both arguments and minecraft_arguments - // should use arguments only (legacy is fallback). - let fx = Fixture::new(); - let mut profile = minimal_profile(); - profile.arguments = Some(Arguments { - game: vec![Argument::Literal("--from-arguments".into())], - jvm: Vec::new(), - }); - profile.minecraft_arguments = Some("--from-legacy".into()); - - let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); - assert_eq!(rendered.game, vec!["--from-arguments"]); - } -} +#[path = "tests/render.rs"] +mod tests; diff --git a/src/launch_profile/resolve.rs b/src/launch_profile/resolve.rs index b7e793c..d325b1f 100644 --- a/src/launch_profile/resolve.rs +++ b/src/launch_profile/resolve.rs @@ -149,424 +149,5 @@ pub async fn resolve( } #[cfg(test)] -mod tests { - use super::*; - use crate::launch_profile::model::{Argument, ArgumentValue, AssetIndex, JavaVersion, Library}; - use crate::launch_profile::rules::{Rule, RuleAction}; - - fn empty_profile(id: &str) -> LaunchProfile { - LaunchProfile { - id: id.into(), - ..Default::default() - } - } - - fn lib(name: &str) -> Library { - Library { - name: name.into(), - ..Default::default() - } - } - - fn allow_linux_rule() -> Rule { - Rule { - action: RuleAction::Allow, - os: Some(crate::launch_profile::rules::OsCondition { - name: Some("linux".into()), - ..Default::default() - }), - features: None, - } - } - - #[test] - fn child_id_wins() { - let mut child = empty_profile("child"); - let parent = empty_profile("parent"); - child.main_class = None; - let merged = merge_into(child, parent); - assert_eq!(merged.id, "child"); - } - - #[test] - fn merge_carries_parent_inherits_from() { - // merge_into preserves parent's inherits_from so resolve() can keep - // walking. resolve() itself clears the final result's inherits_from - // after the loop exits. - let mut child = empty_profile("child"); - child.inherits_from = Some("parent".into()); - let mut parent = empty_profile("parent"); - parent.inherits_from = Some("grandparent".into()); - let merged = merge_into(child, parent); - assert_eq!(merged.inherits_from.as_deref(), Some("grandparent")); - } - - #[test] - fn merge_with_root_parent_clears_inherits_from() { - // parent with no inherits_from means the chain ends. - let mut child = empty_profile("child"); - child.inherits_from = Some("parent".into()); - let parent = empty_profile("parent"); - let merged = merge_into(child, parent); - assert!(merged.inherits_from.is_none()); - } - - #[test] - fn child_main_class_overrides_parent() { - let mut child = empty_profile("child"); - let mut parent = empty_profile("parent"); - child.main_class = Some("child.Main".into()); - parent.main_class = Some("parent.Main".into()); - let merged = merge_into(child, parent); - assert_eq!(merged.main_class.as_deref(), Some("child.Main")); - } - - #[test] - fn parent_main_class_used_when_child_missing() { - let child = empty_profile("child"); - let mut parent = empty_profile("parent"); - parent.main_class = Some("parent.Main".into()); - let merged = merge_into(child, parent); - assert_eq!(merged.main_class.as_deref(), Some("parent.Main")); - } - - #[test] - fn libraries_are_concatenated_parent_first() { - let mut child = empty_profile("child"); - let mut parent = empty_profile("parent"); - parent.libraries = vec![lib("p1"), lib("p2")]; - child.libraries = vec![lib("c1")]; - let merged = merge_into(child, parent); - let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect(); - assert_eq!(names, vec!["p1", "p2", "c1"]); - } - - #[test] - fn child_library_supersedes_parent_with_same_group_artifact() { - // forge declares log4j 2.17.0; vanilla declared 2.0-beta9. without - // dedup, both end up on the classpath and the JVM picks the first - // (vanilla) match - defeating forge's override. dedup keeps child's. - let mut child = empty_profile("forge"); - let mut parent = empty_profile("vanilla"); - parent.libraries = vec![ - lib("org.apache.logging.log4j:log4j-core:2.0-beta9"), - lib("org.lwjgl:lwjgl:3.3.1"), - ]; - child.libraries = vec![ - lib("org.apache.logging.log4j:log4j-core:2.17.0"), - lib("net.minecraftforge:forge:47.2.0"), - ]; - let merged = merge_into(child, parent); - let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect(); - // parent's log4j-core is filtered (superseded by child); parent's - // lwjgl stays (no conflict); child's log4j and forge come last. - assert_eq!( - names, - vec![ - "org.lwjgl:lwjgl:3.3.1", - "org.apache.logging.log4j:log4j-core:2.17.0", - "net.minecraftforge:forge:47.2.0", - ] - ); - } - - #[test] - fn coord_key_extracts_group_artifact() { - assert_eq!(coord_key("org.lwjgl:lwjgl:3.3.1"), "org.lwjgl:lwjgl"); - assert_eq!( - coord_key("org.apache.logging.log4j:log4j-core:2.17.0"), - "org.apache.logging.log4j:log4j-core" - ); - // with classifier - assert_eq!( - coord_key("org.lwjgl:lwjgl:3.3.1:natives-linux"), - "org.lwjgl:lwjgl" - ); - // malformed (no colons) - return as-is - assert_eq!(coord_key("malformed"), "malformed"); - } - - #[test] - fn arguments_are_concatenated_parent_first() { - let mut child = empty_profile("child"); - let mut parent = empty_profile("parent"); - parent.arguments = Some(Arguments { - game: vec![Argument::Literal("--from-parent-game".into())], - jvm: vec![Argument::Literal("--from-parent-jvm".into())], - }); - child.arguments = Some(Arguments { - game: vec![Argument::Literal("--from-child-game".into())], - jvm: vec![Argument::Literal("--from-child-jvm".into())], - }); - let merged = merge_into(child, parent); - let args = merged.arguments.expect("arguments present"); - assert_eq!( - args.game, - vec![ - Argument::Literal("--from-parent-game".into()), - Argument::Literal("--from-child-game".into()), - ] - ); - assert_eq!( - args.jvm, - vec![ - Argument::Literal("--from-parent-jvm".into()), - Argument::Literal("--from-child-jvm".into()), - ] - ); - } - - #[test] - fn arguments_from_child_only_carry_through() { - let mut child = empty_profile("child"); - let parent = empty_profile("parent"); - child.arguments = Some(Arguments { - game: vec![Argument::Literal("--child".into())], - jvm: Vec::new(), - }); - let merged = merge_into(child, parent); - let args = merged.arguments.expect("arguments present"); - assert_eq!(args.game.len(), 1); - assert!(args.jvm.is_empty()); - } - - #[test] - fn arguments_from_parent_only_carry_through() { - let child = empty_profile("child"); - let mut parent = empty_profile("parent"); - parent.arguments = Some(Arguments { - game: Vec::new(), - jvm: vec![Argument::Literal("--parent-jvm".into())], - }); - let merged = merge_into(child, parent); - let args = merged.arguments.expect("arguments present"); - assert!(args.game.is_empty()); - assert_eq!(args.jvm.len(), 1); - } - - #[test] - fn conditional_arguments_with_rules_survive_merge() { - // make sure the Argument::Conditional shape isn't accidentally - // flattened or filtered during merging - rule eval happens later - // at render time, not during merge. - let mut child = empty_profile("child"); - let parent = empty_profile("parent"); - child.arguments = Some(Arguments { - game: vec![Argument::Conditional { - rules: vec![allow_linux_rule()], - value: ArgumentValue::Single("--linux-only".into()), - }], - jvm: Vec::new(), - }); - let merged = merge_into(child, parent); - let args = merged.arguments.expect("arguments present"); - match &args.game[0] { - Argument::Conditional { rules, .. } => { - assert_eq!(rules.len(), 1); - assert_eq!(rules[0].action, RuleAction::Allow); - } - _ => panic!("expected conditional argument to survive merge"), - } - } - - #[test] - fn legacy_minecraft_arguments_child_overrides_parent() { - let mut child = empty_profile("child"); - let mut parent = empty_profile("parent"); - child.minecraft_arguments = Some("--child".into()); - parent.minecraft_arguments = Some("--parent".into()); - let merged = merge_into(child, parent); - assert_eq!(merged.minecraft_arguments.as_deref(), Some("--child")); - } - - #[test] - fn asset_index_inherits_from_parent_when_child_absent() { - let child = empty_profile("child"); - let mut parent = empty_profile("parent"); - parent.asset_index = Some(AssetIndex { - id: "5".into(), - url: "https://example.invalid/5.json".into(), - sha1: "0".repeat(40), - size: None, - total_size: None, - }); - let merged = merge_into(child, parent); - assert!(merged.asset_index.is_some()); - assert_eq!(merged.asset_index.unwrap().id, "5"); - } - - #[test] - fn java_version_inherits_from_parent_when_child_absent() { - let child = empty_profile("child"); - let mut parent = empty_profile("parent"); - parent.java_version = Some(JavaVersion { - component: Some("java-runtime-gamma".into()), - major_version: 17, - }); - let merged = merge_into(child, parent); - assert_eq!( - merged.java_version.as_ref().map(|j| j.major_version), - Some(17) - ); - } - - use tempfile::TempDir; - - fn write_profile(meta_dir: &Path, profile: &LaunchProfile) { - let path = meta_dir - .join("cache/minecraft/versions") - .join(&profile.id) - .join("meta.json"); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - let json = serde_json::to_string_pretty(profile).unwrap(); - std::fs::write(&path, json).unwrap(); - } - - #[tokio::test] - async fn resolve_returns_unchanged_when_no_inherits_from() { - let tmp = TempDir::new().unwrap(); - let profile = empty_profile("standalone"); - let resolved = resolve(profile, tmp.path()).await.unwrap(); - assert_eq!(resolved.id, "standalone"); - assert!(resolved.inherits_from.is_none()); - } - - #[tokio::test] - async fn resolve_single_level_inheritance_merges_parent() { - let tmp = TempDir::new().unwrap(); - - let mut parent = empty_profile("1.20.1"); - parent.main_class = Some("net.minecraft.client.main.Main".into()); - parent.libraries = vec![lib("vanilla-lib")]; - write_profile(tmp.path(), &parent); - - let mut child = empty_profile("1.20.1-forge-47.2.0"); - child.inherits_from = Some("1.20.1".into()); - child.libraries = vec![lib("forge-lib")]; - - let resolved = resolve(child, tmp.path()).await.unwrap(); - assert_eq!(resolved.id, "1.20.1-forge-47.2.0"); - assert!(resolved.inherits_from.is_none()); - assert_eq!( - resolved.main_class.as_deref(), - Some("net.minecraft.client.main.Main") - ); - let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect(); - assert_eq!(names, vec!["vanilla-lib", "forge-lib"]); - } - - #[tokio::test] - async fn resolve_errors_when_parent_missing() { - let tmp = TempDir::new().unwrap(); - - let mut child = empty_profile("1.20.1-forge-47.2.0"); - child.inherits_from = Some("1.20.1".into()); - - let err = resolve(child, tmp.path()).await.unwrap_err(); - assert!( - matches!(err, ResolveError::ParentNotFound(_)), - "expected ParentNotFound, got {err:?}" - ); - } - - #[tokio::test] - async fn resolve_errors_when_parent_is_invalid_json() { - let tmp = TempDir::new().unwrap(); - - let parent_path = tmp - .path() - .join("cache/minecraft/versions") - .join("1.20.1") - .join("meta.json"); - std::fs::create_dir_all(parent_path.parent().unwrap()).unwrap(); - std::fs::write(&parent_path, "{ not valid json").unwrap(); - - let mut child = empty_profile("1.20.1-forge-47.2.0"); - child.inherits_from = Some("1.20.1".into()); - - let err = resolve(child, tmp.path()).await.unwrap_err(); - assert!( - matches!(err, ResolveError::ParseError(_, _)), - "expected ParseError, got {err:?}" - ); - } - - #[tokio::test] - async fn resolve_multi_level_chain_merges_all_parents() { - let tmp = TempDir::new().unwrap(); - - // chain: grandchild -> child -> root (vanilla). - let mut root = empty_profile("1.20.1"); - root.main_class = Some("net.minecraft.client.main.Main".into()); - root.libraries = vec![lib("vanilla-lib")]; - write_profile(tmp.path(), &root); - - let mut child = empty_profile("1.20.1-forge-47.2.0"); - child.inherits_from = Some("1.20.1".into()); - child.libraries = vec![lib("forge-lib")]; - write_profile(tmp.path(), &child); - - let mut grandchild = empty_profile("1.20.1-forge-47.2.0-modpack"); - grandchild.inherits_from = Some("1.20.1-forge-47.2.0".into()); - grandchild.libraries = vec![lib("modpack-lib")]; - - let resolved = resolve(grandchild, tmp.path()).await.unwrap(); - assert_eq!(resolved.id, "1.20.1-forge-47.2.0-modpack"); - assert!(resolved.inherits_from.is_none()); - assert_eq!( - resolved.main_class.as_deref(), - Some("net.minecraft.client.main.Main") - ); - // libs: root ++ child ++ grandchild (each parent prepended) - let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect(); - assert_eq!(names, vec!["vanilla-lib", "forge-lib", "modpack-lib"]); - } - - #[tokio::test] - async fn resolve_detects_circular_chain() { - let tmp = TempDir::new().unwrap(); - - // a -> b -> a (cycle) - let mut a = empty_profile("a"); - a.inherits_from = Some("b".into()); - write_profile(tmp.path(), &a); - - let mut b = empty_profile("b"); - b.inherits_from = Some("a".into()); - write_profile(tmp.path(), &b); - - // start from a fresh "a" profile that asks to inherit from b - let mut entry = empty_profile("a"); - entry.inherits_from = Some("b".into()); - - let err = resolve(entry, tmp.path()).await.unwrap_err(); - assert!( - matches!(err, ResolveError::CircularInheritance(ref s) if s == "a"), - "expected CircularInheritance(a), got {err:?}" - ); - } - - #[tokio::test] - async fn resolve_caps_depth() { - let tmp = TempDir::new().unwrap(); - - // build a chain 0 -> 1 -> 2 -> ... -> 10. with cap of 8, hitting 10 - // should fail with DepthExceeded. - for i in 0..=10 { - let mut p = empty_profile(&format!("v{i}")); - if i < 10 { - p.inherits_from = Some(format!("v{}", i + 1)); - } - write_profile(tmp.path(), &p); - } - - let mut entry = empty_profile("entry"); - entry.inherits_from = Some("v0".into()); - - let err = resolve(entry, tmp.path()).await.unwrap_err(); - assert!( - matches!(err, ResolveError::DepthExceeded(_)), - "expected DepthExceeded, got {err:?}" - ); - } -} +#[path = "tests/resolve.rs"] +mod tests; diff --git a/src/launch_profile/rules.rs b/src/launch_profile/rules.rs index 276be50..1a384e1 100644 --- a/src/launch_profile/rules.rs +++ b/src/launch_profile/rules.rs @@ -138,274 +138,5 @@ fn features_match(required: &FeatureSet, current: &FeatureSet) -> bool { } #[cfg(test)] -mod tests { - use super::*; - - fn linux_ctx<'a>(features: &'a FeatureSet) -> RuleContext<'a> { - RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features, - } - } - - #[test] - fn empty_rules_allow() { - let features = FeatureSet::default(); - let ctx = linux_ctx(&features); - assert!(evaluate(&[], &ctx)); - } - - #[test] - fn single_allow_matching_os_allows() { - let rules = vec![Rule { - action: RuleAction::Allow, - os: Some(OsCondition { - name: Some("linux".into()), - arch: None, - ..Default::default() - }), - features: None, - }]; - let features = FeatureSet::default(); - let ctx = linux_ctx(&features); - assert!(evaluate(&rules, &ctx)); - } - - #[test] - fn single_disallow_matching_os_disallows() { - let rules = vec![Rule { - action: RuleAction::Disallow, - os: Some(OsCondition { - name: Some("linux".into()), - arch: None, - ..Default::default() - }), - features: None, - }]; - let features = FeatureSet::default(); - let ctx = linux_ctx(&features); - assert!(!evaluate(&rules, &ctx)); - } - - #[test] - fn allow_without_os_match_disallows_by_default() { - // explicit allow for windows; we are on linux; nothing matches; - // default state remains disallow. - let rules = vec![Rule { - action: RuleAction::Allow, - os: Some(OsCondition { - name: Some("windows".into()), - arch: None, - ..Default::default() - }), - features: None, - }]; - let features = FeatureSet::default(); - let ctx = linux_ctx(&features); - assert!(!evaluate(&rules, &ctx)); - } - - #[test] - fn last_matching_rule_wins_when_allow_then_disallow() { - let rules = vec![ - Rule { - action: RuleAction::Allow, - os: None, - features: None, - }, - Rule { - action: RuleAction::Disallow, - os: Some(OsCondition { - name: Some("osx".into()), - arch: None, - ..Default::default() - }), - features: None, - }, - ]; - let features = FeatureSet::default(); - let osx_ctx = RuleContext { - os_name: "osx", - os_version: "6.0", - arch: "x86_64", - features: &features, - }; - assert!(!evaluate(&rules, &osx_ctx)); - // and on linux: only the first rule matches → still allow. - let lin = linux_ctx(&features); - assert!(evaluate(&rules, &lin)); - } - - #[test] - fn last_matching_rule_wins_when_disallow_then_allow() { - let rules = vec![ - Rule { - action: RuleAction::Disallow, - os: None, - features: None, - }, - Rule { - action: RuleAction::Allow, - os: Some(OsCondition { - name: Some("linux".into()), - arch: None, - ..Default::default() - }), - features: None, - }, - ]; - let features = FeatureSet::default(); - let ctx = linux_ctx(&features); - assert!(evaluate(&rules, &ctx)); - } - - #[test] - fn arch_mismatch_blocks_rule() { - let rules = vec![Rule { - action: RuleAction::Allow, - os: Some(OsCondition { - name: Some("linux".into()), - arch: Some("arm64".into()), - version: None, - }), - features: None, - }]; - let features = FeatureSet::default(); - let ctx = linux_ctx(&features); - // we are on linux but x86_64, not arm64 → rule does not match. - assert!(!evaluate(&rules, &ctx)); - } - - #[test] - fn feature_required_true_matches_when_ctx_true() { - let rules = vec![Rule { - action: RuleAction::Allow, - os: None, - features: Some(FeatureSet { - is_demo_user: Some(true), - ..Default::default() - }), - }]; - let demo_features = FeatureSet { - is_demo_user: Some(true), - ..Default::default() - }; - let ctx = RuleContext { - os_name: "linux", - os_version: "6.0", - arch: "x86_64", - features: &demo_features, - }; - assert!(evaluate(&rules, &ctx)); - } - - #[test] - fn feature_required_true_blocks_when_ctx_false() { - let rules = vec![Rule { - action: RuleAction::Allow, - os: None, - features: Some(FeatureSet { - is_demo_user: Some(true), - ..Default::default() - }), - }]; - let features = FeatureSet::default(); - let ctx = linux_ctx(&features); - assert!(!evaluate(&rules, &ctx)); - } - - #[test] - fn no_os_no_features_rule_always_matches() { - let rules = vec![Rule { - action: RuleAction::Allow, - os: None, - features: None, - }]; - let features = FeatureSet::default(); - let ctx = linux_ctx(&features); - assert!(evaluate(&rules, &ctx)); - } - - #[test] - fn os_version_pattern_matches_against_host() { - let rules = vec![Rule { - action: RuleAction::Allow, - os: Some(OsCondition { - name: Some("osx".into()), - arch: None, - version: Some("^10\\.".into()), - }), - features: None, - }]; - let features = FeatureSet::default(); - let ctx_match = RuleContext { - os_name: "osx", - os_version: "10.15.7", - arch: "x86_64", - features: &features, - }; - assert!(evaluate(&rules, &ctx_match)); - let ctx_mismatch = RuleContext { - os_name: "osx", - os_version: "13.2.1", - arch: "x86_64", - features: &features, - }; - assert!(!evaluate(&rules, &ctx_mismatch)); - } - - #[test] - fn os_version_pattern_does_not_match_when_host_unknown() { - let rules = vec![Rule { - action: RuleAction::Allow, - os: Some(OsCondition { - name: Some("windows".into()), - arch: None, - version: Some("^10\\.".into()), - }), - features: None, - }]; - let features = FeatureSet::default(); - let ctx = RuleContext { - os_name: "windows", - os_version: "", - arch: "x86_64", - features: &features, - }; - assert!(!evaluate(&rules, &ctx)); - } - - #[test] - fn rule_deserializes_from_mojang_json() { - // shape lifted from real mojang library rules. - let json = r#"{ - "action": "allow", - "os": { "name": "osx" } - }"#; - let rule: Rule = serde_json::from_str(json).unwrap(); - assert_eq!(rule.action, RuleAction::Allow); - assert_eq!( - rule.os.as_ref().and_then(|o| o.name.as_deref()), - Some("osx") - ); - assert!(rule.os.as_ref().and_then(|o| o.arch.as_ref()).is_none()); - assert!(rule.features.is_none()); - } - - #[test] - fn rule_deserializes_with_features() { - let json = r#"{ - "action": "allow", - "features": { "is_demo_user": true } - }"#; - let rule: Rule = serde_json::from_str(json).unwrap(); - assert_eq!(rule.action, RuleAction::Allow); - assert!(rule.os.is_none()); - assert_eq!( - rule.features.as_ref().and_then(|f| f.is_demo_user), - Some(true) - ); - } -} +#[path = "tests/rules.rs"] +mod tests; diff --git a/src/launch_profile/templates.rs b/src/launch_profile/templates.rs index 3eb0e6c..0bd563b 100644 --- a/src/launch_profile/templates.rs +++ b/src/launch_profile/templates.rs @@ -97,107 +97,5 @@ fn lookup(name: &str, ctx: &TemplateContext) -> Option { } #[cfg(test)] -mod tests { - use super::*; - use std::path::PathBuf; - - // owns the path buffers so tests don't have to declare them inline; the - // ctx() method borrows from self to build a TemplateContext with the - // standard set of values. windows() returns a fixture with backslash - // paths so the OS-independence test stays self-contained. - struct Fixture { - lib: PathBuf, - nat: PathBuf, - game: PathBuf, - assets: PathBuf, - user_properties: String, - } - - impl Fixture { - fn unix() -> Self { - Self { - lib: PathBuf::from("/m/libraries"), - nat: PathBuf::from("/m/natives"), - game: PathBuf::from("/i/.minecraft"), - assets: PathBuf::from("/m/assets"), - user_properties: "{}".to_string(), - } - } - - fn windows() -> Self { - Self { - lib: PathBuf::from(r"C:\Users\test\.minecraft\libraries"), - nat: PathBuf::from(r"C:\Users\test\.minecraft\natives"), - game: PathBuf::from(r"C:\Users\test\.minecraft"), - assets: PathBuf::from(r"C:\Users\test\.minecraft\assets"), - user_properties: "{}".to_string(), - } - } - - fn ctx(&self) -> TemplateContext<'_> { - TemplateContext { - library_directory: &self.lib, - classpath_separator: ":", - version_name: "1.20.1", - version_type: "release", - natives_directory: &self.nat, - classpath: "a.jar:b.jar", - game_directory: &self.game, - assets_root: &self.assets, - assets_index_name: "5", - auth_player_name: "Player", - auth_uuid: "00000000-0000-0000-0000-000000000000", - auth_access_token: "token", - auth_xuid: "0", - user_type: "msa", - user_properties: &self.user_properties, - launcher_name: "rmcl", - launcher_version: "0.3.0", - clientid: "0", - } - } - } - - #[rstest::rstest] - #[case::no_placeholders("--add-modules ALL-MODULE-PATH", "--add-modules ALL-MODULE-PATH")] - #[case::single_known("v=${version_name}", "v=1.20.1")] - #[case::unknown_placeholder("x=${not_a_real_var}y", "x=${not_a_real_var}y")] - #[case::unclosed_placeholder("--prefix ${unclosed", "--prefix ${unclosed")] - #[case::dollar_without_brace("$$ literal $5 $", "$$ literal $5 $")] - #[case::multiple("${version_name}-${auth_player_name}", "1.20.1-Player")] - #[case::path( - "-DlibraryDirectory=${library_directory}", - "-DlibraryDirectory=/m/libraries" - )] - #[case::empty_input("", "")] - fn substitute_handles(#[case] input: &str, #[case] expected: &str) { - let fx = Fixture::unix(); - assert_eq!(substitute(input, &fx.ctx()), expected); - } - - #[test] - fn substituted_value_is_not_recursively_substituted() { - // simulate a user_properties value that happens to contain a ${...} - // pattern. it should NOT trigger another substitution pass. - let mut fx = Fixture::unix(); - fx.user_properties = "${version_name}".to_string(); - assert_eq!( - substitute("${user_properties}", &fx.ctx()), - "${version_name}" - ); - } - - #[test] - fn windows_style_backslashes_in_value_pass_through() { - // simulate a Windows install where library_directory is a path with - // backslashes. the substitution must not interpret backslashes as - // escape sequences or do anything else clever - it just copies the - // value into the output. - let fx = Fixture::windows(); - let result = substitute("-Dpath=${library_directory}", &fx.ctx()); - assert!( - result.contains(r"C:\Users\test\.minecraft\libraries"), - "expected backslashes preserved, got: {result}" - ); - } -} +#[path = "tests/templates.rs"] +mod tests; diff --git a/src/launch_profile/tests/model.rs b/src/launch_profile/tests/model.rs new file mode 100644 index 0000000..20769c4 --- /dev/null +++ b/src/launch_profile/tests/model.rs @@ -0,0 +1,166 @@ +use super::*; +use crate::launch_profile::rules::RuleAction; + +const MODERN_FIXTURE: &str = r#"{ + "id": "1.20.1", + "type": "release", + "mainClass": "net.minecraft.client.main.Main", + "assetIndex": { + "id": "5", + "url": "https://example.invalid/5.json", + "sha1": "0000000000000000000000000000000000000000" + }, + "javaVersion": { + "component": "java-runtime-gamma", + "majorVersion": 17 + }, + "libraries": [ + { + "name": "org.lwjgl:lwjgl:3.3.1", + "downloads": { + "artifact": { + "url": "https://example.invalid/lwjgl.jar", + "path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar", + "sha1": "1111111111111111111111111111111111111111", + "size": 100 + } + }, + "rules": [ + { "action": "allow", "os": { "name": "linux" } } + ] + } + ], + "arguments": { + "game": [ + "--username", "${auth_player_name}", + { + "rules": [{ "action": "allow", "features": { "is_demo_user": true } }], + "value": "--demo" + } + ], + "jvm": [ + "-Djava.library.path=${natives_directory}", + { + "rules": [{ "action": "allow", "os": { "name": "osx" } }], + "value": ["-XstartOnFirstThread"] + } + ] + } + }"#; + +const LEGACY_FIXTURE: &str = r#"{ + "id": "1.7.10", + "type": "release", + "mainClass": "net.minecraft.client.main.Main", + "minecraftArguments": "--username ${auth_player_name} --version ${version_name} --gameDir ${game_directory}", + "assetIndex": { + "id": "1.7.10", + "url": "https://example.invalid/1.7.10.json", + "sha1": "0000000000000000000000000000000000000000" + }, + "libraries": [] + }"#; + +const LOADER_FIXTURE: &str = r#"{ + "id": "1.20.1-forge-47.2.0", + "inheritsFrom": "1.20.1", + "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", + "libraries": [ + { "name": "net.minecraftforge:forge:47.2.0" } + ], + "arguments": { + "game": ["--launchTarget", "forge_client"], + "jvm": [ + "--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler", + "-DlibraryDirectory=${library_directory}" + ] + } + }"#; + +#[test] +fn parses_modern_arguments_object() { + let profile: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap(); + assert_eq!(profile.id, "1.20.1"); + assert_eq!( + profile.main_class.as_deref(), + Some("net.minecraft.client.main.Main") + ); + assert!(profile.inherits_from.is_none()); + assert!(profile.minecraft_arguments.is_none()); + + let args = profile.arguments.as_ref().expect("arguments present"); + assert_eq!(args.game.len(), 3); + assert_eq!(args.jvm.len(), 2); + + // first game arg should be a literal "--username" + match &args.game[0] { + Argument::Literal(s) => assert_eq!(s, "--username"), + _ => panic!("expected literal"), + } + // third game arg should be a conditional with a single-string value + match &args.game[2] { + Argument::Conditional { rules, value } => { + assert_eq!(rules.len(), 1); + assert_eq!(rules[0].action, RuleAction::Allow); + assert!(matches!(value, ArgumentValue::Single(_))); + } + _ => panic!("expected conditional"), + } + // second jvm arg should be a conditional with a multi-string value + match &args.jvm[1] { + Argument::Conditional { value, .. } => { + assert!(matches!(value, ArgumentValue::Multiple(_))); + } + _ => panic!("expected conditional"), + } +} + +#[test] +fn parses_legacy_minecraft_arguments_string() { + let profile: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap(); + assert_eq!(profile.id, "1.7.10"); + assert!(profile.arguments.is_none()); + assert!( + profile + .minecraft_arguments + .as_deref() + .unwrap() + .contains("${version_name}") + ); + assert!(profile.libraries.is_empty()); +} + +#[test] +fn parses_loader_profile_with_inherits_from() { + let profile: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap(); + assert_eq!(profile.id, "1.20.1-forge-47.2.0"); + assert_eq!(profile.inherits_from.as_deref(), Some("1.20.1")); + assert!(profile.asset_index.is_none()); // inherited from parent + let args = profile.arguments.as_ref().unwrap(); + assert_eq!(args.game.len(), 2); + assert_eq!(args.jvm.len(), 3); +} + +#[test] +fn modern_profile_round_trips() { + let original: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap(); + let serialized = serde_json::to_string(&original).unwrap(); + let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap(); + assert_eq!(original, reparsed); +} + +#[test] +fn loader_profile_round_trips() { + let original: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap(); + let serialized = serde_json::to_string(&original).unwrap(); + let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap(); + assert_eq!(original, reparsed); +} + +#[test] +fn legacy_profile_round_trips() { + let original: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap(); + let serialized = serde_json::to_string(&original).unwrap(); + let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap(); + assert_eq!(original, reparsed); +} diff --git a/src/launch_profile/tests/render.rs b/src/launch_profile/tests/render.rs new file mode 100644 index 0000000..07f60f2 --- /dev/null +++ b/src/launch_profile/tests/render.rs @@ -0,0 +1,278 @@ +use super::*; +use crate::launch_profile::model::Arguments; +use crate::launch_profile::rules::{FeatureSet, OsCondition, Rule, RuleAction}; +use std::path::PathBuf; + +// owns the path buffers + FeatureSet so each test just calls +// fx.template_ctx() and fx.rule_ctx() instead of declaring four PathBufs +// and a RuleContext inline. all tests use linux/x86_64; if a test needs +// a different OS it sets it explicitly. +struct Fixture { + lib: PathBuf, + nat: PathBuf, + game: PathBuf, + assets: PathBuf, + features: FeatureSet, +} + +impl Fixture { + fn new() -> Self { + Self { + lib: PathBuf::from("/m/libraries"), + nat: PathBuf::from("/m/natives"), + game: PathBuf::from("/i/.minecraft"), + assets: PathBuf::from("/m/assets"), + features: FeatureSet::default(), + } + } + + fn template_ctx(&self) -> TemplateContext<'_> { + TemplateContext { + library_directory: &self.lib, + classpath_separator: ":", + version_name: "1.20.1", + version_type: "release", + natives_directory: &self.nat, + classpath: "a.jar:b.jar", + game_directory: &self.game, + assets_root: &self.assets, + assets_index_name: "5", + auth_player_name: "Player", + auth_uuid: "00000000-0000-0000-0000-000000000000", + auth_access_token: "token", + auth_xuid: "0", + user_type: "msa", + user_properties: "{}", + launcher_name: "rmcl", + launcher_version: "0.3.0", + clientid: "0", + } + } + + fn rule_ctx(&self) -> RuleContext<'_> { + RuleContext { + os_name: "linux", + os_version: "6.0", + arch: "x86_64", + features: &self.features, + } + } +} + +fn minimal_profile() -> LaunchProfile { + LaunchProfile { + id: "test".into(), + main_class: Some("net.test.Main".into()), + ..Default::default() + } +} + +#[test] +fn legacy_minecraft_arguments_render_into_game() { + let fx = Fixture::new(); + let mut profile = minimal_profile(); + profile.minecraft_arguments = + Some("--username ${auth_player_name} --version ${version_name}".into()); + + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); + assert_eq!(rendered.main_class, "net.test.Main"); + assert!(rendered.jvm.is_empty()); + assert_eq!( + rendered.game, + vec!["--username", "Player", "--version", "1.20.1"] + ); +} + +#[test] +fn modern_arguments_render_with_literals_and_substitutions() { + let fx = Fixture::new(); + let mut profile = minimal_profile(); + profile.arguments = Some(Arguments { + game: vec![ + Argument::Literal("--username".into()), + Argument::Literal("${auth_player_name}".into()), + ], + jvm: vec![Argument::Literal( + "-Djava.library.path=${natives_directory}".into(), + )], + }); + + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); + assert_eq!(rendered.game, vec!["--username", "Player"]); + assert_eq!(rendered.jvm, vec!["-Djava.library.path=/m/natives"]); +} + +#[test] +fn conditional_argument_with_single_value_is_filtered_by_os_rule() { + let fx = Fixture::new(); + let osx_only = Argument::Conditional { + rules: vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("osx".into()), + arch: None, + ..Default::default() + }), + features: None, + }], + value: ArgumentValue::Single("-XstartOnFirstThread".into()), + }; + + let mut profile = minimal_profile(); + profile.arguments = Some(Arguments { + game: Vec::new(), + jvm: vec![osx_only], + }); + + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); + assert!( + rendered.jvm.is_empty(), + "osx-only arg should be skipped on linux" + ); +} + +#[test] +fn conditional_argument_with_multiple_value_pushes_all() { + let fx = Fixture::new(); + let linux_arg = Argument::Conditional { + rules: vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("linux".into()), + arch: None, + ..Default::default() + }), + features: None, + }], + value: ArgumentValue::Multiple(vec![ + "--add-opens".into(), + "java.base/sun.security.util=ALL-UNNAMED".into(), + ]), + }; + + let mut profile = minimal_profile(); + profile.arguments = Some(Arguments { + game: Vec::new(), + jvm: vec![linux_arg], + }); + + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); + assert_eq!( + rendered.jvm, + vec!["--add-opens", "java.base/sun.security.util=ALL-UNNAMED"] + ); +} + +#[test] +fn missing_main_class_returns_error() { + let fx = Fixture::new(); + let mut profile = minimal_profile(); + profile.main_class = None; + + let result = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()); + assert!(matches!(result, Err(RenderError::MissingMainClass))); +} + +#[tokio::test] +async fn end_to_end_resolve_then_render_modern_forge_shape() { + // exercises the full pipeline: load a synthetic vanilla profile + // from disk, load a synthetic loader profile with inheritsFrom, + // resolve the chain, then render args. catches integration bugs + // that unit tests of each layer would miss. + use crate::launch_profile::resolve; + use tempfile::TempDir; + + let tmp = TempDir::new().unwrap(); + let vanilla_path = tmp + .path() + .join("cache/minecraft/versions") + .join("1.20.1") + .join("meta.json"); + std::fs::create_dir_all(vanilla_path.parent().unwrap()).unwrap(); + let vanilla_json = br#"{ + "id": "1.20.1", + "mainClass": "net.minecraft.client.main.Main", + "libraries": [ + { + "name": "org.lwjgl:lwjgl:3.3.1", + "downloads": { + "artifact": { + "url": "https://example.invalid/lwjgl.jar", + "path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar", + "sha1": "1111111111111111111111111111111111111111", + "size": 100 + } + } + } + ], + "arguments": { + "game": ["--username", "${auth_player_name}", "--version", "${version_name}"], + "jvm": ["-Djava.library.path=${natives_directory}"] + } + }"#; + std::fs::write(&vanilla_path, vanilla_json).unwrap(); + + let loader_json = r#"{ + "id": "1.20.1-forge-47.2.0", + "inheritsFrom": "1.20.1", + "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", + "libraries": [ + { "name": "net.minecraftforge:forge:47.2.0" } + ], + "arguments": { + "game": ["--launchTarget", "forge_client"], + "jvm": [ + "--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler" + ] + } + }"#; + let loader_profile: LaunchProfile = serde_json::from_str(loader_json).unwrap(); + + let merged = resolve::resolve(loader_profile, tmp.path()).await.unwrap(); + + let fx = Fixture::new(); + let rendered = render_args(&merged, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); + + // child main_class wins after merge + assert_eq!( + rendered.main_class, + "cpw.mods.bootstraplauncher.BootstrapLauncher" + ); + // game args: parent first then child + assert_eq!( + rendered.game, + vec![ + "--username", + "Player", + "--version", + "1.20.1", + "--launchTarget", + "forge_client" + ] + ); + // jvm args: parent first then child + assert_eq!( + rendered.jvm, + vec![ + "-Djava.library.path=/m/natives", + "--add-opens", + "java.base/sun.security.util=cpw.mods.securejarhandler" + ] + ); +} + +#[test] +fn modern_arguments_takes_precedence_over_legacy_field() { + // a profile that somehow has both arguments and minecraft_arguments + // should use arguments only (legacy is fallback). + let fx = Fixture::new(); + let mut profile = minimal_profile(); + profile.arguments = Some(Arguments { + game: vec![Argument::Literal("--from-arguments".into())], + jvm: Vec::new(), + }); + profile.minecraft_arguments = Some("--from-legacy".into()); + + let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); + assert_eq!(rendered.game, vec!["--from-arguments"]); +} diff --git a/src/launch_profile/tests/resolve.rs b/src/launch_profile/tests/resolve.rs new file mode 100644 index 0000000..40d3a26 --- /dev/null +++ b/src/launch_profile/tests/resolve.rs @@ -0,0 +1,419 @@ +use super::*; +use crate::launch_profile::model::{Argument, ArgumentValue, AssetIndex, JavaVersion, Library}; +use crate::launch_profile::rules::{Rule, RuleAction}; + +fn empty_profile(id: &str) -> LaunchProfile { + LaunchProfile { + id: id.into(), + ..Default::default() + } +} + +fn lib(name: &str) -> Library { + Library { + name: name.into(), + ..Default::default() + } +} + +fn allow_linux_rule() -> Rule { + Rule { + action: RuleAction::Allow, + os: Some(crate::launch_profile::rules::OsCondition { + name: Some("linux".into()), + ..Default::default() + }), + features: None, + } +} + +#[test] +fn child_id_wins() { + let mut child = empty_profile("child"); + let parent = empty_profile("parent"); + child.main_class = None; + let merged = merge_into(child, parent); + assert_eq!(merged.id, "child"); +} + +#[test] +fn merge_carries_parent_inherits_from() { + // merge_into preserves parent's inherits_from so resolve() can keep + // walking. resolve() itself clears the final result's inherits_from + // after the loop exits. + let mut child = empty_profile("child"); + child.inherits_from = Some("parent".into()); + let mut parent = empty_profile("parent"); + parent.inherits_from = Some("grandparent".into()); + let merged = merge_into(child, parent); + assert_eq!(merged.inherits_from.as_deref(), Some("grandparent")); +} + +#[test] +fn merge_with_root_parent_clears_inherits_from() { + // parent with no inherits_from means the chain ends. + let mut child = empty_profile("child"); + child.inherits_from = Some("parent".into()); + let parent = empty_profile("parent"); + let merged = merge_into(child, parent); + assert!(merged.inherits_from.is_none()); +} + +#[test] +fn child_main_class_overrides_parent() { + let mut child = empty_profile("child"); + let mut parent = empty_profile("parent"); + child.main_class = Some("child.Main".into()); + parent.main_class = Some("parent.Main".into()); + let merged = merge_into(child, parent); + assert_eq!(merged.main_class.as_deref(), Some("child.Main")); +} + +#[test] +fn parent_main_class_used_when_child_missing() { + let child = empty_profile("child"); + let mut parent = empty_profile("parent"); + parent.main_class = Some("parent.Main".into()); + let merged = merge_into(child, parent); + assert_eq!(merged.main_class.as_deref(), Some("parent.Main")); +} + +#[test] +fn libraries_are_concatenated_parent_first() { + let mut child = empty_profile("child"); + let mut parent = empty_profile("parent"); + parent.libraries = vec![lib("p1"), lib("p2")]; + child.libraries = vec![lib("c1")]; + let merged = merge_into(child, parent); + let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, vec!["p1", "p2", "c1"]); +} + +#[test] +fn child_library_supersedes_parent_with_same_group_artifact() { + // forge declares log4j 2.17.0; vanilla declared 2.0-beta9. without + // dedup, both end up on the classpath and the JVM picks the first + // (vanilla) match - defeating forge's override. dedup keeps child's. + let mut child = empty_profile("forge"); + let mut parent = empty_profile("vanilla"); + parent.libraries = vec![ + lib("org.apache.logging.log4j:log4j-core:2.0-beta9"), + lib("org.lwjgl:lwjgl:3.3.1"), + ]; + child.libraries = vec![ + lib("org.apache.logging.log4j:log4j-core:2.17.0"), + lib("net.minecraftforge:forge:47.2.0"), + ]; + let merged = merge_into(child, parent); + let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect(); + // parent's log4j-core is filtered (superseded by child); parent's + // lwjgl stays (no conflict); child's log4j and forge come last. + assert_eq!( + names, + vec![ + "org.lwjgl:lwjgl:3.3.1", + "org.apache.logging.log4j:log4j-core:2.17.0", + "net.minecraftforge:forge:47.2.0", + ] + ); +} + +#[test] +fn coord_key_extracts_group_artifact() { + assert_eq!(coord_key("org.lwjgl:lwjgl:3.3.1"), "org.lwjgl:lwjgl"); + assert_eq!( + coord_key("org.apache.logging.log4j:log4j-core:2.17.0"), + "org.apache.logging.log4j:log4j-core" + ); + // with classifier + assert_eq!( + coord_key("org.lwjgl:lwjgl:3.3.1:natives-linux"), + "org.lwjgl:lwjgl" + ); + // malformed (no colons) - return as-is + assert_eq!(coord_key("malformed"), "malformed"); +} + +#[test] +fn arguments_are_concatenated_parent_first() { + let mut child = empty_profile("child"); + let mut parent = empty_profile("parent"); + parent.arguments = Some(Arguments { + game: vec![Argument::Literal("--from-parent-game".into())], + jvm: vec![Argument::Literal("--from-parent-jvm".into())], + }); + child.arguments = Some(Arguments { + game: vec![Argument::Literal("--from-child-game".into())], + jvm: vec![Argument::Literal("--from-child-jvm".into())], + }); + let merged = merge_into(child, parent); + let args = merged.arguments.expect("arguments present"); + assert_eq!( + args.game, + vec![ + Argument::Literal("--from-parent-game".into()), + Argument::Literal("--from-child-game".into()), + ] + ); + assert_eq!( + args.jvm, + vec![ + Argument::Literal("--from-parent-jvm".into()), + Argument::Literal("--from-child-jvm".into()), + ] + ); +} + +#[test] +fn arguments_from_child_only_carry_through() { + let mut child = empty_profile("child"); + let parent = empty_profile("parent"); + child.arguments = Some(Arguments { + game: vec![Argument::Literal("--child".into())], + jvm: Vec::new(), + }); + let merged = merge_into(child, parent); + let args = merged.arguments.expect("arguments present"); + assert_eq!(args.game.len(), 1); + assert!(args.jvm.is_empty()); +} + +#[test] +fn arguments_from_parent_only_carry_through() { + let child = empty_profile("child"); + let mut parent = empty_profile("parent"); + parent.arguments = Some(Arguments { + game: Vec::new(), + jvm: vec![Argument::Literal("--parent-jvm".into())], + }); + let merged = merge_into(child, parent); + let args = merged.arguments.expect("arguments present"); + assert!(args.game.is_empty()); + assert_eq!(args.jvm.len(), 1); +} + +#[test] +fn conditional_arguments_with_rules_survive_merge() { + // make sure the Argument::Conditional shape isn't accidentally + // flattened or filtered during merging - rule eval happens later + // at render time, not during merge. + let mut child = empty_profile("child"); + let parent = empty_profile("parent"); + child.arguments = Some(Arguments { + game: vec![Argument::Conditional { + rules: vec![allow_linux_rule()], + value: ArgumentValue::Single("--linux-only".into()), + }], + jvm: Vec::new(), + }); + let merged = merge_into(child, parent); + let args = merged.arguments.expect("arguments present"); + match &args.game[0] { + Argument::Conditional { rules, .. } => { + assert_eq!(rules.len(), 1); + assert_eq!(rules[0].action, RuleAction::Allow); + } + _ => panic!("expected conditional argument to survive merge"), + } +} + +#[test] +fn legacy_minecraft_arguments_child_overrides_parent() { + let mut child = empty_profile("child"); + let mut parent = empty_profile("parent"); + child.minecraft_arguments = Some("--child".into()); + parent.minecraft_arguments = Some("--parent".into()); + let merged = merge_into(child, parent); + assert_eq!(merged.minecraft_arguments.as_deref(), Some("--child")); +} + +#[test] +fn asset_index_inherits_from_parent_when_child_absent() { + let child = empty_profile("child"); + let mut parent = empty_profile("parent"); + parent.asset_index = Some(AssetIndex { + id: "5".into(), + url: "https://example.invalid/5.json".into(), + sha1: "0".repeat(40), + size: None, + total_size: None, + }); + let merged = merge_into(child, parent); + assert!(merged.asset_index.is_some()); + assert_eq!(merged.asset_index.unwrap().id, "5"); +} + +#[test] +fn java_version_inherits_from_parent_when_child_absent() { + let child = empty_profile("child"); + let mut parent = empty_profile("parent"); + parent.java_version = Some(JavaVersion { + component: Some("java-runtime-gamma".into()), + major_version: 17, + }); + let merged = merge_into(child, parent); + assert_eq!( + merged.java_version.as_ref().map(|j| j.major_version), + Some(17) + ); +} + +use tempfile::TempDir; + +fn write_profile(meta_dir: &Path, profile: &LaunchProfile) { + let path = meta_dir + .join("cache/minecraft/versions") + .join(&profile.id) + .join("meta.json"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let json = serde_json::to_string_pretty(profile).unwrap(); + std::fs::write(&path, json).unwrap(); +} + +#[tokio::test] +async fn resolve_returns_unchanged_when_no_inherits_from() { + let tmp = TempDir::new().unwrap(); + let profile = empty_profile("standalone"); + let resolved = resolve(profile, tmp.path()).await.unwrap(); + assert_eq!(resolved.id, "standalone"); + assert!(resolved.inherits_from.is_none()); +} + +#[tokio::test] +async fn resolve_single_level_inheritance_merges_parent() { + let tmp = TempDir::new().unwrap(); + + let mut parent = empty_profile("1.20.1"); + parent.main_class = Some("net.minecraft.client.main.Main".into()); + parent.libraries = vec![lib("vanilla-lib")]; + write_profile(tmp.path(), &parent); + + let mut child = empty_profile("1.20.1-forge-47.2.0"); + child.inherits_from = Some("1.20.1".into()); + child.libraries = vec![lib("forge-lib")]; + + let resolved = resolve(child, tmp.path()).await.unwrap(); + assert_eq!(resolved.id, "1.20.1-forge-47.2.0"); + assert!(resolved.inherits_from.is_none()); + assert_eq!( + resolved.main_class.as_deref(), + Some("net.minecraft.client.main.Main") + ); + let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, vec!["vanilla-lib", "forge-lib"]); +} + +#[tokio::test] +async fn resolve_errors_when_parent_missing() { + let tmp = TempDir::new().unwrap(); + + let mut child = empty_profile("1.20.1-forge-47.2.0"); + child.inherits_from = Some("1.20.1".into()); + + let err = resolve(child, tmp.path()).await.unwrap_err(); + assert!( + matches!(err, ResolveError::ParentNotFound(_)), + "expected ParentNotFound, got {err:?}" + ); +} + +#[tokio::test] +async fn resolve_errors_when_parent_is_invalid_json() { + let tmp = TempDir::new().unwrap(); + + let parent_path = tmp + .path() + .join("cache/minecraft/versions") + .join("1.20.1") + .join("meta.json"); + std::fs::create_dir_all(parent_path.parent().unwrap()).unwrap(); + std::fs::write(&parent_path, "{ not valid json").unwrap(); + + let mut child = empty_profile("1.20.1-forge-47.2.0"); + child.inherits_from = Some("1.20.1".into()); + + let err = resolve(child, tmp.path()).await.unwrap_err(); + assert!( + matches!(err, ResolveError::ParseError(_, _)), + "expected ParseError, got {err:?}" + ); +} + +#[tokio::test] +async fn resolve_multi_level_chain_merges_all_parents() { + let tmp = TempDir::new().unwrap(); + + // chain: grandchild -> child -> root (vanilla). + let mut root = empty_profile("1.20.1"); + root.main_class = Some("net.minecraft.client.main.Main".into()); + root.libraries = vec![lib("vanilla-lib")]; + write_profile(tmp.path(), &root); + + let mut child = empty_profile("1.20.1-forge-47.2.0"); + child.inherits_from = Some("1.20.1".into()); + child.libraries = vec![lib("forge-lib")]; + write_profile(tmp.path(), &child); + + let mut grandchild = empty_profile("1.20.1-forge-47.2.0-modpack"); + grandchild.inherits_from = Some("1.20.1-forge-47.2.0".into()); + grandchild.libraries = vec![lib("modpack-lib")]; + + let resolved = resolve(grandchild, tmp.path()).await.unwrap(); + assert_eq!(resolved.id, "1.20.1-forge-47.2.0-modpack"); + assert!(resolved.inherits_from.is_none()); + assert_eq!( + resolved.main_class.as_deref(), + Some("net.minecraft.client.main.Main") + ); + // libs: root ++ child ++ grandchild (each parent prepended) + let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, vec!["vanilla-lib", "forge-lib", "modpack-lib"]); +} + +#[tokio::test] +async fn resolve_detects_circular_chain() { + let tmp = TempDir::new().unwrap(); + + // a -> b -> a (cycle) + let mut a = empty_profile("a"); + a.inherits_from = Some("b".into()); + write_profile(tmp.path(), &a); + + let mut b = empty_profile("b"); + b.inherits_from = Some("a".into()); + write_profile(tmp.path(), &b); + + // start from a fresh "a" profile that asks to inherit from b + let mut entry = empty_profile("a"); + entry.inherits_from = Some("b".into()); + + let err = resolve(entry, tmp.path()).await.unwrap_err(); + assert!( + matches!(err, ResolveError::CircularInheritance(ref s) if s == "a"), + "expected CircularInheritance(a), got {err:?}" + ); +} + +#[tokio::test] +async fn resolve_caps_depth() { + let tmp = TempDir::new().unwrap(); + + // build a chain 0 -> 1 -> 2 -> ... -> 10. with cap of 8, hitting 10 + // should fail with DepthExceeded. + for i in 0..=10 { + let mut p = empty_profile(&format!("v{i}")); + if i < 10 { + p.inherits_from = Some(format!("v{}", i + 1)); + } + write_profile(tmp.path(), &p); + } + + let mut entry = empty_profile("entry"); + entry.inherits_from = Some("v0".into()); + + let err = resolve(entry, tmp.path()).await.unwrap_err(); + assert!( + matches!(err, ResolveError::DepthExceeded(_)), + "expected DepthExceeded, got {err:?}" + ); +} diff --git a/src/launch_profile/tests/rules.rs b/src/launch_profile/tests/rules.rs new file mode 100644 index 0000000..db703ef --- /dev/null +++ b/src/launch_profile/tests/rules.rs @@ -0,0 +1,269 @@ +use super::*; + +fn linux_ctx<'a>(features: &'a FeatureSet) -> RuleContext<'a> { + RuleContext { + os_name: "linux", + os_version: "6.0", + arch: "x86_64", + features, + } +} + +#[test] +fn empty_rules_allow() { + let features = FeatureSet::default(); + let ctx = linux_ctx(&features); + assert!(evaluate(&[], &ctx)); +} + +#[test] +fn single_allow_matching_os_allows() { + let rules = vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("linux".into()), + arch: None, + ..Default::default() + }), + features: None, + }]; + let features = FeatureSet::default(); + let ctx = linux_ctx(&features); + assert!(evaluate(&rules, &ctx)); +} + +#[test] +fn single_disallow_matching_os_disallows() { + let rules = vec![Rule { + action: RuleAction::Disallow, + os: Some(OsCondition { + name: Some("linux".into()), + arch: None, + ..Default::default() + }), + features: None, + }]; + let features = FeatureSet::default(); + let ctx = linux_ctx(&features); + assert!(!evaluate(&rules, &ctx)); +} + +#[test] +fn allow_without_os_match_disallows_by_default() { + // explicit allow for windows; we are on linux; nothing matches; + // default state remains disallow. + let rules = vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("windows".into()), + arch: None, + ..Default::default() + }), + features: None, + }]; + let features = FeatureSet::default(); + let ctx = linux_ctx(&features); + assert!(!evaluate(&rules, &ctx)); +} + +#[test] +fn last_matching_rule_wins_when_allow_then_disallow() { + let rules = vec![ + Rule { + action: RuleAction::Allow, + os: None, + features: None, + }, + Rule { + action: RuleAction::Disallow, + os: Some(OsCondition { + name: Some("osx".into()), + arch: None, + ..Default::default() + }), + features: None, + }, + ]; + let features = FeatureSet::default(); + let osx_ctx = RuleContext { + os_name: "osx", + os_version: "6.0", + arch: "x86_64", + features: &features, + }; + assert!(!evaluate(&rules, &osx_ctx)); + // and on linux: only the first rule matches → still allow. + let lin = linux_ctx(&features); + assert!(evaluate(&rules, &lin)); +} + +#[test] +fn last_matching_rule_wins_when_disallow_then_allow() { + let rules = vec![ + Rule { + action: RuleAction::Disallow, + os: None, + features: None, + }, + Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("linux".into()), + arch: None, + ..Default::default() + }), + features: None, + }, + ]; + let features = FeatureSet::default(); + let ctx = linux_ctx(&features); + assert!(evaluate(&rules, &ctx)); +} + +#[test] +fn arch_mismatch_blocks_rule() { + let rules = vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("linux".into()), + arch: Some("arm64".into()), + version: None, + }), + features: None, + }]; + let features = FeatureSet::default(); + let ctx = linux_ctx(&features); + // we are on linux but x86_64, not arm64 → rule does not match. + assert!(!evaluate(&rules, &ctx)); +} + +#[test] +fn feature_required_true_matches_when_ctx_true() { + let rules = vec![Rule { + action: RuleAction::Allow, + os: None, + features: Some(FeatureSet { + is_demo_user: Some(true), + ..Default::default() + }), + }]; + let demo_features = FeatureSet { + is_demo_user: Some(true), + ..Default::default() + }; + let ctx = RuleContext { + os_name: "linux", + os_version: "6.0", + arch: "x86_64", + features: &demo_features, + }; + assert!(evaluate(&rules, &ctx)); +} + +#[test] +fn feature_required_true_blocks_when_ctx_false() { + let rules = vec![Rule { + action: RuleAction::Allow, + os: None, + features: Some(FeatureSet { + is_demo_user: Some(true), + ..Default::default() + }), + }]; + let features = FeatureSet::default(); + let ctx = linux_ctx(&features); + assert!(!evaluate(&rules, &ctx)); +} + +#[test] +fn no_os_no_features_rule_always_matches() { + let rules = vec![Rule { + action: RuleAction::Allow, + os: None, + features: None, + }]; + let features = FeatureSet::default(); + let ctx = linux_ctx(&features); + assert!(evaluate(&rules, &ctx)); +} + +#[test] +fn os_version_pattern_matches_against_host() { + let rules = vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("osx".into()), + arch: None, + version: Some("^10\\.".into()), + }), + features: None, + }]; + let features = FeatureSet::default(); + let ctx_match = RuleContext { + os_name: "osx", + os_version: "10.15.7", + arch: "x86_64", + features: &features, + }; + assert!(evaluate(&rules, &ctx_match)); + let ctx_mismatch = RuleContext { + os_name: "osx", + os_version: "13.2.1", + arch: "x86_64", + features: &features, + }; + assert!(!evaluate(&rules, &ctx_mismatch)); +} + +#[test] +fn os_version_pattern_does_not_match_when_host_unknown() { + let rules = vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("windows".into()), + arch: None, + version: Some("^10\\.".into()), + }), + features: None, + }]; + let features = FeatureSet::default(); + let ctx = RuleContext { + os_name: "windows", + os_version: "", + arch: "x86_64", + features: &features, + }; + assert!(!evaluate(&rules, &ctx)); +} + +#[test] +fn rule_deserializes_from_mojang_json() { + // shape lifted from real mojang library rules. + let json = r#"{ + "action": "allow", + "os": { "name": "osx" } + }"#; + let rule: Rule = serde_json::from_str(json).unwrap(); + assert_eq!(rule.action, RuleAction::Allow); + assert_eq!( + rule.os.as_ref().and_then(|o| o.name.as_deref()), + Some("osx") + ); + assert!(rule.os.as_ref().and_then(|o| o.arch.as_ref()).is_none()); + assert!(rule.features.is_none()); +} + +#[test] +fn rule_deserializes_with_features() { + let json = r#"{ + "action": "allow", + "features": { "is_demo_user": true } + }"#; + let rule: Rule = serde_json::from_str(json).unwrap(); + assert_eq!(rule.action, RuleAction::Allow); + assert!(rule.os.is_none()); + assert_eq!( + rule.features.as_ref().and_then(|f| f.is_demo_user), + Some(true) + ); +} diff --git a/src/launch_profile/tests/templates.rs b/src/launch_profile/tests/templates.rs new file mode 100644 index 0000000..bfa7659 --- /dev/null +++ b/src/launch_profile/tests/templates.rs @@ -0,0 +1,102 @@ +use super::*; +use std::path::PathBuf; + +// owns the path buffers so tests don't have to declare them inline; the +// ctx() method borrows from self to build a TemplateContext with the +// standard set of values. windows() returns a fixture with backslash +// paths so the OS-independence test stays self-contained. +struct Fixture { + lib: PathBuf, + nat: PathBuf, + game: PathBuf, + assets: PathBuf, + user_properties: String, +} + +impl Fixture { + fn unix() -> Self { + Self { + lib: PathBuf::from("/m/libraries"), + nat: PathBuf::from("/m/natives"), + game: PathBuf::from("/i/.minecraft"), + assets: PathBuf::from("/m/assets"), + user_properties: "{}".to_string(), + } + } + + fn windows() -> Self { + Self { + lib: PathBuf::from(r"C:\Users\test\.minecraft\libraries"), + nat: PathBuf::from(r"C:\Users\test\.minecraft\natives"), + game: PathBuf::from(r"C:\Users\test\.minecraft"), + assets: PathBuf::from(r"C:\Users\test\.minecraft\assets"), + user_properties: "{}".to_string(), + } + } + + fn ctx(&self) -> TemplateContext<'_> { + TemplateContext { + library_directory: &self.lib, + classpath_separator: ":", + version_name: "1.20.1", + version_type: "release", + natives_directory: &self.nat, + classpath: "a.jar:b.jar", + game_directory: &self.game, + assets_root: &self.assets, + assets_index_name: "5", + auth_player_name: "Player", + auth_uuid: "00000000-0000-0000-0000-000000000000", + auth_access_token: "token", + auth_xuid: "0", + user_type: "msa", + user_properties: &self.user_properties, + launcher_name: "rmcl", + launcher_version: "0.3.0", + clientid: "0", + } + } +} + +#[rstest::rstest] +#[case::no_placeholders("--add-modules ALL-MODULE-PATH", "--add-modules ALL-MODULE-PATH")] +#[case::single_known("v=${version_name}", "v=1.20.1")] +#[case::unknown_placeholder("x=${not_a_real_var}y", "x=${not_a_real_var}y")] +#[case::unclosed_placeholder("--prefix ${unclosed", "--prefix ${unclosed")] +#[case::dollar_without_brace("$$ literal $5 $", "$$ literal $5 $")] +#[case::multiple("${version_name}-${auth_player_name}", "1.20.1-Player")] +#[case::path( + "-DlibraryDirectory=${library_directory}", + "-DlibraryDirectory=/m/libraries" +)] +#[case::empty_input("", "")] +fn substitute_handles(#[case] input: &str, #[case] expected: &str) { + let fx = Fixture::unix(); + assert_eq!(substitute(input, &fx.ctx()), expected); +} + +#[test] +fn substituted_value_is_not_recursively_substituted() { + // simulate a user_properties value that happens to contain a ${...} + // pattern. it should NOT trigger another substitution pass. + let mut fx = Fixture::unix(); + fx.user_properties = "${version_name}".to_string(); + assert_eq!( + substitute("${user_properties}", &fx.ctx()), + "${version_name}" + ); +} + +#[test] +fn windows_style_backslashes_in_value_pass_through() { + // simulate a Windows install where library_directory is a path with + // backslashes. the substitution must not interpret backslashes as + // escape sequences or do anything else clever - it just copies the + // value into the output. + let fx = Fixture::windows(); + let result = substitute("-Dpath=${library_directory}", &fx.ctx()); + assert!( + result.contains(r"C:\Users\test\.minecraft\libraries"), + "expected backslashes preserved, got: {result}" + ); +} diff --git a/src/layout_migration.rs b/src/layout_migration.rs index 117a582..dacf891 100644 --- a/src/layout_migration.rs +++ b/src/layout_migration.rs @@ -644,214 +644,5 @@ fn write_json_atomic(path: &Path, value: &impl Serialize) -> Result<(), Migratio } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn migration_backs_up_and_renames_instance_directories() { - let temp = tempfile::tempdir().unwrap(); - let instances = temp.path().join("instances"); - let meta = temp.path().join("meta"); - let config = temp.path().join("config.toml"); - let instance = instances.join("Example"); - fs::create_dir_all(instance.join(".minecraft/saves/world")).unwrap(); - fs::create_dir_all(instance.join(".rmcl/config-sync/local-config/config")).unwrap(); - fs::write(instance.join(".minecraft/saves/world/level.dat"), b"world").unwrap(); - fs::write( - instance.join(".rmcl/config-sync/local-config/options.txt"), - b"options", - ) - .unwrap(); - fs::write(&config, b"[paths]").unwrap(); - fs::create_dir_all(meta.join("config-sync/profiles/main")).unwrap(); - fs::write( - meta.join("config-sync/profiles/main/options.txt"), - b"profile", - ) - .unwrap(); - - let mut progress = Vec::new(); - let backup = run(&instances, &meta, &config, |update| progress.push(update)).unwrap(); - - assert_eq!( - fs::read(instance.join("minecraft/saves/world/level.dat")).unwrap(), - b"world" - ); - assert_eq!( - fs::read(instance.join("rmcl/content/config/options.txt")).unwrap(), - b"options" - ); - assert!(backup.join("instances/Example/.minecraft").exists()); - assert!(backup.join("profiles/legacy/main/options.txt").exists()); - assert!( - backup - .file_name() - .unwrap() - .to_string_lossy() - .starts_with("backup-") - ); - assert!(!meta.join("config-sync").exists()); - assert!(progress.iter().any(|update| { - update.item_total.is_some_and(|total| total > 0) - && update.item_current.is_some_and(|current| current > 0) - })); - assert_eq!( - marker_version(&MetadataPaths::new(&meta).layout_marker()), - Some(LAYOUT_VERSION) - ); - assert!(cache_rebuild_pending(&meta)); - assert_eq!(run(&instances, &meta, &config, |_| {}).unwrap(), backup); - finish_cache_rebuild(&meta).unwrap(); - assert!(!cache_rebuild_pending(&meta)); - } - - #[test] - fn migration_resumes_from_the_recorded_journal() { - let temp = tempfile::tempdir().unwrap(); - let instances = temp.path().join("instances"); - let meta = temp.path().join("meta"); - let config = temp.path().join("config.toml"); - let done = instances.join("Done"); - let pending = instances.join("Pending"); - fs::create_dir_all(done.join("minecraft")).unwrap(); - fs::create_dir_all(pending.join(".minecraft/saves")).unwrap(); - - let metadata = MetadataPaths::new(&meta); - fs::create_dir_all(metadata.state()).unwrap(); - fs::create_dir_all(metadata.backups()).unwrap(); - let backup = metadata.backups().join("backup-resume"); - fs::create_dir_all(&backup).unwrap(); - write_json_atomic( - &metadata.migration_journal(), - &MigrationJournal { - version: LAYOUT_VERSION, - backup_dir: backup.clone(), - completed: vec!["backup".to_owned(), "instance:Done".to_owned()], - }, - ) - .unwrap(); - - assert_eq!(run(&instances, &meta, &config, |_| {}).unwrap(), backup); - assert!(done.join("minecraft").exists()); - assert!(pending.join("minecraft/saves").exists()); - assert!(!metadata.migration_journal().exists()); - } - - #[test] - fn stale_partial_backup_is_replaced() { - let temp = tempfile::tempdir().unwrap(); - let instances = temp.path().join("instances"); - let backup = temp.path().join("backups/backup-test"); - let partial = backup.with_extension("partial"); - fs::create_dir_all(instances.join("Example")).unwrap(); - fs::write(instances.join("Example/data.txt"), b"current").unwrap(); - fs::create_dir_all(&partial).unwrap(); - fs::write(partial.join("stale.txt"), b"stale").unwrap(); - - backup_user_data( - &instances, - &temp.path().join("missing-config.toml"), - &temp.path().join("meta"), - &backup, - |_, _, _| {}, - ) - .unwrap(); - - assert_eq!( - fs::read(backup.join("instances/Example/data.txt")).unwrap(), - b"current" - ); - assert!(!backup.join("stale.txt").exists()); - assert!(!partial.exists()); - } - - #[test] - fn backup_rejects_overlap_and_insufficient_space() { - let temp = tempfile::tempdir().unwrap(); - let instances = temp.path().join("instances"); - fs::create_dir_all(&instances).unwrap(); - - let overlap = - validate_backup_destination(&instances, &instances.join("backup"), 0).unwrap_err(); - assert!(matches!(overlap, MigrationError::BackupOverlap(_))); - - let outside = temp.path().join("backups/backup"); - let insufficient = validate_backup_destination(&instances, &outside, u64::MAX).unwrap_err(); - assert!(matches!( - insufficient, - MigrationError::InsufficientSpace { .. } - )); - } - - #[test] - fn migration_need_follows_legacy_data_marker_and_pending_rebuild() { - let temp = tempfile::tempdir().unwrap(); - let instances = temp.path().join("instances"); - let meta = temp.path().join("meta"); - fs::create_dir_all(instances.join("Example/.minecraft")).unwrap(); - - assert!(is_needed(&instances, &meta)); - initialize_new_layout(&meta).unwrap(); - assert!(!is_needed(&instances, &meta)); - fs::write(MetadataPaths::new(&meta).layout_marker(), b"invalid marker").unwrap(); - assert!(is_needed(&instances, &meta)); - initialize_new_layout(&meta).unwrap(); - fs::write( - MetadataPaths::new(&meta).cache_rebuild_pending(), - LAYOUT_VERSION.to_string(), - ) - .unwrap(); - assert!(is_needed(&instances, &meta)); - } - - #[cfg(unix)] - #[test] - fn backup_preserves_symlinks() { - let temp = tempfile::tempdir().unwrap(); - let source = temp.path().join("source"); - let destination = temp.path().join("destination"); - fs::create_dir_all(&source).unwrap(); - fs::write(source.join("target.txt"), b"target").unwrap(); - std::os::unix::fs::symlink("target.txt", source.join("link.txt")).unwrap(); - - copy_dir_recursive_with_progress(&source, &destination, &mut |_, _| {}).unwrap(); - - assert_eq!( - fs::read_link(destination.join("link.txt")).unwrap(), - PathBuf::from("target.txt") - ); - } - - #[test] - fn conflicting_visible_and_hidden_directories_are_not_merged() { - let temp = tempfile::tempdir().unwrap(); - let instance = temp.path().join("Example"); - fs::create_dir_all(instance.join(".minecraft")).unwrap(); - fs::create_dir_all(instance.join("minecraft")).unwrap(); - let error = migrate_instance(&instance, "Example").unwrap_err(); - assert!(matches!(error, MigrationError::PathConflict { .. })); - } - - #[test] - fn merge_conflicts_do_not_overwrite_existing_profiles() { - let temp = tempfile::tempdir().unwrap(); - let source = temp.path().join("legacy"); - let destination = temp.path().join("current"); - fs::create_dir_all(source.join("nested")).unwrap(); - fs::create_dir_all(destination.join("nested")).unwrap(); - fs::write(source.join("nested/options.txt"), b"legacy").unwrap(); - fs::write(destination.join("nested/options.txt"), b"current").unwrap(); - - let error = move_or_merge(&source, &destination).unwrap_err(); - - assert!(matches!(error, MigrationError::MergeConflict { .. })); - assert_eq!( - fs::read(destination.join("nested/options.txt")).unwrap(), - b"current" - ); - assert_eq!( - fs::read(source.join("nested/options.txt")).unwrap(), - b"legacy" - ); - } -} +#[path = "tests/layout_migration.rs"] +mod tests; diff --git a/src/lib.rs b/src/lib.rs index 8ad740f..1ade360 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,16 +7,20 @@ pub mod auth; mod cli; pub mod config; -pub mod content_provider; +pub mod feedback; pub mod instance; -pub mod instance_logs; pub mod launch_profile; pub mod layout_migration; mod migrate; pub mod net; -pub mod running; pub mod storage; pub mod tui; +#[cfg(test)] +pub(crate) mod tests; + pub use cli::init as cli_init; +pub use instance::content::provider as content_provider; +pub use instance::logs::live as instance_logs; +pub use instance::runtime as running; pub use migrate::run_legacy_rename as migrate_legacy_rename; diff --git a/src/migrate.rs b/src/migrate.rs index 6821f35..e9b73d7 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -173,127 +173,5 @@ fn sanitize(name: &str) -> String { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn rename_top_level_moves_when_only_old_exists() { - let tmp = tempfile::tempdir().unwrap(); - let old = tmp.path().join("mcl"); - let new = tmp.path().join("rmcl"); - fs::create_dir_all(old.join("sub")).unwrap(); - fs::write(old.join("sub").join("f.txt"), b"hi").unwrap(); - - rename_top_level(&old, &new); - - assert!(!old.exists()); - assert!(new.exists()); - assert_eq!(fs::read(new.join("sub").join("f.txt")).unwrap(), b"hi"); - } - - #[test] - fn rename_top_level_skips_when_only_new_exists() { - let tmp = tempfile::tempdir().unwrap(); - let old = tmp.path().join("mcl"); - let new = tmp.path().join("rmcl"); - fs::create_dir_all(&new).unwrap(); - fs::write(new.join("marker.txt"), b"keep").unwrap(); - - rename_top_level(&old, &new); - - assert!(!old.exists()); - assert_eq!(fs::read(new.join("marker.txt")).unwrap(), b"keep"); - } - - #[test] - fn rename_top_level_skips_when_both_exist() { - let tmp = tempfile::tempdir().unwrap(); - let old = tmp.path().join("mcl"); - let new = tmp.path().join("rmcl"); - fs::create_dir_all(&old).unwrap(); - fs::create_dir_all(&new).unwrap(); - fs::write(old.join("a"), b"old").unwrap(); - fs::write(new.join("b"), b"new").unwrap(); - - rename_top_level(&old, &new); - - assert!(old.exists(), "old should remain when both exist"); - assert!(new.exists(), "new should remain when both exist"); - assert_eq!(fs::read(old.join("a")).unwrap(), b"old"); - assert_eq!(fs::read(new.join("b")).unwrap(), b"new"); - } - - #[test] - fn rename_top_level_noop_when_neither_exists() { - let tmp = tempfile::tempdir().unwrap(); - let old = tmp.path().join("mcl"); - let new = tmp.path().join("rmcl"); - - rename_top_level(&old, &new); - - assert!(!old.exists()); - assert!(!new.exists()); - } - - #[test] - fn cleanup_instance_leftovers_removes_shim_and_log4j() { - let tmp = tempfile::tempdir().unwrap(); - let instances = tmp.path().join("instances"); - let mc = instances - .join("Test") - .join(crate::storage::MINECRAFT_DIR_NAME); - fs::create_dir_all(&mc).unwrap(); - fs::write(mc.join(".mcl-shim.jar"), b"jar").unwrap(); - fs::write(mc.join(".mcl-log4j2.xml"), b"xml").unwrap(); - fs::write(mc.join("keep.txt"), b"keep").unwrap(); - - cleanup_instance_leftovers(&instances); - - assert!(!mc.join(".mcl-shim.jar").exists()); - assert!(!mc.join(".mcl-log4j2.xml").exists()); - assert!(mc.join("keep.txt").exists()); - } - - #[test] - #[cfg(target_os = "linux")] - fn rewrite_linux_desktop_entries_renames_and_rewrites_exec() { - let tmp = tempfile::tempdir().unwrap(); - let data = tmp.path(); - let instances = data.join("rmcl").join("instances"); - let apps = data.join("applications"); - fs::create_dir_all(instances.join("MyPack")).unwrap(); - fs::create_dir_all(&apps).unwrap(); - let old_entry = apps.join("mcl-MyPack.desktop"); - fs::write( - &old_entry, - "[Desktop Entry]\nName=Test\nExec=mcl instance launch \"MyPack\"\n", - ) - .unwrap(); - - rewrite_linux_desktop_entries(data, &instances); - - let new_entry = apps.join("rmcl-MyPack.desktop"); - assert!(!old_entry.exists(), "old .desktop should be removed"); - assert!(new_entry.exists(), "new .desktop should exist"); - let content = fs::read_to_string(&new_entry).unwrap(); - assert!(content.contains("Exec=rmcl instance launch \"MyPack\"")); - } - - #[test] - fn copy_dir_recursive_copies_nested_tree() { - let tmp = tempfile::tempdir().unwrap(); - let src = tmp.path().join("a"); - let dst = tmp.path().join("b"); - fs::create_dir_all(src.join("nested")).unwrap(); - fs::write(src.join("top.txt"), b"top").unwrap(); - fs::write(src.join("nested").join("inner.txt"), b"inner").unwrap(); - - copy_dir_recursive(&src, &dst).unwrap(); - - assert_eq!(fs::read(dst.join("top.txt")).unwrap(), b"top"); - assert_eq!( - fs::read(dst.join("nested").join("inner.txt")).unwrap(), - b"inner" - ); - } -} +#[path = "tests/migrate.rs"] +mod tests; diff --git a/src/net/fabric.rs b/src/net/fabric.rs index c65d130..d8211bc 100644 --- a/src/net/fabric.rs +++ b/src/net/fabric.rs @@ -5,9 +5,9 @@ use std::path::Path; use serde::{Deserialize, Serialize}; +use crate::feedback::progress::set_sub_action; use crate::instance::loader::GameVersion; use crate::net::{HttpClient, NetError, download_file}; -use crate::tui::progress::set_sub_action; const FABRIC_META_BASE: &str = "https://meta.fabricmc.net/v2"; @@ -163,7 +163,7 @@ pub async fn download_fabric_libraries( ); for lib in &profile.libraries { - let maven_path = match crate::net::maven_coord_to_path(&lib.name) { + let maven_path = match crate::instance::loader::maven::maven_coord_to_path(&lib.name) { Some(p) => p, None => { return Err(NetError::Parse(format!( diff --git a/src/net/forge.rs b/src/net/forge.rs index 903ad45..76ca12a 100644 --- a/src/net/forge.rs +++ b/src/net/forge.rs @@ -7,9 +7,11 @@ use std::path::Path; use serde::Deserialize; -use crate::instance::loader::{GameVersion, InstallError, InstallerError}; +use crate::feedback::progress::set_action; +use crate::instance::loader::GameVersion; use crate::net::{HttpClient, NetError, download_file}; -use crate::tui::progress::{set_action, set_sub_action}; + +pub use crate::instance::loader::forge::run_forge_installer; const FORGE_PROMOTIONS_URL: &str = "https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json"; @@ -115,7 +117,7 @@ pub async fn download_forge_installer( 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); + crate::feedback::progress::set_progress(downloaded, total); }) .await { @@ -136,300 +138,3 @@ pub async fn download_forge_installer( )) })) } - -pub async fn run_forge_installer( - installer_path: &Path, - instance_dir: &Path, - java_path: &str, -) -> Result<(), InstallerError> { - use tokio::process::Command; - - set_action("Running Forge installer..."); - - let output = match Command::new(java_path) - .arg("-jar") - .arg(installer_path) - .arg("--installClient") - .current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)) - .output() - .await - { - Ok(o) => o, - Err(e) => { - tracing::debug!( - "Failed to spawn Forge installer {} with Java {}: {}", - installer_path.display(), - java_path, - e - ); - return Err(InstallerError::Io(e)); - } - }; - - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - let detail = if stderr.trim().is_empty() { - format!("exit code {:?}", output.status.code()) - } else { - stderr.lines().last().unwrap_or("unknown error").to_string() - }; - tracing::debug!( - "Forge installer {} failed with status {:?}: {}", - installer_path.display(), - output.status.code(), - detail - ); - return Err(InstallerError::ProcessFailed(detail)); - } - - tracing::debug!("Forge installer completed successfully"); - Ok(()) -} - -// old forge installers have an install_profile.json with a "versionInfo" key -// containing everything needed. modern ones don't have this structure. -pub(crate) fn has_legacy_install_profile(installer_path: &Path) -> bool { - let file = match std::fs::File::open(installer_path) { - Ok(f) => f, - Err(_) => return false, - }; - let mut archive = match zip::ZipArchive::new(file) { - Ok(a) => a, - Err(_) => return false, - }; - let entry = match archive.by_name("install_profile.json") { - Ok(e) => e, - Err(_) => return false, - }; - let value: serde_json::Value = match serde_json::from_reader(entry) { - Ok(v) => v, - Err(_) => return false, - }; - value.get("versionInfo").is_some() -} - -// handles old-style forge installation by extracting the universal jar and -// library info directly from the installer, bypassing the GUI-only installer -pub(crate) async fn install_forge_from_profile( - client: &HttpClient, - installer_path: &Path, - meta_dir: &Path, - profile_filename: &str, -) -> Result<(), InstallError> { - use std::io::Read; - - set_action("Installing legacy Forge from profile..."); - tracing::debug!( - "Installing legacy Forge from {} into {}", - installer_path.display(), - meta_dir.display() - ); - - let file = std::fs::File::open(installer_path) - .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; - let mut archive = zip::ZipArchive::new(file).map_err(|e| { - InstallError::Installer(InstallerError::Profile(format!( - "Failed to open installer as ZIP: {e}" - ))) - })?; - - let profile_data: serde_json::Value = { - let entry = archive.by_name("install_profile.json").map_err(|e| { - InstallError::Installer(InstallerError::Profile(format!( - "install_profile.json not found in installer: {e}" - ))) - })?; - serde_json::from_reader(entry).map_err(|e| { - InstallError::Installer(InstallerError::Profile(format!( - "Failed to parse install_profile.json: {e}" - ))) - })? - }; - - let version_info = profile_data.get("versionInfo").ok_or_else(|| { - InstallError::Installer(InstallerError::Profile( - "install_profile.json missing versionInfo".into(), - )) - })?; - let install_info = profile_data.get("install").ok_or_else(|| { - InstallError::Installer(InstallerError::Profile( - "install_profile.json missing install section".into(), - )) - })?; - - let libraries = version_info - .get("libraries") - .and_then(|v| v.as_array()) - .ok_or_else(|| { - InstallError::Installer(InstallerError::Profile( - "missing versionInfo.libraries".into(), - )) - })?; - - let file_path = install_info - .get("filePath") - .and_then(|v| v.as_str()) - .ok_or_else(|| { - InstallError::Installer(InstallerError::Profile("missing install.filePath".into())) - })?; - - let install_path_coord = install_info - .get("path") - .and_then(|v| v.as_str()) - .ok_or_else(|| { - InstallError::Installer(InstallerError::Profile("missing install.path".into())) - })?; - - // extract the universal jar to the correct maven location - let universal_maven_path = - crate::net::maven_coord_to_path(install_path_coord).ok_or_else(|| { - InstallError::Installer(InstallerError::Profile(format!( - "Invalid maven coord in install.path: {install_path_coord}" - ))) - })?; - - set_sub_action("Extracting universal JAR..."); - let universal_dest = crate::storage::MetadataPaths::new(meta_dir) - .libraries() - .join(&universal_maven_path); - if let Some(parent) = universal_dest.parent() { - std::fs::create_dir_all(parent) - .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; - } - - { - let mut entry = archive.by_name(file_path).map_err(|e| { - InstallError::Installer(InstallerError::Profile(format!( - "Universal JAR '{file_path}' not found in installer: {e}" - ))) - })?; - let mut buf = Vec::new(); - entry - .read_to_end(&mut buf) - .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; - std::fs::write(&universal_dest, &buf) - .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; - tracing::debug!( - "Extracted legacy Forge universal JAR to {} ({} bytes)", - universal_dest.display(), - buf.len() - ); - } - - // download libraries needed by this forge version. libs with a url field - // are forge-hosted, libs without one are typically from mojang's library - // server. old forge versions reference libs like launchwrapper that aren't - // in mojang's modern version metadata, so we fetch those too. - let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries(); - for lib in libraries { - let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default(); - - let maven_path = match crate::net::maven_coord_to_path(name) { - Some(p) => p, - None => { - return Err(InstallError::Installer(InstallerError::Profile(format!( - "Invalid Maven coordinate: {name}" - )))); - } - }; - - let dest = libraries_dir.join(&maven_path); - if dest.exists() { - tracing::trace!("Legacy Forge library already cached: {}", name); - continue; - } - - let base_url = lib - .get("url") - .and_then(|v| v.as_str()) - .unwrap_or("https://libraries.minecraft.net/") - .trim_end_matches('/'); - 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?; - } - - set_action("Saving Forge profile..."); - // write the installer's versionInfo as compact JSON. it already has the - // mainClass, the full library list (with name + url for forge-hosted - // libs), and minecraftArguments (the legacy --tweakClass etc). the - // launch flow parses this as a LaunchProfile and - if there's no - // inheritsFrom field - implicitly inherits from the configured game - // version so vanilla libraries layer in via resolve(). - // - // we use serde_json::to_vec (not the pretty-print variant via - // save_profile_json) so the written file is content-faithful: every - // field present in the installer's versionInfo round-trips. key order - // and whitespace may differ from the original installer JSON because - // the source is a serde_json::Value (which doesn't preserve order), - // but no field is silently dropped. - let serialized = serde_json::to_vec(version_info).map_err(|e| { - InstallError::Installer(InstallerError::Profile(format!( - "Failed to serialize Forge profile: {e}" - ))) - })?; - crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized) - .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - // builds an in-memory zip in a tempdir with the given json as - // install_profile.json. lets the legacy-install-profile detector be - // tested without an actual forge installer. - fn make_installer_zip(tmp: &std::path::Path, json: &serde_json::Value) -> std::path::PathBuf { - use std::io::Write; - let path = tmp.join("installer.jar"); - let file = std::fs::File::create(&path).unwrap(); - let mut zip = zip::ZipWriter::new(file); - let opts: zip::write::SimpleFileOptions = Default::default(); - zip.start_file("install_profile.json", opts).unwrap(); - zip.write_all(serde_json::to_string(json).unwrap().as_bytes()) - .unwrap(); - zip.finish().unwrap(); - path - } - - #[test] - fn has_legacy_install_profile_true_when_version_info_present() { - let tmp = tempfile::tempdir().unwrap(); - let jar = make_installer_zip( - tmp.path(), - &serde_json::json!({ - "install": {}, - "versionInfo": { - "id": "1.7.10-Forge10.13.4.1614-1.7.10", - "mainClass": "net.minecraft.launchwrapper.Launch" - } - }), - ); - assert!(has_legacy_install_profile(&jar)); - } - - #[test] - fn has_legacy_install_profile_false_when_version_info_absent() { - let tmp = tempfile::tempdir().unwrap(); - let jar = make_installer_zip( - tmp.path(), - &serde_json::json!({ - "spec": 1, - "minecraft": "1.20.1", - "data": {} - }), - ); - assert!(!has_legacy_install_profile(&jar)); - } - - #[test] - fn has_legacy_install_profile_false_for_missing_jar() { - let tmp = tempfile::tempdir().unwrap(); - assert!(!has_legacy_install_profile( - &tmp.path().join("missing-installer.jar") - )); - } -} diff --git a/src/net/mod.rs b/src/net/mod.rs index e96d7b7..d5884b8 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -8,6 +8,9 @@ pub mod mojang; pub mod neoforge; pub mod quilt; +pub use crate::instance::java::detect_java_path; +pub use crate::instance::loader::maven::maven_coord_to_path; + use reqwest::Client; use serde::Serialize; use serde::de::DeserializeOwned; @@ -277,95 +280,3 @@ fn is_retryable(err: &NetError) -> bool { _ => false, } } - -// tries JAVA_HOME first, then PATH, then just yolos "java" and hopes for the best -#[must_use] -pub fn detect_java_path() -> String { - if let Ok(java_home) = std::env::var("JAVA_HOME") { - 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::trace!("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::trace!("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() - } - } -} - -// converts maven coordinates like "org.example:artifact:1.0" into a -// filesystem path like "org/example/artifact/1.0/artifact-1.0.jar". -// supports optional classifier as a 4th component. -#[must_use] -pub fn maven_coord_to_path(coord: &str) -> Option { - let parts: Vec<&str> = coord.split(':').collect(); - match parts.as_slice() { - [group, artifact, version] => { - let group_path = group.replace('.', "/"); - Some(format!( - "{}/{}/{}/{}-{}.jar", - group_path, artifact, version, artifact, version - )) - } - [group, artifact, version, classifier] => { - let group_path = group.replace('.', "/"); - Some(format!( - "{}/{}/{}/{}-{}-{}.jar", - group_path, artifact, version, artifact, version, classifier - )) - } - _ => None, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn maven_3_part_coord() { - assert_eq!( - maven_coord_to_path("org.example:artifact:1.0"), - Some("org/example/artifact/1.0/artifact-1.0.jar".to_string()) - ); - } - - #[test] - fn maven_4_part_coord_with_classifier() { - assert_eq!( - maven_coord_to_path("org.example:artifact:1.0:sources"), - Some("org/example/artifact/1.0/artifact-1.0-sources.jar".to_string()) - ); - } - - #[test] - fn maven_nested_group() { - assert_eq!( - maven_coord_to_path("com.google.code.gson:gson:2.10"), - Some("com/google/code/gson/gson/2.10/gson-2.10.jar".to_string()) - ); - } - - #[test] - fn maven_invalid_coordinates() { - for coordinate in ["org.example:artifact", "a:b:c:d:e", "just-a-string", ""] { - assert_eq!(maven_coord_to_path(coordinate), None); - } - } -} diff --git a/src/net/modrinth.rs b/src/net/modrinth.rs index eb7fc6e..9c6c573 100644 --- a/src/net/modrinth.rs +++ b/src/net/modrinth.rs @@ -107,7 +107,7 @@ pub async fn search_discovery( offset: usize, limit: usize, ) -> Result { - let progress = crate::tui::progress::ProgressTask::start(if query.trim().is_empty() { + let progress = crate::feedback::progress::ProgressTask::start(if query.trim().is_empty() { "Loading Modrinth discovery".to_owned() } else { format!("Searching Modrinth for '{}'", query.trim()) @@ -235,7 +235,8 @@ pub async fn fetch_content_versions( game_version: &str, loader: ModLoader, ) -> Result, crate::net::NetError> { - let progress = crate::tui::progress::ProgressTask::start("Loading compatible project versions"); + let progress = + crate::feedback::progress::ProgressTask::start("Loading compatible project versions"); let url = content_versions_url(API_BASE, project_id, kind, game_version, loader); tracing::debug!( "Fetching compatible Modrinth versions for '{}' ({}, {})", @@ -320,7 +321,7 @@ pub async fn download_version_file( tokio::fs::remove_file(&temporary).await?; } let progress = - crate::tui::progress::ProgressTask::start(format!("Downloading {}", file.filename)); + crate::feedback::progress::ProgressTask::start(format!("Downloading {}", file.filename)); crate::net::download_file(client, &file.url, &temporary, |current, total| { progress.set_progress(current, total); }) @@ -363,7 +364,7 @@ pub async fn download_version_file_for_update( } let progress = - crate::tui::progress::ProgressTask::start(format!("Downloading {}", file.filename)); + crate::feedback::progress::ProgressTask::start(format!("Downloading {}", file.filename)); crate::net::download_file(client, &file.url, &temporary, |current, total| { progress.set_progress(current, total); }) @@ -475,203 +476,5 @@ pub async fn download_mrpack( } #[cfg(test)] -mod tests { - use super::*; - - fn version_with_files(files: Vec) -> VersionInfo { - VersionInfo { - id: "version-id".to_owned(), - project_id: "project-id".to_owned(), - name: "Version 1".to_owned(), - version_number: "1.0.0".to_owned(), - game_versions: vec!["1.21.1".to_owned()], - loaders: vec!["fabric".to_owned()], - date_published: String::new(), - files, - } - } - - #[test] - fn discovery_mod_facets_include_instance_compatibility() { - let facets = discovery_facets(ContentKind::Mod, "1.21.1", ModLoader::Fabric); - assert_eq!( - serde_json::from_str::>>(&facets).unwrap(), - vec![ - vec!["project_type:mod"], - vec!["versions:1.21.1"], - vec!["categories:fabric"], - ] - ); - } - - #[test] - fn discovery_resource_pack_facets_do_not_require_loader() { - let facets = discovery_facets(ContentKind::ResourcePack, "1.20.1", ModLoader::Forge); - assert_eq!( - serde_json::from_str::>>(&facets).unwrap(), - vec![vec!["project_type:resourcepack"], vec!["versions:1.20.1"]] - ); - } - - #[test] - fn compatible_mod_versions_filter_by_game_and_loader() { - let url = content_versions_url( - "https://example.test/v2", - "fabric-api", - ContentKind::Mod, - "1.21.1", - ModLoader::Fabric, - ); - assert_eq!( - url, - "https://example.test/v2/project/fabric-api/version?include_changelog=false&game_versions=%5B%221.21.1%22%5D&loaders=%5B%22fabric%22%5D" - ); - } - - #[test] - fn compatible_resource_pack_versions_do_not_filter_by_loader() { - let url = content_versions_url( - "https://example.test/v2", - "stay-true", - ContentKind::ResourcePack, - "1.21.1", - ModLoader::Fabric, - ); - assert_eq!( - url, - "https://example.test/v2/project/stay-true/version?include_changelog=false&game_versions=%5B%221.21.1%22%5D" - ); - } - - #[test] - fn primary_file_selection_falls_back_to_first_file() { - let version = version_with_files(vec![ - VersionFile { - url: "https://example.test/first.jar".to_owned(), - filename: "first.jar".to_owned(), - size: 1, - primary: false, - hashes: HashMap::new(), - }, - VersionFile { - url: "https://example.test/primary.jar".to_owned(), - filename: "primary.jar".to_owned(), - size: 1, - primary: true, - hashes: HashMap::new(), - }, - ]); - assert_eq!( - select_primary_file(&version).unwrap().filename, - "primary.jar" - ); - - let fallback = version_with_files(vec![VersionFile { - url: "https://example.test/first.jar".to_owned(), - filename: "first.jar".to_owned(), - size: 1, - primary: false, - hashes: HashMap::new(), - }]); - assert_eq!( - select_primary_file(&fallback).unwrap().filename, - "first.jar" - ); - } - - #[tokio::test] - async fn content_download_skips_an_existing_filename() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("example.jar"); - std::fs::write(&path, b"existing").unwrap(); - let version = version_with_files(vec![VersionFile { - url: "https://example.test/example.jar".to_owned(), - filename: "example.jar".to_owned(), - size: b"existing".len() as u64, - primary: true, - hashes: HashMap::new(), - }]); - - let outcome = - download_version_file(&crate::net::HttpClient::new(), &version, directory.path()) - .await - .unwrap(); - - assert_eq!(outcome, DownloadOutcome::SkippedExisting(path)); - assert_eq!( - std::fs::read(directory.path().join("example.jar")).unwrap(), - b"existing" - ); - } - - #[tokio::test] - async fn staged_update_replaces_the_old_file_and_cleans_its_backup() { - let directory = tempfile::tempdir().unwrap(); - let installed = directory.path().join("example.jar"); - let temporary = directory.path().join(".example.jar.rmcl-download"); - let backup = directory.path().join(".example.jar.rmcl-backup"); - std::fs::write(&installed, b"old version").unwrap(); - std::fs::write(&temporary, b"new version").unwrap(); - - replace_installed_file(&temporary, &installed, &installed, &backup) - .await - .unwrap(); - - assert_eq!(std::fs::read(installed).unwrap(), b"new version"); - assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1); - } - - #[test] - fn discovery_search_ignores_new_modrinth_enum_values() { - let response: DiscoverySearchResponse = serde_json::from_str( - r#"{ - "hits": [{ - "project_id": "project-id", - "slug": "example", - "title": "Example", - "description": "Example project", - "downloads": 42, - "icon_url": null, - "client_side": "unknown", - "server_side": "unknown" - }], - "total_hits": 1 - }"#, - ) - .unwrap(); - - assert_eq!(response.hits.len(), 1); - assert_eq!(response.hits[0].project_id, "project-id"); - assert_eq!(response.total_hits, 1); - } - - #[test] - fn discovery_search_treats_blank_icon_urls_as_missing() { - let hit: DiscoverySearchHit = serde_json::from_str( - r#"{ - "project_id": "project-id", - "slug": "example", - "title": "Example", - "description": "Example project", - "icon_url": " " - }"#, - ) - .unwrap(); - - assert!(DiscoveryProject::from(hit).icon_url.is_none()); - } - - // covers each branch of url_encode: unreserved bytes pass through; the - // reserved set + spaces + non-ascii bytes get percent-encoded. emoji - // exercises multi-byte UTF-8 since the encoder operates on bytes, not - // chars, so each byte of the codepoint encodes separately. - #[rstest::rstest] - #[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")] - #[case::space("hello world", "hello%20world")] - #[case::reserved("/?&=#", "%2F%3F%26%3D%23")] - #[case::utf8_emoji("\u{2603}", "%E2%98%83")] - #[case::empty("", "")] - fn url_encode_handles(#[case] input: &str, #[case] expected: &str) { - assert_eq!(url_encode(input), expected); - } -} +#[path = "tests/modrinth.rs"] +mod tests; diff --git a/src/net/mojang.rs b/src/net/mojang.rs index 14861f4..c8a82b7 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize}; use tokio::task::JoinSet; use super::{HttpClient, NetError, download_file}; -use crate::tui::progress::{clear, set_action, set_progress, set_sub_action}; +use crate::feedback::progress::{clear, set_action, set_progress, set_sub_action}; const MANIFEST_URL: &str = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"; const ASSETS_BASE_URL: &str = "https://resources.download.minecraft.net"; diff --git a/src/net/neoforge.rs b/src/net/neoforge.rs index 17d4f50..209cf15 100644 --- a/src/net/neoforge.rs +++ b/src/net/neoforge.rs @@ -7,10 +7,11 @@ use std::path::Path; use serde::Deserialize; +use crate::feedback::progress::set_action; use crate::instance::loader::GameVersion; -use crate::instance::loader::InstallerError; use crate::net::{HttpClient, NetError, download_file}; -use crate::tui::progress::set_action; + +pub use crate::instance::loader::neoforge::run_neoforge_installer; const NEOFORGE_MAVEN_BASE: &str = "https://maven.neoforged.net/releases/net/neoforged/neoforge"; const NEOFORGE_API_BASE: &str = @@ -163,82 +164,11 @@ pub async fn download_neoforge_installer( ); download_file(client, &url, dest, |downloaded, total| { - crate::tui::progress::set_progress(downloaded, total); + crate::feedback::progress::set_progress(downloaded, total); }) .await } -pub async fn run_neoforge_installer( - installer_path: &Path, - instance_dir: &Path, - java_path: &str, -) -> Result<(), InstallerError> { - use tokio::process::Command; - - set_action("Running NeoForge installer..."); - - let output = match Command::new(java_path) - .arg(format!("-Duser.home={}", instance_dir.display())) - .arg("-jar") - .arg(installer_path) - .arg("--installClient") - .current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)) - .output() - .await - { - Ok(o) => o, - Err(e) => { - tracing::debug!( - "Failed to spawn NeoForge installer {} with Java {}: {}", - installer_path.display(), - java_path, - e - ); - return Err(InstallerError::Io(e)); - } - }; - - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - let detail = stderr.lines().last().unwrap_or("").trim(); - tracing::debug!( - "NeoForge installer {} failed with status {:?}: {}", - installer_path.display(), - output.status.code(), - detail - ); - return Err(InstallerError::ProcessFailed(format!( - "NeoForge installer exited with {:?}", - output.status.code() - ))); - } - - tracing::debug!("NeoForge installer completed successfully"); - Ok(()) -} - #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_game_version_to_neoforge_prefix() { - assert_eq!( - game_version_to_neoforge_prefix("1.21"), - Some("21.0.".to_string()) - ); - assert_eq!( - game_version_to_neoforge_prefix("1.20.4"), - Some("20.4.".to_string()) - ); - assert_eq!( - game_version_to_neoforge_prefix("1.21.1"), - Some("21.1.".to_string()) - ); - assert_eq!( - game_version_to_neoforge_prefix("26.1.2"), - Some("26.1.2.".to_string()) - ); - assert_eq!(game_version_to_neoforge_prefix("invalid"), None); - } -} +#[path = "tests/neoforge.rs"] +mod tests; diff --git a/src/net/quilt.rs b/src/net/quilt.rs index d284061..a1eac82 100644 --- a/src/net/quilt.rs +++ b/src/net/quilt.rs @@ -5,9 +5,9 @@ use std::path::Path; use serde::{Deserialize, Serialize}; +use crate::feedback::progress::set_sub_action; use crate::instance::loader::GameVersion; use crate::net::{HttpClient, NetError, download_file}; -use crate::tui::progress::set_sub_action; const QUILT_META_BASE: &str = "https://meta.quiltmc.org/v3"; @@ -157,7 +157,7 @@ pub async fn download_quilt_libraries( ); for lib in &profile.libraries { - let maven_path = match crate::net::maven_coord_to_path(&lib.name) { + let maven_path = match crate::instance::loader::maven::maven_coord_to_path(&lib.name) { Some(p) => p, None => { return Err(NetError::Parse(format!( diff --git a/src/net/tests/modrinth.rs b/src/net/tests/modrinth.rs new file mode 100644 index 0000000..ff2494f --- /dev/null +++ b/src/net/tests/modrinth.rs @@ -0,0 +1,197 @@ +use super::*; + +fn version_with_files(files: Vec) -> VersionInfo { + VersionInfo { + id: "version-id".to_owned(), + project_id: "project-id".to_owned(), + name: "Version 1".to_owned(), + version_number: "1.0.0".to_owned(), + game_versions: vec!["1.21.1".to_owned()], + loaders: vec!["fabric".to_owned()], + date_published: String::new(), + files, + } +} + +#[test] +fn discovery_mod_facets_include_instance_compatibility() { + let facets = discovery_facets(ContentKind::Mod, "1.21.1", ModLoader::Fabric); + assert_eq!( + serde_json::from_str::>>(&facets).unwrap(), + vec![ + vec!["project_type:mod"], + vec!["versions:1.21.1"], + vec!["categories:fabric"], + ] + ); +} + +#[test] +fn discovery_resource_pack_facets_do_not_require_loader() { + let facets = discovery_facets(ContentKind::ResourcePack, "1.20.1", ModLoader::Forge); + assert_eq!( + serde_json::from_str::>>(&facets).unwrap(), + vec![vec!["project_type:resourcepack"], vec!["versions:1.20.1"]] + ); +} + +#[test] +fn compatible_mod_versions_filter_by_game_and_loader() { + let url = content_versions_url( + "https://example.test/v2", + "fabric-api", + ContentKind::Mod, + "1.21.1", + ModLoader::Fabric, + ); + assert_eq!( + url, + "https://example.test/v2/project/fabric-api/version?include_changelog=false&game_versions=%5B%221.21.1%22%5D&loaders=%5B%22fabric%22%5D" + ); +} + +#[test] +fn compatible_resource_pack_versions_do_not_filter_by_loader() { + let url = content_versions_url( + "https://example.test/v2", + "stay-true", + ContentKind::ResourcePack, + "1.21.1", + ModLoader::Fabric, + ); + assert_eq!( + url, + "https://example.test/v2/project/stay-true/version?include_changelog=false&game_versions=%5B%221.21.1%22%5D" + ); +} + +#[test] +fn primary_file_selection_falls_back_to_first_file() { + let version = version_with_files(vec![ + VersionFile { + url: "https://example.test/first.jar".to_owned(), + filename: "first.jar".to_owned(), + size: 1, + primary: false, + hashes: HashMap::new(), + }, + VersionFile { + url: "https://example.test/primary.jar".to_owned(), + filename: "primary.jar".to_owned(), + size: 1, + primary: true, + hashes: HashMap::new(), + }, + ]); + assert_eq!( + select_primary_file(&version).unwrap().filename, + "primary.jar" + ); + + let fallback = version_with_files(vec![VersionFile { + url: "https://example.test/first.jar".to_owned(), + filename: "first.jar".to_owned(), + size: 1, + primary: false, + hashes: HashMap::new(), + }]); + assert_eq!( + select_primary_file(&fallback).unwrap().filename, + "first.jar" + ); +} + +#[tokio::test] +async fn content_download_skips_an_existing_filename() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("example.jar"); + std::fs::write(&path, b"existing").unwrap(); + let version = version_with_files(vec![VersionFile { + url: "https://example.test/example.jar".to_owned(), + filename: "example.jar".to_owned(), + size: b"existing".len() as u64, + primary: true, + hashes: HashMap::new(), + }]); + + let outcome = download_version_file(&crate::net::HttpClient::new(), &version, directory.path()) + .await + .unwrap(); + + assert_eq!(outcome, DownloadOutcome::SkippedExisting(path)); + assert_eq!( + std::fs::read(directory.path().join("example.jar")).unwrap(), + b"existing" + ); +} + +#[tokio::test] +async fn staged_update_replaces_the_old_file_and_cleans_its_backup() { + let directory = tempfile::tempdir().unwrap(); + let installed = directory.path().join("example.jar"); + let temporary = directory.path().join(".example.jar.rmcl-download"); + let backup = directory.path().join(".example.jar.rmcl-backup"); + std::fs::write(&installed, b"old version").unwrap(); + std::fs::write(&temporary, b"new version").unwrap(); + + replace_installed_file(&temporary, &installed, &installed, &backup) + .await + .unwrap(); + + assert_eq!(std::fs::read(installed).unwrap(), b"new version"); + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1); +} + +#[test] +fn discovery_search_ignores_new_modrinth_enum_values() { + let response: DiscoverySearchResponse = serde_json::from_str( + r#"{ + "hits": [{ + "project_id": "project-id", + "slug": "example", + "title": "Example", + "description": "Example project", + "downloads": 42, + "icon_url": null, + "client_side": "unknown", + "server_side": "unknown" + }], + "total_hits": 1 + }"#, + ) + .unwrap(); + + assert_eq!(response.hits.len(), 1); + assert_eq!(response.hits[0].project_id, "project-id"); + assert_eq!(response.total_hits, 1); +} + +#[test] +fn discovery_search_treats_blank_icon_urls_as_missing() { + let hit: DiscoverySearchHit = serde_json::from_str( + r#"{ + "project_id": "project-id", + "slug": "example", + "title": "Example", + "description": "Example project", + "icon_url": " " + }"#, + ) + .unwrap(); + + assert!(DiscoveryProject::from(hit).icon_url.is_none()); +} + +// covers each branch of url_encode: unreserved bytes pass through; the +// reserved set + spaces + non-ascii bytes get percent-encoded. emoji +// exercises multi-byte UTF-8 since the encoder operates on bytes, not +// chars, so each byte of the codepoint encodes separately. +#[rstest::rstest] +#[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")] +#[case::space("hello world", "hello%20world")] +#[case::reserved("/?&=#", "%2F%3F%26%3D%23")] +#[case::utf8_emoji("\u{2603}", "%E2%98%83")] +#[case::empty("", "")] +fn url_encode_handles(#[case] input: &str, #[case] expected: &str) { + assert_eq!(url_encode(input), expected); +} diff --git a/src/net/tests/neoforge.rs b/src/net/tests/neoforge.rs new file mode 100644 index 0000000..c3d078d --- /dev/null +++ b/src/net/tests/neoforge.rs @@ -0,0 +1,22 @@ +use super::*; + +#[test] +fn test_game_version_to_neoforge_prefix() { + assert_eq!( + game_version_to_neoforge_prefix("1.21"), + Some("21.0.".to_string()) + ); + assert_eq!( + game_version_to_neoforge_prefix("1.20.4"), + Some("20.4.".to_string()) + ); + assert_eq!( + game_version_to_neoforge_prefix("1.21.1"), + Some("21.1.".to_string()) + ); + assert_eq!( + game_version_to_neoforge_prefix("26.1.2"), + Some("26.1.2.".to_string()) + ); + assert_eq!(game_version_to_neoforge_prefix("invalid"), None); +} diff --git a/src/storage.rs b/src/storage.rs index 89bd264..983b349 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -175,50 +175,5 @@ fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn instance_paths_use_visible_directories() { - let paths = InstancePaths::new("/instances/example"); - assert_eq!( - paths.minecraft(), - PathBuf::from("/instances/example/minecraft") - ); - assert_eq!( - paths.content_manifest(), - PathBuf::from("/instances/example/rmcl/content/manifest.json") - ); - assert_eq!( - paths.local_config(), - PathBuf::from("/instances/example/rmcl/content/config") - ); - } - - #[test] - fn metadata_paths_separate_state_and_cache() { - let paths = MetadataPaths::new("/meta"); - assert_eq!(paths.profiles(), PathBuf::from("/meta/state/profiles")); - assert_eq!( - paths.provider_icons("modrinth"), - PathBuf::from("/meta/cache/providers/modrinth/icons") - ); - assert_eq!( - paths.versions(), - PathBuf::from("/meta/cache/minecraft/versions") - ); - assert_eq!( - paths.migration_journal(), - PathBuf::from("/meta/state/migration.json") - ); - } - - #[test] - fn atomic_write_replaces_existing_file() { - let temp = tempfile::tempdir().unwrap(); - let path = temp.path().join("state.json"); - std::fs::write(&path, b"old").unwrap(); - write_atomic(&path, b"new").unwrap(); - assert_eq!(std::fs::read(path).unwrap(), b"new"); - } -} +#[path = "tests/storage.rs"] +mod tests; diff --git a/src/tests/layout_migration.rs b/src/tests/layout_migration.rs new file mode 100644 index 0000000..4e097b0 --- /dev/null +++ b/src/tests/layout_migration.rs @@ -0,0 +1,209 @@ +use super::*; + +#[test] +fn migration_backs_up_and_renames_instance_directories() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + let config = temp.path().join("config.toml"); + let instance = instances.join("Example"); + fs::create_dir_all(instance.join(".minecraft/saves/world")).unwrap(); + fs::create_dir_all(instance.join(".rmcl/config-sync/local-config/config")).unwrap(); + fs::write(instance.join(".minecraft/saves/world/level.dat"), b"world").unwrap(); + fs::write( + instance.join(".rmcl/config-sync/local-config/options.txt"), + b"options", + ) + .unwrap(); + fs::write(&config, b"[paths]").unwrap(); + fs::create_dir_all(meta.join("config-sync/profiles/main")).unwrap(); + fs::write( + meta.join("config-sync/profiles/main/options.txt"), + b"profile", + ) + .unwrap(); + + let mut progress = Vec::new(); + let backup = run(&instances, &meta, &config, |update| progress.push(update)).unwrap(); + + assert_eq!( + fs::read(instance.join("minecraft/saves/world/level.dat")).unwrap(), + b"world" + ); + assert_eq!( + fs::read(instance.join("rmcl/content/config/options.txt")).unwrap(), + b"options" + ); + assert!(backup.join("instances/Example/.minecraft").exists()); + assert!(backup.join("profiles/legacy/main/options.txt").exists()); + assert!( + backup + .file_name() + .unwrap() + .to_string_lossy() + .starts_with("backup-") + ); + assert!(!meta.join("config-sync").exists()); + assert!(progress.iter().any(|update| { + update.item_total.is_some_and(|total| total > 0) + && update.item_current.is_some_and(|current| current > 0) + })); + assert_eq!( + marker_version(&MetadataPaths::new(&meta).layout_marker()), + Some(LAYOUT_VERSION) + ); + assert!(cache_rebuild_pending(&meta)); + assert_eq!(run(&instances, &meta, &config, |_| {}).unwrap(), backup); + finish_cache_rebuild(&meta).unwrap(); + assert!(!cache_rebuild_pending(&meta)); +} + +#[test] +fn migration_resumes_from_the_recorded_journal() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + let config = temp.path().join("config.toml"); + let done = instances.join("Done"); + let pending = instances.join("Pending"); + fs::create_dir_all(done.join("minecraft")).unwrap(); + fs::create_dir_all(pending.join(".minecraft/saves")).unwrap(); + + let metadata = MetadataPaths::new(&meta); + fs::create_dir_all(metadata.state()).unwrap(); + fs::create_dir_all(metadata.backups()).unwrap(); + let backup = metadata.backups().join("backup-resume"); + fs::create_dir_all(&backup).unwrap(); + write_json_atomic( + &metadata.migration_journal(), + &MigrationJournal { + version: LAYOUT_VERSION, + backup_dir: backup.clone(), + completed: vec!["backup".to_owned(), "instance:Done".to_owned()], + }, + ) + .unwrap(); + + assert_eq!(run(&instances, &meta, &config, |_| {}).unwrap(), backup); + assert!(done.join("minecraft").exists()); + assert!(pending.join("minecraft/saves").exists()); + assert!(!metadata.migration_journal().exists()); +} + +#[test] +fn stale_partial_backup_is_replaced() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let backup = temp.path().join("backups/backup-test"); + let partial = backup.with_extension("partial"); + fs::create_dir_all(instances.join("Example")).unwrap(); + fs::write(instances.join("Example/data.txt"), b"current").unwrap(); + fs::create_dir_all(&partial).unwrap(); + fs::write(partial.join("stale.txt"), b"stale").unwrap(); + + backup_user_data( + &instances, + &temp.path().join("missing-config.toml"), + &temp.path().join("meta"), + &backup, + |_, _, _| {}, + ) + .unwrap(); + + assert_eq!( + fs::read(backup.join("instances/Example/data.txt")).unwrap(), + b"current" + ); + assert!(!backup.join("stale.txt").exists()); + assert!(!partial.exists()); +} + +#[test] +fn backup_rejects_overlap_and_insufficient_space() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + fs::create_dir_all(&instances).unwrap(); + + let overlap = + validate_backup_destination(&instances, &instances.join("backup"), 0).unwrap_err(); + assert!(matches!(overlap, MigrationError::BackupOverlap(_))); + + let outside = temp.path().join("backups/backup"); + let insufficient = validate_backup_destination(&instances, &outside, u64::MAX).unwrap_err(); + assert!(matches!( + insufficient, + MigrationError::InsufficientSpace { .. } + )); +} + +#[test] +fn migration_need_follows_legacy_data_marker_and_pending_rebuild() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + fs::create_dir_all(instances.join("Example/.minecraft")).unwrap(); + + assert!(is_needed(&instances, &meta)); + initialize_new_layout(&meta).unwrap(); + assert!(!is_needed(&instances, &meta)); + fs::write(MetadataPaths::new(&meta).layout_marker(), b"invalid marker").unwrap(); + assert!(is_needed(&instances, &meta)); + initialize_new_layout(&meta).unwrap(); + fs::write( + MetadataPaths::new(&meta).cache_rebuild_pending(), + LAYOUT_VERSION.to_string(), + ) + .unwrap(); + assert!(is_needed(&instances, &meta)); +} + +#[cfg(unix)] +#[test] +fn backup_preserves_symlinks() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("source"); + let destination = temp.path().join("destination"); + fs::create_dir_all(&source).unwrap(); + fs::write(source.join("target.txt"), b"target").unwrap(); + std::os::unix::fs::symlink("target.txt", source.join("link.txt")).unwrap(); + + copy_dir_recursive_with_progress(&source, &destination, &mut |_, _| {}).unwrap(); + + assert_eq!( + fs::read_link(destination.join("link.txt")).unwrap(), + PathBuf::from("target.txt") + ); +} + +#[test] +fn conflicting_visible_and_hidden_directories_are_not_merged() { + let temp = tempfile::tempdir().unwrap(); + let instance = temp.path().join("Example"); + fs::create_dir_all(instance.join(".minecraft")).unwrap(); + fs::create_dir_all(instance.join("minecraft")).unwrap(); + let error = migrate_instance(&instance, "Example").unwrap_err(); + assert!(matches!(error, MigrationError::PathConflict { .. })); +} + +#[test] +fn merge_conflicts_do_not_overwrite_existing_profiles() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("legacy"); + let destination = temp.path().join("current"); + fs::create_dir_all(source.join("nested")).unwrap(); + fs::create_dir_all(destination.join("nested")).unwrap(); + fs::write(source.join("nested/options.txt"), b"legacy").unwrap(); + fs::write(destination.join("nested/options.txt"), b"current").unwrap(); + + let error = move_or_merge(&source, &destination).unwrap_err(); + + assert!(matches!(error, MigrationError::MergeConflict { .. })); + assert_eq!( + fs::read(destination.join("nested/options.txt")).unwrap(), + b"current" + ); + assert_eq!( + fs::read(source.join("nested/options.txt")).unwrap(), + b"legacy" + ); +} diff --git a/src/tests/migrate.rs b/src/tests/migrate.rs new file mode 100644 index 0000000..ffce813 --- /dev/null +++ b/src/tests/migrate.rs @@ -0,0 +1,122 @@ +use super::*; + +#[test] +fn rename_top_level_moves_when_only_old_exists() { + let tmp = tempfile::tempdir().unwrap(); + let old = tmp.path().join("mcl"); + let new = tmp.path().join("rmcl"); + fs::create_dir_all(old.join("sub")).unwrap(); + fs::write(old.join("sub").join("f.txt"), b"hi").unwrap(); + + rename_top_level(&old, &new); + + assert!(!old.exists()); + assert!(new.exists()); + assert_eq!(fs::read(new.join("sub").join("f.txt")).unwrap(), b"hi"); +} + +#[test] +fn rename_top_level_skips_when_only_new_exists() { + let tmp = tempfile::tempdir().unwrap(); + let old = tmp.path().join("mcl"); + let new = tmp.path().join("rmcl"); + fs::create_dir_all(&new).unwrap(); + fs::write(new.join("marker.txt"), b"keep").unwrap(); + + rename_top_level(&old, &new); + + assert!(!old.exists()); + assert_eq!(fs::read(new.join("marker.txt")).unwrap(), b"keep"); +} + +#[test] +fn rename_top_level_skips_when_both_exist() { + let tmp = tempfile::tempdir().unwrap(); + let old = tmp.path().join("mcl"); + let new = tmp.path().join("rmcl"); + fs::create_dir_all(&old).unwrap(); + fs::create_dir_all(&new).unwrap(); + fs::write(old.join("a"), b"old").unwrap(); + fs::write(new.join("b"), b"new").unwrap(); + + rename_top_level(&old, &new); + + assert!(old.exists(), "old should remain when both exist"); + assert!(new.exists(), "new should remain when both exist"); + assert_eq!(fs::read(old.join("a")).unwrap(), b"old"); + assert_eq!(fs::read(new.join("b")).unwrap(), b"new"); +} + +#[test] +fn rename_top_level_noop_when_neither_exists() { + let tmp = tempfile::tempdir().unwrap(); + let old = tmp.path().join("mcl"); + let new = tmp.path().join("rmcl"); + + rename_top_level(&old, &new); + + assert!(!old.exists()); + assert!(!new.exists()); +} + +#[test] +fn cleanup_instance_leftovers_removes_shim_and_log4j() { + let tmp = tempfile::tempdir().unwrap(); + let instances = tmp.path().join("instances"); + let mc = instances + .join("Test") + .join(crate::storage::MINECRAFT_DIR_NAME); + fs::create_dir_all(&mc).unwrap(); + fs::write(mc.join(".mcl-shim.jar"), b"jar").unwrap(); + fs::write(mc.join(".mcl-log4j2.xml"), b"xml").unwrap(); + fs::write(mc.join("keep.txt"), b"keep").unwrap(); + + cleanup_instance_leftovers(&instances); + + assert!(!mc.join(".mcl-shim.jar").exists()); + assert!(!mc.join(".mcl-log4j2.xml").exists()); + assert!(mc.join("keep.txt").exists()); +} + +#[test] +#[cfg(target_os = "linux")] +fn rewrite_linux_desktop_entries_renames_and_rewrites_exec() { + let tmp = tempfile::tempdir().unwrap(); + let data = tmp.path(); + let instances = data.join("rmcl").join("instances"); + let apps = data.join("applications"); + fs::create_dir_all(instances.join("MyPack")).unwrap(); + fs::create_dir_all(&apps).unwrap(); + let old_entry = apps.join("mcl-MyPack.desktop"); + fs::write( + &old_entry, + "[Desktop Entry]\nName=Test\nExec=mcl instance launch \"MyPack\"\n", + ) + .unwrap(); + + rewrite_linux_desktop_entries(data, &instances); + + let new_entry = apps.join("rmcl-MyPack.desktop"); + assert!(!old_entry.exists(), "old .desktop should be removed"); + assert!(new_entry.exists(), "new .desktop should exist"); + let content = fs::read_to_string(&new_entry).unwrap(); + assert!(content.contains("Exec=rmcl instance launch \"MyPack\"")); +} + +#[test] +fn copy_dir_recursive_copies_nested_tree() { + let tmp = tempfile::tempdir().unwrap(); + let src = tmp.path().join("a"); + let dst = tmp.path().join("b"); + fs::create_dir_all(src.join("nested")).unwrap(); + fs::write(src.join("top.txt"), b"top").unwrap(); + fs::write(src.join("nested").join("inner.txt"), b"inner").unwrap(); + + copy_dir_recursive(&src, &dst).unwrap(); + + assert_eq!(fs::read(dst.join("top.txt")).unwrap(), b"top"); + assert_eq!( + fs::read(dst.join("nested").join("inner.txt")).unwrap(), + b"inner" + ); +} diff --git a/src/tests/mod.rs b/src/tests/mod.rs new file mode 100644 index 0000000..4250d35 --- /dev/null +++ b/src/tests/mod.rs @@ -0,0 +1,3 @@ +use std::sync::Mutex; + +pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(()); diff --git a/src/tests/storage.rs b/src/tests/storage.rs new file mode 100644 index 0000000..8f02ab0 --- /dev/null +++ b/src/tests/storage.rs @@ -0,0 +1,45 @@ +use super::*; + +#[test] +fn instance_paths_use_visible_directories() { + let paths = InstancePaths::new("/instances/example"); + assert_eq!( + paths.minecraft(), + PathBuf::from("/instances/example/minecraft") + ); + assert_eq!( + paths.content_manifest(), + PathBuf::from("/instances/example/rmcl/content/manifest.json") + ); + assert_eq!( + paths.local_config(), + PathBuf::from("/instances/example/rmcl/content/config") + ); +} + +#[test] +fn metadata_paths_separate_state_and_cache() { + let paths = MetadataPaths::new("/meta"); + assert_eq!(paths.profiles(), PathBuf::from("/meta/state/profiles")); + assert_eq!( + paths.provider_icons("modrinth"), + PathBuf::from("/meta/cache/providers/modrinth/icons") + ); + assert_eq!( + paths.versions(), + PathBuf::from("/meta/cache/minecraft/versions") + ); + assert_eq!( + paths.migration_journal(), + PathBuf::from("/meta/state/migration.json") + ); +} + +#[test] +fn atomic_write_replaces_existing_file() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("state.json"); + std::fs::write(&path, b"old").unwrap(); + write_atomic(&path, b"new").unwrap(); + assert_eq!(std::fs::read(path).unwrap(), b"new"); +} diff --git a/src/tui/event.rs b/src/tui/event.rs index f33ac6c..aed6086 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -6,9 +6,9 @@ use std::time::Duration; use super::Tui; use super::app::{App, PENDING_INSTANCES}; use super::widgets::{self, popups::import_modpack, popups::new_instance}; +use crate::feedback::errors as error_buffer; +use crate::feedback::progress; use crate::instance::InstanceManager; -use crate::tui::error_buffer; -use crate::tui::progress; impl App { /// main loop: poll async results and input at ~60Hz, drawing only when state changes @@ -17,7 +17,7 @@ impl App { .checked_sub(Duration::from_secs(1)) .unwrap_or_else(std::time::Instant::now); while !self.exit { - let redraw_requested = super::take_redraw_request(); + let redraw_requested = crate::feedback::take_redraw_request(); // check if any popup wizard finished and wants to create/import if let Some(params) = new_instance::take_result() { self.spawn_create(params); @@ -86,7 +86,7 @@ impl App { self.ensure_provider_conflict_popup(); self.ensure_active_discovery_loaded(); let progress_active = progress::is_active(); - let spinner_active = progress_active || crate::running::has_active(); + let spinner_active = progress_active || crate::instance::runtime::has_active(); if spinner_active { // only advance the spinner every 8 ticks to keep it readable self.throbber_tick = self.throbber_tick.wrapping_add(1); @@ -366,7 +366,7 @@ impl App { Ok(config) => { if let Ok(mut pending) = pending_instances.lock() { pending.push(config); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } Err(e) => { @@ -393,11 +393,11 @@ impl App { Ok(config) => { if let Ok(mut pending) = pending_instances.lock() { pending.push(config); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } Err(e) => { - crate::tui::progress::clear(); + crate::feedback::progress::clear(); error_buffer::push_error(error_buffer::ErrorEvent { id: 0, level: tracing::Level::ERROR, @@ -496,7 +496,7 @@ impl App { pub(super) fn spawn_launch(&self, instance: crate::instance::InstanceConfig) { use crate::instance::launch; - use crate::running; + use crate::instance::runtime; let instance = match self.instance_manager.load_one(&instance.name) { Ok(config) => config, @@ -511,7 +511,7 @@ impl App { } }; - running::set_state(&instance.name, running::RunState::Authenticating); + runtime::set_state(&instance.name, runtime::RunState::Authenticating); let instances_dir = self.instance_manager.instances_dir.clone(); let meta_dir = self.instance_manager.meta_dir.clone(); @@ -519,7 +519,7 @@ impl App { tokio::spawn(async move { if let Err(e) = launch::launch(&instance, &instances_dir, &meta_dir).await { tracing::error!("Failed to launch '{}': {}", instance.name, e); - running::remove(&instance.name); + runtime::remove(&instance.name); } }); } @@ -550,7 +550,7 @@ impl App { } fn drain_pending_last_played(&mut self) { - for (name, time) in crate::running::drain_last_played() { + for (name, time) in crate::instance::runtime::drain_last_played() { for inst in &mut self.instances_state.instances { if inst.name == name { inst.last_played = Some(time); diff --git a/src/tui/input.rs b/src/tui/input.rs index 5b84bb5..231e70b 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -11,7 +11,7 @@ use super::app::{App, FocusedArea}; use super::widgets::{ self, WidgetKey, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance, }; -use crate::tui::error_buffer; +use crate::feedback::errors as error_buffer; impl App { pub(super) fn handle_mouse_event(&mut self, event: MouseEvent) { @@ -582,12 +582,12 @@ impl App { { if let Some(instance) = self.instances_state.selected_instance().cloned() { let can_launch = matches!( - crate::running::get(&instance.name), - None | Some(crate::running::RunState::Crashed(_)) + crate::instance::runtime::get(&instance.name), + None | Some(crate::instance::runtime::RunState::Crashed(_)) ); if can_launch { - crate::running::remove(&instance.name); - crate::instance_logs::clear(&instance.name); + crate::instance::runtime::remove(&instance.name); + crate::instance::logs::live::clear(&instance.name); self.spawn_launch(instance); } } @@ -606,7 +606,7 @@ impl App { && !self.instances_state.search.active => { if let Some(instance) = self.instances_state.selected_instance() { - crate::running::send_kill(&instance.name); + crate::instance::runtime::send_kill(&instance.name); } } _ => {} @@ -689,8 +689,9 @@ impl App { instance.loader.to_string().to_lowercase() )); tokio::spawn(async move { - let registry = - crate::content_provider::ProviderRegistry::modrinth(crate::net::HttpClient::new()); + let registry = crate::instance::content::provider::ProviderRegistry::modrinth( + crate::net::HttpClient::new(), + ); let result = match registry.preferred("modrinth") { Some(provider) => match provider .compatible_versions( @@ -741,7 +742,7 @@ impl App { let project = match request.cached_project { Some(project) => project, None => { - let progress = crate::tui::progress::ProgressTask::start(format!( + let progress = crate::feedback::progress::ProgressTask::start(format!( "Loading {} from Modrinth", request.project_title )); @@ -783,7 +784,7 @@ impl App { } image_urls.sort(); image_urls.dedup(); - let progress = crate::tui::progress::ProgressTask::start(format!( + let progress = crate::feedback::progress::ProgressTask::start(format!( "Loading images for {}", project.title )); @@ -868,14 +869,15 @@ impl App { } else { format!("Installing {}", request.project_title) }; - let progress = crate::tui::progress::ProgressTask::start(action); + let progress = crate::feedback::progress::ProgressTask::start(action); progress.set_sub_action(&request.version.version_number); let client = crate::net::HttpClient::new(); let result = async { tokio::fs::create_dir_all(&destination) .await .map_err(crate::net::NetError::from)?; - let registry = crate::content_provider::ProviderRegistry::modrinth(client); + let registry = + crate::instance::content::provider::ProviderRegistry::modrinth(client); let provider = registry.preferred("modrinth").ok_or_else(|| { crate::net::NetError::Parse( "Modrinth content provider is unavailable".to_owned(), @@ -1053,7 +1055,8 @@ impl App { tokio::spawn(async move { let client = crate::net::HttpClient::new(); - let registry = crate::content_provider::ProviderRegistry::modrinth(client.clone()); + let registry = + crate::instance::content::provider::ProviderRegistry::modrinth(client.clone()); let result = match registry.preferred("modrinth") { Some(provider) => { provider @@ -1109,9 +1112,9 @@ impl App { let Ok(_permit) = icon_slots.acquire_owned().await else { return; }; - let progress = crate::tui::progress::ProgressTask::start(format!( - "Downloading icon for {file_stem}" - )); + let progress = crate::feedback::progress::ProgressTask::start( + format!("Downloading icon for {file_stem}"), + ); match client.get_bytes(&url).await { Ok(bytes) if !bytes.is_empty() => { if let Some(parent) = cached_icon.parent() { diff --git a/src/tui/logging.rs b/src/tui/logging.rs index 9f145ea..02d806b 100644 --- a/src/tui/logging.rs +++ b/src/tui/logging.rs @@ -16,7 +16,7 @@ use tracing_subscriber::{EnvFilter, Layer}; use std::sync::LazyLock; -use crate::tui::error_buffer::{self, ErrorEvent}; +use crate::feedback::errors::{self as error_buffer, ErrorEvent}; const MINECRAFT_LOG_TARGET: &str = "mc_instance"; const DEFAULT_FILE_FILTER: &str = "warn,rmcl=trace"; diff --git a/src/tui/mod.rs b/src/tui/mod.rs index b84e694..a8000fc 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -1,29 +1,19 @@ // tui entrypoint: sets up the terminal, runs the app, cleans up on exit. pub mod app; -pub mod error_buffer; mod event; mod input; pub mod logging; -pub mod progress; mod render; pub mod widgets; +pub use crate::feedback::errors as error_buffer; +pub use crate::feedback::progress; +pub use crate::feedback::request_redraw; + #[cfg(test)] pub(crate) mod tests; -use std::sync::atomic::{AtomicBool, Ordering}; - -static REDRAW_REQUESTED: AtomicBool = AtomicBool::new(true); - -pub fn request_redraw() { - REDRAW_REQUESTED.store(true, Ordering::Release); -} - -pub(super) fn take_redraw_request() -> bool { - REDRAW_REQUESTED.swap(false, Ordering::AcqRel) -} - pub type Tui = ratatui::DefaultTerminal; pub async fn show() -> color_eyre::Result<()> { @@ -234,7 +224,7 @@ async fn rebuild_runtime_cache_screen( }); while !task.is_finished() { - let progress = crate::tui::progress::PROGRESS + let progress = crate::feedback::progress::PROGRESS .lock() .ok() .map(|progress| progress.clone()) diff --git a/src/tui/render.rs b/src/tui/render.rs index 45d634d..d458f60 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -13,7 +13,7 @@ use super::app::{App, ErrorEffectState, FocusedArea}; use super::widgets::{ self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance, }; -use crate::tui::error_buffer; +use crate::feedback::errors as error_buffer; use crate::tui::widgets::popups::confirm::{ConfirmPopup, confirm_popup_area}; use crate::tui::widgets::popups::error::{ErrorPopup, popup_area}; diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index a806078..9a3057c 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -3,9 +3,9 @@ use std::collections::{HashMap, HashSet}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind}; use ratatui::{Terminal, backend::TestBackend}; -use super::UI_TEST_LOCK; use crate::auth::{Account, AccountStore, AccountType}; use crate::instance::{InstanceConfig, InstanceManager, ModLoader}; +use crate::tests::TEST_LOCK; use crate::tui::{ app::{App, FocusedArea}, widgets, @@ -21,17 +21,15 @@ pub(in crate::tui) struct UiHarness { impl UiHarness { pub fn new() -> Self { - let guard = UI_TEST_LOCK - .lock() - .unwrap_or_else(|error| error.into_inner()); + let guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); widgets::popups::confirm::clear_pending(); widgets::popups::new_instance::reset_for_test(); widgets::popups::import_modpack::reset_for_test(); - crate::tui::error_buffer::ERROR_EVENTS + crate::feedback::errors::ERROR_EVENTS .lock() .expect("error buffer") .clear(); - crate::tui::progress::clear(); + crate::feedback::progress::clear(); let temp = tempfile::tempdir().expect("temporary UI data"); let instances_dir = temp.path().join("instances"); diff --git a/src/tui/tests/mod.rs b/src/tui/tests/mod.rs index 079a715..9f53416 100644 --- a/src/tui/tests/mod.rs +++ b/src/tui/tests/mod.rs @@ -1,7 +1,3 @@ mod flows; pub(super) mod harness; mod snapshots; - -use std::sync::Mutex; - -pub(crate) static UI_TEST_LOCK: Mutex<()> = Mutex::new(()); diff --git a/src/tui/tests/snapshots.rs b/src/tui/tests/snapshots.rs index 1a8fd12..0445012 100644 --- a/src/tui/tests/snapshots.rs +++ b/src/tui/tests/snapshots.rs @@ -13,16 +13,16 @@ fn empty_app_renders_the_complete_frame() { #[test] fn active_progress_is_visible_in_the_complete_frame() { let mut ui = UiHarness::new(); - crate::tui::progress::set_action("Downloading test data"); - crate::tui::progress::set_sub_action("one.jar"); - crate::tui::progress::set_progress(1, 2); + crate::feedback::progress::set_action("Downloading test data"); + crate::feedback::progress::set_sub_action("one.jar"); + crate::feedback::progress::set_progress(1, 2); ui.draw(); let screen = ui.screen(); assert!(screen.contains("Downloading test data")); assert!(screen.contains("one.jar")); - crate::tui::progress::clear(); + crate::feedback::progress::clear(); } #[test] diff --git a/src/tui/tests/widgets/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index 9c35fab..95dbc96 100644 --- a/src/tui/tests/widgets/content/discovery.rs +++ b/src/tui/tests/widgets/content/discovery.rs @@ -1,5 +1,5 @@ use super::*; -use crate::tui::tests::UI_TEST_LOCK; +use crate::tests::TEST_LOCK; use chrono::Utc; use crossterm::event::KeyModifiers; @@ -283,9 +283,7 @@ fn discovery_delete_only_clears_the_matching_installed_badge() { #[test] fn successful_install_marks_the_project_and_closes_the_popup() { - let _guard = UI_TEST_LOCK - .lock() - .unwrap_or_else(|error| error.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); let project = DiscoveryProject { id: "project".to_owned(), slug: "project".to_owned(), diff --git a/src/tui/tests/widgets/markdown.rs b/src/tui/tests/widgets/markdown.rs index 114d248..53d0077 100644 --- a/src/tui/tests/widgets/markdown.rs +++ b/src/tui/tests/widgets/markdown.rs @@ -1,5 +1,9 @@ use ratatui::{Terminal, backend::TestBackend}; +fn formatted_text(source: &str, width: u16) -> ratatui::text::Text<'static> { + super::external_markdown_text(source, width).0 +} + #[test] fn html_images_are_extracted_and_raw_html_is_removed() { let document = super::Document::new( @@ -89,7 +93,7 @@ fn inserted_html_keeps_its_content_and_hides_tag_shells() { _ => None, }) .unwrap(); - let text = super::formatted_text(source, 80); + let text = formatted_text(source, 80); let rendered = text .lines .iter() @@ -123,7 +127,7 @@ fn nested_inline_html_uses_dom_conversion_for_links_and_emphasis() { assert!(source.contains("[**Supported**](https://example.com)")); assert!(!source.contains('<')); - let text = super::formatted_text(source, 80); + let text = formatted_text(source, 80); let supported = text .lines .iter() @@ -162,7 +166,7 @@ fn markdown_images_inside_links_do_not_leave_the_link_destination() { #[test] fn visible_link_text_does_not_include_the_destination() { - let text = super::formatted_text("[buying me a coffee](https://example.com/donate)", 80); + let text = formatted_text("[buying me a coffee](https://example.com/donate)", 80); let rendered = text .lines .iter() @@ -227,7 +231,7 @@ fn only_explicitly_centered_project_images_are_centered() { #[test] fn headings_hide_markers_and_rules_use_terminal_lines() { - let text = super::formatted_text("## Known Issues\n\n---", 12); + let text = formatted_text("## Known Issues\n\n---", 12); let rendered = text .lines .iter() @@ -246,7 +250,7 @@ fn headings_hide_markers_and_rules_use_terminal_lines() { #[test] fn all_heading_levels_are_bold() { - let text = super::formatted_text("### Performance", 20); + let text = formatted_text("### Performance", 20); let heading = text .lines .iter() @@ -301,7 +305,7 @@ fn unrelated_and_later_headings_are_kept() { #[test] fn lists_use_terminal_bullets() { - let text = super::formatted_text("- first\n - nested\n- second", 20); + let text = formatted_text("- first\n - nested\n- second", 20); let rendered = text .lines .iter() @@ -317,7 +321,7 @@ fn lists_use_terminal_bullets() { #[test] fn wrapped_list_items_keep_a_hanging_indent() { - let text = super::formatted_text("- one two three four", 16); + let text = formatted_text("- one two three four", 16); let rendered = text .lines .iter() @@ -347,7 +351,7 @@ fn markdown_headings_with_inline_html_are_converted_as_one_block() { }) .unwrap(); assert!(!source.contains('<'), "{source}"); - let rendered = super::formatted_text(source, 80) + let rendered = formatted_text(source, 80) .lines .iter() .flat_map(|line| &line.spans) @@ -388,7 +392,7 @@ fn emphasis_survives_html_list_conversion_without_literal_markers() { _ => None, }) .unwrap(); - let text = super::formatted_text(source, 80); + let text = formatted_text(source, 80); let rendered = text .lines .iter() @@ -419,7 +423,7 @@ fn emphasis_next_to_html_tag_boundaries_does_not_leak_markers() { _ => None, }) .unwrap(); - let rendered = super::formatted_text(source, 100) + let rendered = formatted_text(source, 100) .lines .iter() .flat_map(|line| &line.spans) @@ -430,7 +434,7 @@ fn emphasis_next_to_html_tag_boundaries_does_not_leak_markers() { #[test] fn fenced_code_blocks_are_rendered_without_fences() { - let text = super::formatted_text("```json5\n{\n \"enabled\": true\n}\n```", 24); + let text = formatted_text("```json5\n{\n \"enabled\": true\n}\n```", 24); let rendered = text .lines .iter() @@ -462,7 +466,7 @@ fn fenced_code_blocks_are_rendered_without_fences() { #[test] fn tables_wrap_cells_without_breaking_the_columns() { - let text = super::formatted_text( + let text = formatted_text( "| Mod | Status | Note |\n| --- | --- | --- |\n| Player Animator | Supported | This means mods that use it like Better Combat and Emotecraft |", 48, ); diff --git a/src/tui/tests/widgets/popups/error/render.rs b/src/tui/tests/widgets/popups/error/render.rs index 9ba6499..1abc40b 100644 --- a/src/tui/tests/widgets/popups/error/render.rs +++ b/src/tui/tests/widgets/popups/error/render.rs @@ -4,7 +4,7 @@ use ratatui::backend::TestBackend; use std::time::Instant; use tracing::Level; -use crate::tui::error_buffer::ErrorEvent; +use crate::feedback::errors::ErrorEvent; fn render(event: ErrorEvent, width: u16, height: u16) -> Terminal { let backend = TestBackend::new(width, height); diff --git a/src/tui/tests/widgets/popups/import_modpack/render.rs b/src/tui/tests/widgets/popups/import_modpack/render.rs index 441d47a..024bf6f 100644 --- a/src/tui/tests/widgets/popups/import_modpack/render.rs +++ b/src/tui/tests/widgets/popups/import_modpack/render.rs @@ -1,5 +1,5 @@ use super::*; -use crate::tui::tests::UI_TEST_LOCK; +use crate::tests::TEST_LOCK; use ratatui::Terminal; use ratatui::backend::TestBackend; @@ -12,7 +12,7 @@ fn reset_import_state(step: ImportStep) { #[test] fn import_modpack_renders_input_step() { - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); reset_import_state(ImportStep::Input); let backend = TestBackend::new(60, 12); @@ -25,7 +25,7 @@ fn import_modpack_renders_input_step() { #[test] fn import_modpack_renders_fetching_step() { - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); reset_import_state(ImportStep::Fetching); let backend = TestBackend::new(60, 12); @@ -43,7 +43,7 @@ fn import_modpack_renders_fetching_step() { fn import_modpack_renders_version_step() { use crate::net::modrinth::VersionInfo; - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); { let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock"); *guard = ImportWizardState::default(); @@ -90,7 +90,7 @@ fn import_modpack_renders_confirm_step() { use crate::instance::models::ModLoader; use std::path::PathBuf; - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); { let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock"); *guard = ImportWizardState::default(); @@ -125,7 +125,7 @@ fn import_modpack_renders_confirm_step_without_loader_version() { use crate::instance::models::ModLoader; use std::path::PathBuf; - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); { let mut guard = IMPORT_STATE.lock().expect("IMPORT_STATE lock"); *guard = ImportWizardState::default(); diff --git a/src/tui/tests/widgets/popups/import_modpack/state.rs b/src/tui/tests/widgets/popups/import_modpack/state.rs index f52732d..fc78e40 100644 --- a/src/tui/tests/widgets/popups/import_modpack/state.rs +++ b/src/tui/tests/widgets/popups/import_modpack/state.rs @@ -7,7 +7,7 @@ use crate::instance::{ ModLoader, import::{ImportSummary, PackFormat}, }; -use crate::tui::tests::UI_TEST_LOCK; +use crate::tests::TEST_LOCK; fn key(code: KeyCode) -> KeyEvent { KeyEvent::new(code, KeyModifiers::NONE) @@ -29,9 +29,7 @@ fn summary() -> ImportSummary { #[test] fn empty_input_is_ignored_and_escape_closes_the_popup() { - let _guard = UI_TEST_LOCK - .lock() - .unwrap_or_else(|error| error.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); let mut instances = instances::State { show_import_popup: true, ..instances::State::default() @@ -47,9 +45,7 @@ fn empty_input_is_ignored_and_escape_closes_the_popup() { #[test] fn confirm_returns_the_import_summary() { - let _guard = UI_TEST_LOCK - .lock() - .unwrap_or_else(|error| error.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); let mut instances = instances::State { show_import_popup: true, ..instances::State::default() diff --git a/src/tui/tests/widgets/popups/import_modpack/support.rs b/src/tui/tests/widgets/popups/import_modpack/support.rs new file mode 100644 index 0000000..847a01a --- /dev/null +++ b/src/tui/tests/widgets/popups/import_modpack/support.rs @@ -0,0 +1,9 @@ +use super::state; + +pub(crate) fn reset() { + state::IMPORT_STATE + .lock() + .expect("import wizard state") + .reset(); + *state::IMPORT_RESULT.lock().expect("import wizard result") = None; +} diff --git a/src/tui/tests/widgets/popups/new_instance/render.rs b/src/tui/tests/widgets/popups/new_instance/render.rs index 0d32eac..a766ab4 100644 --- a/src/tui/tests/widgets/popups/new_instance/render.rs +++ b/src/tui/tests/widgets/popups/new_instance/render.rs @@ -1,5 +1,5 @@ use super::*; -use crate::tui::tests::UI_TEST_LOCK; +use crate::tests::TEST_LOCK; use ratatui::Terminal; use ratatui::backend::TestBackend; @@ -15,7 +15,7 @@ fn reset_wizard_state(step: WizardStep) { #[test] fn new_instance_renders_name_step() { - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); // Name is the default step; render touches no network helpers. reset_wizard_state(WizardStep::Name); @@ -29,7 +29,7 @@ fn new_instance_renders_name_step() { #[test] fn new_instance_renders_loader_step() { - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); // Loader step is reached after Name; render just paints the hardcoded // loader list, no network. reset_wizard_state(WizardStep::Loader); @@ -50,7 +50,7 @@ fn new_instance_renders_loader_step() { fn new_instance_renders_version_step() { use crate::instance::loader::GameVersion; - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); { let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock"); *guard = WizardState::default(); @@ -86,7 +86,7 @@ fn new_instance_renders_version_step() { fn new_instance_renders_loader_version_step() { use crate::instance::loader::GameVersion; - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); { let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock"); *guard = WizardState::default(); @@ -115,7 +115,7 @@ fn new_instance_renders_confirm_step() { use crate::instance::loader::GameVersion; use tui_prompts::TextState; - let _serial = UI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); { let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock"); *guard = WizardState::default(); diff --git a/src/tui/tests/widgets/popups/new_instance/state.rs b/src/tui/tests/widgets/popups/new_instance/state.rs index dfb73e0..572b214 100644 --- a/src/tui/tests/widgets/popups/new_instance/state.rs +++ b/src/tui/tests/widgets/popups/new_instance/state.rs @@ -2,7 +2,7 @@ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use tui_prompts::TextState; use super::*; -use crate::tui::tests::UI_TEST_LOCK; +use crate::tests::TEST_LOCK; fn key(code: KeyCode) -> KeyEvent { KeyEvent::new(code, KeyModifiers::NONE) @@ -10,9 +10,7 @@ fn key(code: KeyCode) -> KeyEvent { #[test] fn vanilla_wizard_reaches_confirm_and_returns_parameters() { - let _guard = UI_TEST_LOCK - .lock() - .unwrap_or_else(|error| error.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); let mut instances = instances::State { show_popup: true, ..instances::State::default() diff --git a/src/tui/tests/widgets/popups/new_instance/support.rs b/src/tui/tests/widgets/popups/new_instance/support.rs new file mode 100644 index 0000000..caa25d1 --- /dev/null +++ b/src/tui/tests/widgets/popups/new_instance/support.rs @@ -0,0 +1,6 @@ +use super::state; + +pub(crate) fn reset() { + state::WIZARD_STATE.lock().expect("wizard state").reset(); + *state::WIZARD_RESULT.lock().expect("wizard result") = None; +} diff --git a/src/tui/widgets/content/discovery.rs b/src/tui/widgets/content/discovery.rs index 3647be7..719968e 100644 --- a/src/tui/widgets/content/discovery.rs +++ b/src/tui/widgets/content/discovery.rs @@ -420,7 +420,7 @@ impl DiscoveryState { } } if changed { - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } @@ -449,7 +449,7 @@ impl DiscoveryState { }; entry.installed_path = None; entry.title_suffix = None; - crate::tui::request_redraw(); + crate::feedback::request_redraw(); true } @@ -520,14 +520,14 @@ impl DiscoveryState { offset, result, }); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } pub fn push_action_result(pending: &PendingActions, result: DiscoveryActionResult) { if let Ok(mut pending) = pending.lock() { pending.push(result); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } @@ -689,24 +689,20 @@ impl DiscoveryState { } else { "installed" }; - crate::tui::error_buffer::push_error( - crate::tui::error_buffer::ErrorEvent { - id: request_id, - level: tracing::Level::INFO, - message: format!("{project_title}: {action}"), - pushed_at: std::time::Instant::now(), - }, - ); + crate::feedback::errors::push_error(crate::feedback::errors::ErrorEvent { + id: request_id, + level: tracing::Level::INFO, + message: format!("{project_title}: {action}"), + pushed_at: std::time::Instant::now(), + }); } Err(error) => { - crate::tui::error_buffer::push_error( - crate::tui::error_buffer::ErrorEvent { - id: request_id, - level: tracing::Level::ERROR, - message: format!("{project_title}: {error}"), - pushed_at: std::time::Instant::now(), - }, - ); + crate::feedback::errors::push_error(crate::feedback::errors::ErrorEvent { + id: request_id, + level: tracing::Level::ERROR, + message: format!("{project_title}: {error}"), + pushed_at: std::time::Instant::now(), + }); } }, } diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index bb86459..1cc4462 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -41,7 +41,7 @@ pub struct ContentStream { impl ContentStream { pub fn send(&self, entry: ContentEntry) -> bool { if self.sender.send(ContentStreamUpdate::Entry(entry)).is_ok() { - crate::tui::request_redraw(); + crate::feedback::request_redraw(); true } else { false @@ -58,7 +58,7 @@ impl ContentStream { }) .is_ok() { - crate::tui::request_redraw(); + crate::feedback::request_redraw(); true } else { false @@ -71,7 +71,7 @@ impl ContentStream { .send(ContentStreamUpdate::IconUnavailable { file_stem, path }) .is_ok() { - crate::tui::request_redraw(); + crate::feedback::request_redraw(); true } else { false @@ -80,7 +80,7 @@ impl ContentStream { pub fn upsert(&self, entry: ContentEntry) -> bool { if self.sender.send(ContentStreamUpdate::Upsert(entry)).is_ok() { - crate::tui::request_redraw(); + crate::feedback::request_redraw(); true } else { false @@ -93,7 +93,7 @@ impl ContentStream { .send(ContentStreamUpdate::Retain(file_stems)) .is_ok() { - crate::tui::request_redraw(); + crate::feedback::request_redraw(); true } else { false @@ -287,7 +287,7 @@ impl ContentListState { self.pending_entry_images.remove(&stem); } self.rebuild_display_metadata(); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } @@ -331,7 +331,7 @@ impl ContentListState { } if changed { self.images_dirty = true; - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } changed } @@ -375,7 +375,7 @@ impl ContentListState { bytes, description, }); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } } Ok(_) => {} @@ -559,7 +559,7 @@ impl ContentListState { && let Ok(mut pending) = pending.lock() { pending.push(result); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } }); } @@ -924,7 +924,7 @@ impl ContentListState { } else { *slot = Some(diff); } - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } let no_pending = pending_paths.lock().is_ok_and(|pending| pending.is_empty()); @@ -1260,7 +1260,7 @@ async fn load_provider_metadata( .ok() .filter(|bytes| !bytes.is_empty() && image::load_from_memory(bytes).is_ok()); - let registry = crate::content_provider::ProviderRegistry::modrinth(client.clone()); + let registry = crate::instance::content::provider::ProviderRegistry::modrinth(client.clone()); let provider = registry.preferred(provider_id).ok_or_else(|| { crate::net::NetError::Parse(format!("Content provider '{provider_id}' is unavailable")) })?; diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index 64ea773..41ed419 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -778,8 +778,8 @@ pub fn title( let [left_area, right_area] = Layout::horizontal([Constraint::Min(0), Constraint::Length(32)]).areas(inner); - use crate::running::RunState; - let run_state = crate::running::get(&inst.name); + use crate::instance::runtime::RunState; + let run_state = crate::instance::runtime::get(&inst.name); match run_state { Some(RunState::Authenticating) diff --git a/src/tui/widgets/instances.rs b/src/tui/widgets/instances.rs index baf75db..7aeaab1 100644 --- a/src/tui/widgets/instances.rs +++ b/src/tui/widgets/instances.rs @@ -14,7 +14,7 @@ use ratatui::{ use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; use crate::instance::models::InstanceConfig; -use crate::running::{RunState, get as get_run_state}; +use crate::instance::runtime::{RunState, get as get_run_state}; use crate::tui::app::FocusedArea; use super::{WidgetKey, search::SearchState, styled_title}; diff --git a/src/tui/widgets/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index dc744ed..04e9395 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -18,7 +18,7 @@ use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; use crate::config::theme::{BORDER_STYLE, THEME}; use crate::instance::launch::parser::LogLevel; -use crate::instance::log_files::{LogFileEntry, read_log_file, scan_log_files}; +use crate::instance::logs::files::{LogFileEntry, read_log_file, scan_log_files}; type PendingLogs = Arc)>>>; @@ -93,7 +93,7 @@ impl LogsState { if let Ok(mut slot) = pending.lock() { *slot = Some((tag, entries)); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } }); } @@ -140,11 +140,11 @@ impl LogsState { return; }; if !matches!( - crate::running::get(name), + crate::instance::runtime::get(name), Some( - crate::running::RunState::Authenticating - | crate::running::RunState::Starting - | crate::running::RunState::Running + crate::instance::runtime::RunState::Authenticating + | crate::instance::runtime::RunState::Starting + | crate::instance::runtime::RunState::Running ) ) { return; @@ -164,7 +164,7 @@ impl LogsState { if let Ok(mut slot) = pending.lock() { *slot = Some((tag, entries)); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } }); } @@ -174,10 +174,10 @@ impl LogsState { fn has_live(&self) -> bool { let name = self.loaded_for.as_deref().unwrap_or(""); matches!( - crate::running::get(name), - Some(crate::running::RunState::Running) - | Some(crate::running::RunState::Starting) - | Some(crate::running::RunState::Crashed(_)) + crate::instance::runtime::get(name), + Some(crate::instance::runtime::RunState::Running) + | Some(crate::instance::runtime::RunState::Starting) + | Some(crate::instance::runtime::RunState::Crashed(_)) ) } @@ -580,7 +580,7 @@ fn render_viewer( let all_lines: Vec = if is_live { let name = state.loaded_for.as_deref().unwrap_or(""); - crate::instance_logs::get_entries(name) + crate::instance::logs::live::get_entries(name) .into_iter() .map(|line| ViewerLine { text: line.text, diff --git a/src/tui/widgets/markdown.rs b/src/tui/widgets/markdown.rs index 42ced9a..d9574b9 100644 --- a/src/tui/widgets/markdown.rs +++ b/src/tui/widgets/markdown.rs @@ -569,11 +569,6 @@ fn push_text_block(blocks: &mut Vec, source: &str) { } } -#[cfg(test)] -fn formatted_text(source: &str, width: u16) -> Text<'static> { - external_markdown_text(source, width).0 -} - fn external_markdown_text(source: &str, width: u16) -> (Text<'static>, Vec) { let theme = markdown_theme(); let rule_style = theme.rule; @@ -1479,7 +1474,7 @@ fn prepare_image( if let Ok(mut pending) = pending.lock() { pending.push(PreparedImageResult { url, key, result }); } - crate::tui::request_redraw(); + crate::feedback::request_redraw(); }); } diff --git a/src/tui/widgets/popups/error.rs b/src/tui/widgets/popups/error.rs index dfccac4..b38e9c2 100644 --- a/src/tui/widgets/popups/error.rs +++ b/src/tui/widgets/popups/error.rs @@ -13,7 +13,7 @@ use tracing::Level; use super::base::PopupFrame; use crate::config::SETTINGS; use crate::config::theme::THEME; -use crate::tui::error_buffer::ErrorEvent; +use crate::feedback::errors::ErrorEvent; pub struct ErrorPopup { pub event: ErrorEvent, diff --git a/src/tui/widgets/popups/import_modpack/mod.rs b/src/tui/widgets/popups/import_modpack/mod.rs index 2f160fc..de53502 100644 --- a/src/tui/widgets/popups/import_modpack/mod.rs +++ b/src/tui/widgets/popups/import_modpack/mod.rs @@ -5,10 +5,7 @@ pub use render::{popup_rect, render}; pub use state::{ImportResult, ImportStep, ImportWizardState, handle_key, take_result}; #[cfg(test)] -pub(crate) fn reset_for_test() { - state::IMPORT_STATE - .lock() - .expect("import wizard state") - .reset(); - *state::IMPORT_RESULT.lock().expect("import wizard result") = None; -} +#[path = "../../../tests/widgets/popups/import_modpack/support.rs"] +mod test_support; +#[cfg(test)] +pub(crate) use test_support::reset as reset_for_test; diff --git a/src/tui/widgets/popups/import_modpack/state.rs b/src/tui/widgets/popups/import_modpack/state.rs index 05cbeb9..2527dca 100644 --- a/src/tui/widgets/popups/import_modpack/state.rs +++ b/src/tui/widgets/popups/import_modpack/state.rs @@ -407,7 +407,7 @@ fn close_popup(state: &mut ImportWizardState, instances_state: &mut instances::S } fn push_import_error(msg: String) { - crate::tui::error_buffer::push_error(crate::tui::error_buffer::ErrorEvent { + crate::feedback::errors::push_error(crate::feedback::errors::ErrorEvent { id: 0, level: Level::ERROR, message: msg, diff --git a/src/tui/widgets/popups/new_instance/mod.rs b/src/tui/widgets/popups/new_instance/mod.rs index 2bb5a56..a3ac1fa 100644 --- a/src/tui/widgets/popups/new_instance/mod.rs +++ b/src/tui/widgets/popups/new_instance/mod.rs @@ -7,7 +7,7 @@ pub use render::{popup_rect, render}; pub use state::{WizardParams, WizardState, WizardStep, handle_key, take_result}; #[cfg(test)] -pub(crate) fn reset_for_test() { - state::WIZARD_STATE.lock().expect("wizard state").reset(); - *state::WIZARD_RESULT.lock().expect("wizard result") = None; -} +#[path = "../../../tests/widgets/popups/new_instance/support.rs"] +mod test_support; +#[cfg(test)] +pub(crate) use test_support::reset as reset_for_test; diff --git a/src/tui/widgets/screenshots_grid.rs b/src/tui/widgets/screenshots_grid.rs index f0e1b26..3f5fe47 100644 --- a/src/tui/widgets/screenshots_grid.rs +++ b/src/tui/widgets/screenshots_grid.rs @@ -111,7 +111,7 @@ impl ScreenshotsState { if let Ok(mut slot) = pending.lock() { *slot = Some((tag, entries)); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } }); } @@ -169,7 +169,7 @@ impl ScreenshotsState { && let Ok(mut slot) = pending.lock() { slot.push((idx, img)); - crate::tui::request_redraw(); + crate::feedback::request_redraw(); } }); } diff --git a/src/tui/widgets/settings.rs b/src/tui/widgets/settings.rs index 20d956f..532cea6 100644 --- a/src/tui/widgets/settings.rs +++ b/src/tui/widgets/settings.rs @@ -158,7 +158,7 @@ fn effective_java_path(instance: &InstanceConfig) -> String { .java_path .clone() .or_else(|| SETTINGS.paths.effective_java_path().map(str::to_string)) - .unwrap_or_else(crate::net::detect_java_path) + .unwrap_or_else(crate::instance::java::detect_java_path) } fn java_version_label(java_path: &str) -> String { diff --git a/src/tui/widgets/status.rs b/src/tui/widgets/status.rs index b7f694b..50f9126 100644 --- a/src/tui/widgets/status.rs +++ b/src/tui/widgets/status.rs @@ -11,8 +11,8 @@ use ratatui::{ use throbber_widgets_tui::{Throbber, ThrobberState}; use crate::config::theme::{BORDER_STYLE, THEME}; +use crate::feedback::progress::PROGRESS; use crate::tui::app::FocusedArea; -use crate::tui::progress::PROGRESS; use super::styled_title;