From 0ec95e51e4435df28776ebc5c7c93de6f5133e2f Mon Sep 17 00:00:00 2001 From: objz Date: Sat, 7 Feb 2026 16:12:33 +0100 Subject: [PATCH] feat(cli): add instance, mod, pack, shader, account, and log commands --- src/cli/account.rs | 196 ++++++++++++++++++++++++++++ src/cli/content.rs | 147 +++++++++++++++++++++ src/cli/instance.rs | 298 +++++++++++++++++++++++++++++++++++++++++++ src/cli/log.rs | 140 ++++++++++++++++++++ src/cli/mod.rs | 305 +++++++++++++++++++++++++++----------------- src/cli/output.rs | 108 ++++++++++++++++ src/cli/version.rs | 136 ++++++++++++++++++++ 7 files changed, 1215 insertions(+), 115 deletions(-) create mode 100644 src/cli/account.rs create mode 100644 src/cli/content.rs create mode 100644 src/cli/instance.rs create mode 100644 src/cli/log.rs create mode 100644 src/cli/output.rs create mode 100644 src/cli/version.rs diff --git a/src/cli/account.rs b/src/cli/account.rs new file mode 100644 index 0000000..f1e7b7f --- /dev/null +++ b/src/cli/account.rs @@ -0,0 +1,196 @@ +use std::io::{self, Write}; +use std::time::Duration; + +use clap::ArgMatches; + +use crate::auth::{Account, AccountStore, AuthResult}; +use crate::cli::output::{active_marker, print_table}; + +type CliResult = Result<(), Box>; + +pub async fn handle_account(matches: &ArgMatches) -> CliResult { + match matches.subcommand() { + Some(("list", _)) => list_accounts(), + Some(("add", sub_matches)) => add_account(sub_matches).await, + Some(("delete", sub_matches)) => delete_account(sub_matches), + Some(("use", sub_matches)) => use_account(sub_matches), + _ => Ok(()), + } +} + +trait AccountStoreLike { + fn accounts(&self) -> &[Account]; + fn add_account(&mut self, account: Account); +} + +impl AccountStoreLike for AccountStore { + fn accounts(&self) -> &[Account] { + &self.accounts + } + + fn add_account(&mut self, account: Account) { + self.add(account); + } +} + +fn list_accounts() -> CliResult { + let store = AccountStore::load(); + let rows = store + .accounts + .iter() + .map(|account| { + vec![ + active_marker(account.active).to_string(), + account.username.clone(), + format!("{:?}", account.account_type), + ] + }) + .collect::>(); + + print_table(&[" ", "Username", "Type"], &rows); + Ok(()) +} + +async fn add_account(matches: &ArgMatches) -> CliResult { + if matches.get_flag("microsoft") { + return add_microsoft_account().await; + } + + if let Some(username) = matches.get_one::("offline") { + let mut store = AccountStore::load(); + add_offline_account(&mut store, username)?; + println!("Added offline account '{}'.", username); + } + + Ok(()) +} + +async fn add_microsoft_account() -> CliResult { + if let Ok(mut slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() { + *slot = None; + } + + let result_arc = crate::auth::start_microsoft_auth(); + + loop { + if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() { + if let Some(info) = slot.as_ref() { + println!("Open: {}", info.verification_uri); + println!("Code: {}", info.user_code); + break; + } + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + + loop { + if let Ok(slot) = result_arc.lock() { + if let Some(result) = slot.as_ref() { + return match result { + AuthResult::Success(account) => { + let mut store = AccountStore::load(); + store.add(account.clone()); + println!("Added Microsoft account '{}'.", account.username); + Ok(()) + } + AuthResult::Error(message) => Err(io::Error::other(message.clone()).into()), + }; + } + } + tokio::time::sleep(Duration::from_millis(500)).await; + } +} + +fn add_offline_account(store: &mut T, username: &str) -> CliResult { + let username = username.trim(); + if username.is_empty() { + return Err(io::Error::other("offline username cannot be empty").into()); + } + + store.add_account(crate::auth::create_offline_account(username)); + Ok(()) +} + +fn delete_account(matches: &ArgMatches) -> CliResult { + let username = required_arg(matches, "username")?; + let mut store = AccountStore::load(); + let index = find_account_index(store.accounts(), username) + .ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?; + + if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? { + println!("Cancelled."); + return Ok(()); + } + + store.remove(index); + println!("Deleted '{}'.", username); + Ok(()) +} + +fn use_account(matches: &ArgMatches) -> CliResult { + let username = required_arg(matches, "username")?; + let mut store = AccountStore::load(); + let index = find_account_index(store.accounts(), username) + .ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?; + store.set_active(index); + println!("Active account set to '{}'.", username); + Ok(()) +} + +fn find_account_index(accounts: &[Account], username: &str) -> Option { + accounts + .iter() + .position(|account| account.username.eq_ignore_ascii_case(username)) +} + +fn confirm(message: &str) -> Result { + print!("{}? [y/N] ", message); + io::stdout().flush()?; + let mut input = String::new(); + io::stdin().read_line(&mut input)?; + Ok(input.trim().eq_ignore_ascii_case("y")) +} + +fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> { + matches + .get_one::(name) + .map(String::as_str) + .ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name))) +} + +#[cfg(test)] +mod tests { + use super::{add_offline_account, AccountStoreLike}; + use crate::auth::{Account, AccountType}; + + #[derive(Default)] + struct MockStore { + accounts: Vec, + } + + impl AccountStoreLike for MockStore { + fn accounts(&self) -> &[Account] { + &self.accounts + } + + fn add_account(&mut self, account: Account) { + self.accounts.push(account); + } + } + + #[test] + fn creates_offline_account_through_store() { + let mut store = MockStore::default(); + add_offline_account(&mut store, "Steve").expect("offline account should be added"); + + assert_eq!(store.accounts.len(), 1); + assert_eq!(store.accounts[0].username, "Steve"); + assert_eq!(store.accounts[0].account_type, AccountType::Offline); + } + + #[test] + fn rejects_empty_offline_username() { + let mut store = MockStore::default(); + assert!(add_offline_account(&mut store, " ").is_err()); + } +} diff --git a/src/cli/content.rs b/src/cli/content.rs new file mode 100644 index 0000000..806b922 --- /dev/null +++ b/src/cli/content.rs @@ -0,0 +1,147 @@ +use std::io; +use std::path::Path; + +use clap::ArgMatches; + +use crate::cli::output::print_table; +use crate::instance::ModEntry; + +type CliResult = Result<(), Box>; +type Scanner = fn(&Path, &str) -> Vec; + +pub async fn handle_mod(matches: &ArgMatches) -> CliResult { + handle_content(matches, "mod", crate::instance::mods::scan_mods) +} + +pub async fn handle_pack(matches: &ArgMatches) -> CliResult { + handle_content(matches, "pack", crate::instance::resource_packs::scan_resource_packs) +} + +pub async fn handle_shader(matches: &ArgMatches) -> CliResult { + handle_content(matches, "shader", crate::instance::shaders::scan_shaders) +} + +fn handle_content(matches: &ArgMatches, kind: &str, scan: Scanner) -> CliResult { + match matches.subcommand() { + Some(("list", sub_matches)) => list_entries(required_arg(sub_matches, "instance")?, scan), + Some(("enable", sub_matches)) => toggle_entry( + required_arg(sub_matches, "instance")?, + required_arg(sub_matches, kind)?, + true, + kind, + scan, + ), + Some(("disable", sub_matches)) => toggle_entry( + required_arg(sub_matches, "instance")?, + required_arg(sub_matches, kind)?, + false, + kind, + scan, + ), + _ => Ok(()), + } +} + +pub(crate) fn find_entry_by_stem<'a>(entries: &'a [ModEntry], target: &str) -> Option<&'a ModEntry> { + entries + .iter() + .find(|entry| entry.file_stem.eq_ignore_ascii_case(target)) +} + +fn require_instance(instances_dir: &Path, name: &str) -> Result<(), io::Error> { + if !instances_dir.join(name).join("instance.json").exists() { + return Err(io::Error::other(format!("Instance '{}' not found", name))); + } + Ok(()) +} + +fn list_entries(instance: &str, scan: Scanner) -> CliResult { + let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); + require_instance(&instances_dir, instance)?; + let rows = scan(&instances_dir, instance) + .into_iter() + .map(|entry| { + vec![ + entry.name, + if entry.enabled { + "enabled".to_string() + } else { + "disabled".to_string() + }, + ] + }) + .collect::>(); + + print_table(&["Name", "State"], &rows); + Ok(()) +} + +fn toggle_entry( + instance: &str, + target: &str, + should_enable: bool, + kind: &str, + scan: Scanner, +) -> CliResult { + let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); + require_instance(&instances_dir, instance)?; + let entries = scan(&instances_dir, instance); + let entry = find_entry_by_stem(&entries, target).ok_or_else(|| { + io::Error::other(format!("{} '{}' not found", kind, target)) + })?; + + if entry.enabled == should_enable { + println!( + "Already {}d.", + if should_enable { "enable" } else { "disable" } + ); + return Ok(()); + } + + crate::instance::mods::toggle_mod(entry)?; + println!( + "{}d '{}'.", + if should_enable { "Enable" } else { "Disable" }, + entry.name + ); + Ok(()) +} + +fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> { + matches + .get_one::(name) + .map(String::as_str) + .ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name))) +} + +#[cfg(test)] +mod tests { + use super::find_entry_by_stem; + use crate::instance::ModEntry; + use std::path::PathBuf; + + fn entry(file_stem: &str) -> ModEntry { + ModEntry { + file_stem: file_stem.to_string(), + name: file_stem.to_string(), + description: String::new(), + enabled: true, + icon_bytes: None, + 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/instance.rs b/src/cli/instance.rs new file mode 100644 index 0000000..222a70d --- /dev/null +++ b/src/cli/instance.rs @@ -0,0 +1,298 @@ +use std::io::{self, Write}; +use std::time::Duration; + +use clap::ArgMatches; + +use crate::cli::output::{format_datetime, print_table}; +use crate::instance::{InstanceManager, ModLoader}; +use crate::running::RunState; + +type CliResult = Result<(), Box>; + +pub async fn handle_instance(matches: &ArgMatches) -> CliResult { + match matches.subcommand() { + Some(("list", _)) => list_instances(), + Some(("create", sub_matches)) => create_instance(sub_matches).await, + Some(("delete", sub_matches)) => delete_instance(sub_matches), + Some(("rename", sub_matches)) => rename_instance(sub_matches), + Some(("launch", sub_matches)) => launch_instance(sub_matches).await, + Some(("config", sub_matches)) => config_instance(sub_matches), + _ => Ok(()), + } +} + +pub(crate) fn parse_loader(input: &str) -> Result { + match input.to_lowercase().as_str() { + "vanilla" => Ok(ModLoader::Vanilla), + "fabric" => Ok(ModLoader::Fabric), + "forge" => Ok(ModLoader::Forge), + "neoforge" => Ok(ModLoader::NeoForge), + "quilt" => Ok(ModLoader::Quilt), + _ => Err(format!( + "unknown loader '{}'. Valid: vanilla, fabric, forge, neoforge, quilt", + input + )), + } +} + +pub(crate) fn parse_resolution(input: &str) -> Result<(u32, u32), String> { + let (width, height) = input + .split_once('x') + .ok_or_else(|| "resolution must be in WxH format".to_string())?; + let width = width + .parse::() + .map_err(|_| "resolution width must be a positive integer".to_string())?; + let height = height + .parse::() + .map_err(|_| "resolution height must be a positive integer".to_string())?; + + if width == 0 || height == 0 { + return Err("resolution values must be greater than zero".to_string()); + } + + Ok((width, height)) +} + +fn manager() -> InstanceManager { + let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); + let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + InstanceManager::new(instances_dir, meta_dir) +} + +fn list_instances() -> CliResult { + let mut instances = manager().load_all(); + instances.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase())); + + let rows = instances + .into_iter() + .map(|config| { + vec![ + config.name, + config.game_version, + config.loader.to_string(), + config + .last_played + .as_ref() + .map(format_datetime) + .unwrap_or_else(|| "-".to_string()), + ] + }) + .collect::>(); + + print_table(&["Name", "Version", "Loader", "Last Played"], &rows); + Ok(()) +} + +async fn create_instance(matches: &ArgMatches) -> CliResult { + let name = required_arg(matches, "name")?; + let version = required_arg(matches, "version")?; + let loader = parse_loader(required_arg(matches, "loader")?) + .map_err(|message| io::Error::other(message))?; + let loader_version = matches.get_one::("loader-version").map(String::as_str); + let manager = manager(); + + println!("Creating instance '{}'...", name); + let config = manager.create(name, version, loader, loader_version).await?; + println!( + "Created '{}' ({} {})", + config.name, config.game_version, config.loader + ); + Ok(()) +} + +fn delete_instance(matches: &ArgMatches) -> CliResult { + let name = required_arg(matches, "name")?; + if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", name))? { + println!("Cancelled."); + return Ok(()); + } + + manager().delete(name)?; + println!("Deleted '{}'.", name); + Ok(()) +} + +fn rename_instance(matches: &ArgMatches) -> CliResult { + let old_name = required_arg(matches, "old")?; + let new_name = required_arg(matches, "new")?; + manager().rename(old_name, new_name)?; + println!("Renamed '{}' to '{}'.", old_name, new_name); + Ok(()) +} + +async fn launch_instance(matches: &ArgMatches) -> CliResult { + let name = required_arg(matches, "name")?; + let manager = manager(); + let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); + let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let config = manager.load_one(name)?; + + println!("Launching '{}'...", name); + crate::instance::launch::launch(&config, &instances_dir, &meta_dir) + .await + .map_err(|error| io::Error::other(format!("Launch failed: {}", error)))?; + + loop { + match crate::running::get(name) { + Some(RunState::Crashed(Some(code))) => { + println!("Game exited with status {}.", code); + break; + } + Some(RunState::Crashed(None)) => { + println!("Game exited with status terminated."); + break; + } + Some(_) => tokio::time::sleep(Duration::from_millis(500)).await, + None => { + println!("Game exited with status 0."); + break; + } + } + } + + Ok(()) +} + +fn config_instance(matches: &ArgMatches) -> CliResult { + let name = required_arg(matches, "name")?; + let manager = manager(); + + if let Some(set_value) = matches.get_one::("set") { + let (key, value) = set_value + .split_once('=') + .ok_or_else(|| io::Error::other("--set must be in key=value format"))?; + + let mut config = manager.load_one(name)?; + apply_config_update(&mut config, key, value)?; + manager.save(&config)?; + println!("Updated '{}' {}.", name, key); + return Ok(()); + } + + let config = manager.load_one(name)?; + let rows = vec![ + vec!["name".to_string(), config.name], + vec!["game-version".to_string(), config.game_version], + vec!["loader".to_string(), config.loader.to_string()], + vec![ + "loader-version".to_string(), + config.loader_version.unwrap_or_else(|| "-".to_string()), + ], + vec!["created".to_string(), format_datetime(&config.created)], + vec![ + "last-played".to_string(), + config + .last_played + .as_ref() + .map(format_datetime) + .unwrap_or_else(|| "-".to_string()), + ], + vec![ + "java-path".to_string(), + config.java_path.unwrap_or_else(|| "-".to_string()), + ], + vec![ + "memory-max".to_string(), + config.memory_max.unwrap_or_else(|| "-".to_string()), + ], + vec![ + "memory-min".to_string(), + config.memory_min.unwrap_or_else(|| "-".to_string()), + ], + vec![ + "jvm-args".to_string(), + if config.jvm_args.is_empty() { + "-".to_string() + } else { + config.jvm_args.join(" ") + }, + ], + vec![ + "resolution".to_string(), + config + .resolution + .map(|(width, height)| format!("{}x{}", width, height)) + .unwrap_or_else(|| "-".to_string()), + ], + ]; + + print_table(&["Field", "Value"], &rows); + Ok(()) +} + +fn apply_config_update( + config: &mut crate::instance::InstanceConfig, + key: &str, + value: &str, +) -> CliResult { + match key { + "memory-max" => { + config.memory_max = if value.is_empty() { + None + } else { + Some(value.to_string()) + } + } + "memory-min" => { + config.memory_min = if value.is_empty() { + None + } else { + Some(value.to_string()) + } + } + "java-path" => { + config.java_path = if value.is_empty() { + None + } else { + Some(value.to_string()) + } + } + "jvm-args" => { + config.jvm_args = value.split_whitespace().map(String::from).collect(); + } + "resolution" => { + config.resolution = if value.is_empty() { + None + } else { + Some(parse_resolution(value).map_err(io::Error::other)?) + }; + } + _ => { + return Err(io::Error::other(format!("unknown key '{}'", key)).into()); + } + } + + Ok(()) +} + +fn confirm(message: &str) -> Result { + print!("{}? [y/N] ", message); + io::stdout().flush()?; + let mut input = String::new(); + io::stdin().read_line(&mut input)?; + Ok(input.trim().eq_ignore_ascii_case("y")) +} + +fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> { + matches + .get_one::(name) + .map(String::as_str) + .ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name))) +} + +#[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()); + } +} diff --git a/src/cli/log.rs b/src/cli/log.rs new file mode 100644 index 0000000..e6e1b7b --- /dev/null +++ b/src/cli/log.rs @@ -0,0 +1,140 @@ +use std::io; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use clap::ArgMatches; + +use crate::cli::output::print_table; + +type CliResult = Result<(), Box>; + +pub async fn handle_log(matches: &ArgMatches) -> CliResult { + match matches.subcommand() { + Some(("list", sub_matches)) => list_logs(required_arg(sub_matches, "instance")?), + Some(("show", sub_matches)) => show_log(sub_matches).await, + _ => Ok(()), + } +} + +fn require_instance(instances_dir: &Path, name: &str) -> Result<(), io::Error> { + if !instances_dir.join(name).join("instance.json").exists() { + return Err(io::Error::other(format!("Instance '{}' not found", name))); + } + Ok(()) +} + +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) + .into_iter() + .map(|entry| { + let size = std::fs::metadata(&entry.path).map(|meta| meta.len()).unwrap_or(0); + vec![entry.name, size.to_string()] + }) + .collect::>(); + + print_table(&["File", "Size"], &rows); + Ok(()) +} + +async fn show_log(matches: &ArgMatches) -> CliResult { + let instance = required_arg(matches, "instance")?; + let file = matches.get_one::("file").map(String::as_str); + let follow = matches.get_flag("follow"); + let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); + require_instance(&instances_dir, instance)?; + let path = resolve_log_path(&instances_dir, instance, file)?; + + let lines = crate::instance::log_files::read_log_file(&path); + for line in &lines { + println!("{}", line); + } + + if follow { + 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); + for line in new_lines.iter().skip(last_len) { + println!("{}", line); + } + last_len = new_lines.len(); + } + } + + Ok(()) +} + +pub(crate) fn resolve_log_path( + instances_dir: &Path, + instance: &str, + file: Option<&str>, +) -> Result { + if let Some(name) = file { + let path = crate::instance::log_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) + .into_iter() + .next() + .map(|entry| entry.path) + .ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance))) +} + +fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> { + matches + .get_one::(name) + .map(String::as_str) + .ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name))) +} + +#[cfg(test)] +mod tests { + use super::resolve_log_path; + + fn unique_temp_dir() -> std::path::PathBuf { + std::env::temp_dir().join(format!( + "mcl_cli_log_test_{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("time should work") + .as_nanos() + )) + } + + #[test] + fn resolves_latest_log_when_no_file_is_given() { + let root = unique_temp_dir(); + let dir = root.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(&root, "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") + ); + + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn resolves_named_log_file() { + let root = unique_temp_dir(); + let dir = root.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(&root, "demo", Some("latest.log")) + .expect("named log should resolve"); + assert_eq!(path.file_name().and_then(|name| name.to_str()), Some("latest.log")); + + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 25c9460..6443091 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1,140 +1,215 @@ -use crate::tui; -use clap::{Arg, ArgAction, Command}; +mod account; +mod content; +mod instance; +mod log; +mod output; +mod version; + +use clap::{Arg, ArgAction, ArgGroup, Command}; pub async fn init() { - let matches = Command::new("mcl") + let matches = build_command().get_matches(); + + if matches.subcommand().is_none() { + let _ = &*crate::tui::theme::THEME; + if let Err(e) = crate::tui::show().await { + tracing::error!("TUI error: {}", e); + } + return; + } + + let result = match matches.subcommand() { + Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await, + Some(("mod", sub_matches)) => content::handle_mod(sub_matches).await, + Some(("pack", sub_matches)) => content::handle_pack(sub_matches).await, + Some(("shader", sub_matches)) => content::handle_shader(sub_matches).await, + Some(("account", sub_matches)) => account::handle_account(sub_matches).await, + Some(("log", sub_matches)) => log::handle_log(sub_matches).await, + Some(("version", sub_matches)) => version::handle_version(sub_matches).await, + _ => Ok(()), + }; + + if let Err(e) = result { + eprintln!("error: {}", e); + std::process::exit(1); + } +} + +fn build_command() -> Command { + Command::new("mcl") .about("Minecraft CLI Launcher") .version("1.0.0") .subcommand_required(false) .arg_required_else_help(false) .subcommand( - Command::new("launch") - .about("Launch Minecraft with a specific profile") + Command::new("instance") + .about("Manage launcher instances") + .subcommand_required(true) .arg_required_else_help(true) - .arg( - Arg::new("profile") - .short('p') - .long("profile") - .help("Profile to launch (e.g., main)") - .required(true) - .action(ArgAction::Set), + .subcommand(Command::new("list").about("List instances")) + .subcommand( + Command::new("create") + .about("Create an instance") + .arg_required_else_help(true) + .arg(Arg::new("name").required(true).action(ArgAction::Set)) + .arg( + Arg::new("version") + .long("version") + .required(true) + .action(ArgAction::Set), + ) + .arg( + Arg::new("loader") + .long("loader") + .required(true) + .action(ArgAction::Set), + ) + .arg( + Arg::new("loader-version") + .long("loader-version") + .action(ArgAction::Set), + ), ) - .arg( - Arg::new("offline") - .short('o') - .long("offline") - .help("Launch Minecraft in offline mode") - .action(ArgAction::SetTrue), + .subcommand( + Command::new("delete") + .about("Delete an instance") + .arg_required_else_help(true) + .arg(Arg::new("name").required(true).action(ArgAction::Set)) + .arg(Arg::new("yes").long("yes").action(ArgAction::SetTrue)), ) - .arg( - Arg::new("memory") - .short('m') - .long("memory") - .help("Set memory allocation for Minecraft (e.g., 4G, 512M)") - .action(ArgAction::Set), + .subcommand( + Command::new("rename") + .about("Rename an instance") + .arg_required_else_help(true) + .arg(Arg::new("old").required(true).action(ArgAction::Set)) + .arg(Arg::new("new").required(true).action(ArgAction::Set)), ) - .arg( - Arg::new("resolution") - .short('r') - .long("resolution") - .help("Set screen resolution (e.g., 1920x1080)") - .action(ArgAction::Set), + .subcommand( + Command::new("launch") + .about("Launch an instance") + .arg_required_else_help(true) + .arg(Arg::new("name").required(true).action(ArgAction::Set)), ) - .arg( - Arg::new("jvm-args") - .short('j') - .long("jvm-args") - .help("Custom JVM arguments for Minecraft (e.g., -Xmx4G)") - .action(ArgAction::Set) - .num_args(1..), + .subcommand( + Command::new("config") + .about("Show or update instance config") + .arg_required_else_help(true) + .arg(Arg::new("name").required(true).action(ArgAction::Set)) + .arg(Arg::new("set").long("set").action(ArgAction::Set)), + ), + ) + .subcommand(build_content_command("mod", "mods")) + .subcommand(build_content_command("pack", "resource packs")) + .subcommand(build_content_command("shader", "shaders")) + .subcommand( + Command::new("account") + .about("Manage accounts") + .subcommand_required(true) + .arg_required_else_help(true) + .subcommand(Command::new("list").about("List accounts")) + .subcommand( + Command::new("add") + .about("Add an account") + .arg( + Arg::new("microsoft") + .long("microsoft") + .action(ArgAction::SetTrue), + ) + .arg(Arg::new("offline").long("offline").action(ArgAction::Set)) + .group( + ArgGroup::new("account_source") + .args(["microsoft", "offline"]) + .required(true), + ), ) - .arg( - Arg::new("no-window") - .short('n') - .long("no-window") - .help("Run Minecraft in headless mode (no graphical window)") - .action(ArgAction::SetTrue), + .subcommand( + Command::new("delete") + .about("Delete an account") + .arg_required_else_help(true) + .arg(Arg::new("username").required(true).action(ArgAction::Set)) + .arg(Arg::new("yes").long("yes").action(ArgAction::SetTrue)), + ) + .subcommand( + Command::new("use") + .about("Set active account") + .arg_required_else_help(true) + .arg(Arg::new("username").required(true).action(ArgAction::Set)), ), ) .subcommand( - Command::new("profiles") - .about("Manage Minecraft profiles") + Command::new("log") + .about("View instance logs") + .subcommand_required(true) .arg_required_else_help(true) - .arg( - Arg::new("list") - .short('l') - .long("list") - .help("List all available profiles") - .conflicts_with("delete") - .action(ArgAction::SetTrue), + .subcommand( + Command::new("list") + .about("List log files") + .arg_required_else_help(true) + .arg(Arg::new("instance").required(true).action(ArgAction::Set)), ) - .arg( - Arg::new("delete") - .short('d') - .long("delete") - .help("Delete a specific profile") - .action(ArgAction::Set), + .subcommand( + Command::new("show") + .about("Show a log file") + .arg_required_else_help(true) + .arg(Arg::new("instance").required(true).action(ArgAction::Set)) + .arg(Arg::new("file").long("file").action(ArgAction::Set)) + .arg(Arg::new("follow").long("follow").action(ArgAction::SetTrue)), ), ) - .get_matches(); + .subcommand( + Command::new("version") + .about("List available game versions") + .subcommand_required(true) + .arg_required_else_help(true) + .subcommand( + Command::new("list") + .about("List available versions") + .arg(Arg::new("loader").long("loader").action(ArgAction::Set)) + .arg( + Arg::new("snapshots") + .long("snapshots") + .action(ArgAction::SetTrue), + ), + ), + ) +} - if matches.subcommand().is_none() { - // Force eager theme initialization before TUI starts (prevents lazy init inside render loop) - let _ = &*crate::tui::theme::THEME; - match tui::show().await { - Ok(_) => {} - Err(e) => { - tracing::error!("TUI error: {}", e); - } - } - } +fn build_content_command(name: &'static str, about: &'static str) -> Command { + Command::new(name) + .about(format!("Manage {}", about)) + .subcommand_required(true) + .arg_required_else_help(true) + .subcommand( + Command::new("list") + .about(format!("List {}", about)) + .arg_required_else_help(true) + .arg(Arg::new("instance").required(true).action(ArgAction::Set)), + ) + .subcommand( + Command::new("enable") + .about(format!("Enable a {} entry", name)) + .arg_required_else_help(true) + .arg(Arg::new("instance").required(true).action(ArgAction::Set)) + .arg(Arg::new(name).required(true).action(ArgAction::Set)), + ) + .subcommand( + Command::new("disable") + .about(format!("Disable a {} entry", name)) + .arg_required_else_help(true) + .arg(Arg::new("instance").required(true).action(ArgAction::Set)) + .arg(Arg::new(name).required(true).action(ArgAction::Set)), + ) +} - match matches.subcommand() { - Some(("launch", launch_matches)) => { - let profile = match launch_matches.get_one::("profile") { - Some(p) => p, - None => { - tracing::error!("Launch subcommand missing required --profile argument"); - return; - } - }; +#[cfg(test)] +mod tests { + use super::build_command; - let mem_default = String::from("Default"); - let memory = launch_matches - .get_one::("memory") - .unwrap_or(&mem_default); - - let res_default = String::from("Default"); - let resolution = launch_matches - .get_one::("resolution") - .unwrap_or(&res_default); - - let jvm_args = launch_matches - .get_many::("jvm-args") - .map(|args| args.map(|s| s.as_str()).collect::>().join(" ")) - .unwrap_or_else(|| "None".to_string()); - - if launch_matches.get_flag("offline") { - tracing::debug!("Launching profile '{}' in offline mode...", profile); - } else { - tracing::debug!("Launching profile '{}' in online mode...", profile); - } - - tracing::debug!("Memory: {}", memory); - tracing::debug!("Resolution: {}", resolution); - tracing::debug!("JVM Args: {}", jvm_args); - - if launch_matches.get_flag("no-window") { - tracing::debug!("Running in headless mode..."); - } - } - Some(("profiles", profiles_matches)) => { - if profiles_matches.get_flag("list") { - tracing::debug!("Listing all profiles..."); - } else if let Some(profile) = profiles_matches.get_one::("delete") { - tracing::debug!("Deleting profile '{}'...", profile); - } - } - _ => {} + #[test] + fn parses_instance_list_subcommand() { + let matches = build_command() + .try_get_matches_from(["mcl", "instance", "list"]) + .expect("command should parse"); + assert!(matches.subcommand_matches("instance").is_some()); } } diff --git a/src/cli/output.rs b/src/cli/output.rs new file mode 100644 index 0000000..d5ec575 --- /dev/null +++ b/src/cli/output.rs @@ -0,0 +1,108 @@ +use chrono::{DateTime, Utc}; + +pub fn print_table(headers: &[&str], rows: &[Vec]) { + print!("{}", render_table(headers, rows)); +} + +pub fn render_table(headers: &[&str], rows: &[Vec]) -> String { + let widths = column_widths(headers, rows); + let mut out = String::new(); + + out.push_str(&render_row( + &headers + .iter() + .map(|value| value.to_string()) + .collect::>(), + &widths, + )); + out.push('\n'); + out.push_str(&render_separator(&widths)); + out.push('\n'); + + for row in rows { + out.push_str(&render_row(row, &widths)); + out.push('\n'); + } + + out +} + +pub fn format_datetime(value: &DateTime) -> String { + value.format("%Y-%m-%d %H:%M:%S UTC").to_string() +} + +pub fn active_marker(active: bool) -> &'static str { + if active { + ">" + } else { + " " + } +} + +fn column_widths(headers: &[&str], rows: &[Vec]) -> Vec { + let mut widths: Vec = headers.iter().map(|header| header.len()).collect(); + + for row in rows { + if row.len() > widths.len() { + widths.resize(row.len(), 0); + } + + for (index, value) in row.iter().enumerate() { + widths[index] = widths[index].max(value.len()); + } + } + + widths +} + +fn render_row(row: &[String], widths: &[usize]) -> String { + widths + .iter() + .enumerate() + .map(|(index, width)| { + format!( + "{:>() + .join(" ") +} + +fn render_separator(widths: &[usize]) -> String { + widths + .iter() + .map(|width| "-".repeat(*width)) + .collect::>() + .join(" ") +} + +#[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"); + } +} diff --git a/src/cli/version.rs b/src/cli/version.rs new file mode 100644 index 0000000..311eb5e --- /dev/null +++ b/src/cli/version.rs @@ -0,0 +1,136 @@ +use std::collections::HashSet; +use std::io; + +use clap::ArgMatches; + +use crate::cli::instance::parse_loader; +use crate::cli::output::print_table; +use crate::instance::ModLoader; +use crate::net::HttpClient; +use crate::net::mojang::{VersionEntry, VersionManifest}; + +type CliResult = Result<(), Box>; + +pub async fn handle_version(matches: &ArgMatches) -> CliResult { + match matches.subcommand() { + Some(("list", sub_matches)) => list_versions(sub_matches).await, + _ => Ok(()), + } +} + +async fn list_versions(matches: &ArgMatches) -> CliResult { + let client = HttpClient::new(); + let manifest = crate::net::mojang::fetch_version_manifest(&client).await?; + let snapshots = matches.get_flag("snapshots"); + let loader = matches + .get_one::("loader") + .map(|value| parse_loader(value).map_err(io::Error::other)) + .transpose()?; + + let supported = match loader { + Some(ModLoader::Vanilla) | None => None, + Some(loader) => Some(fetch_supported_versions(&client, loader).await?), + }; + + let rows = filter_manifest_versions(&manifest, supported.as_ref(), snapshots) + .into_iter() + .map(|entry| vec![entry.id, entry.version_type]) + .collect::>(); + + print_table(&["Version", "Type"], &rows); + Ok(()) +} + +async fn fetch_supported_versions( + client: &HttpClient, + loader: ModLoader, +) -> Result, Box> { + let versions: HashSet = match loader { + ModLoader::Vanilla => HashSet::new(), + ModLoader::Fabric => crate::net::fabric::fetch_fabric_game_versions(client) + .await? + .into_iter() + .map(|version| version.id) + .collect::>(), + ModLoader::Forge => crate::net::forge::fetch_forge_game_versions(client) + .await? + .into_iter() + .map(|version| version.id) + .collect::>(), + ModLoader::NeoForge => crate::net::neoforge::fetch_neoforge_game_versions(client) + .await? + .into_iter() + .map(|version| version.id) + .collect::>(), + ModLoader::Quilt => crate::net::quilt::fetch_quilt_game_versions(client) + .await? + .into_iter() + .map(|version| version.id) + .collect::>(), + }; + + Ok(versions) +} + +fn filter_manifest_versions( + manifest: &VersionManifest, + supported: Option<&HashSet>, + snapshots: bool, +) -> Vec { + manifest + .versions + .iter() + .filter(|entry| snapshots || entry.version_type == "release") + .filter(|entry| { + supported + .map(|versions| versions.contains(&entry.id)) + .unwrap_or(true) + }) + .cloned() + .collect() +} + +#[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"); + } +}