refactor: upgrade crates and restructure project
This commit is contained in:
1 parent
ea093c044f
commit
47dad69321
80 files changed
+6094
-6125
No files matched your search
+2
-15
@@ -1,4 +1,4 @@
|
||||
use std::io::{self, Write};
|
||||
use std::io;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::ArgMatches;
|
||||
@@ -143,20 +143,7 @@ fn find_account_index(accounts: &[Account], username: &str) -> Option<usize> {
|
||||
.position(|account| account.username.eq_ignore_ascii_case(username))
|
||||
}
|
||||
|
||||
fn confirm(message: &str) -> Result<bool, io::Error> {
|
||||
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::<String>(name)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name)))
|
||||
}
|
||||
use super::utils::{confirm, required_arg};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
+27
-30
@@ -3,22 +3,31 @@ use std::path::Path;
|
||||
|
||||
use clap::ArgMatches;
|
||||
|
||||
use super::utils::{require_instance, required_arg};
|
||||
use crate::cli::output::print_table;
|
||||
use crate::instance::ModEntry;
|
||||
use crate::instance::ContentEntry;
|
||||
|
||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||
type Scanner = fn(&Path, &str) -> Vec<ModEntry>;
|
||||
type Scanner = fn(&Path, &str) -> Vec<ContentEntry>;
|
||||
|
||||
pub async fn handle_mod(matches: &ArgMatches) -> CliResult {
|
||||
handle_content(matches, "mod", crate::instance::mods::scan_mods)
|
||||
pub fn handle_mod(matches: &ArgMatches) -> CliResult {
|
||||
handle_content(matches, "mod", crate::instance::content::mods::scan_mods)
|
||||
}
|
||||
|
||||
pub async fn handle_pack(matches: &ArgMatches) -> CliResult {
|
||||
handle_content(matches, "pack", crate::instance::resource_packs::scan_resource_packs)
|
||||
pub fn handle_pack(matches: &ArgMatches) -> CliResult {
|
||||
handle_content(
|
||||
matches,
|
||||
"pack",
|
||||
crate::instance::content::resource_packs::scan_resource_packs,
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn handle_shader(matches: &ArgMatches) -> CliResult {
|
||||
handle_content(matches, "shader", crate::instance::shaders::scan_shaders)
|
||||
pub fn handle_shader(matches: &ArgMatches) -> CliResult {
|
||||
handle_content(
|
||||
matches,
|
||||
"shader",
|
||||
crate::instance::content::shaders::scan_shaders,
|
||||
)
|
||||
}
|
||||
|
||||
fn handle_content(matches: &ArgMatches, kind: &str, scan: Scanner) -> CliResult {
|
||||
@@ -42,19 +51,15 @@ fn handle_content(matches: &ArgMatches, kind: &str, scan: Scanner) -> CliResult
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn find_entry_by_stem<'a>(entries: &'a [ModEntry], target: &str) -> Option<&'a ModEntry> {
|
||||
pub(crate) fn find_entry_by_stem<'a>(
|
||||
entries: &'a [ContentEntry],
|
||||
target: &str,
|
||||
) -> Option<&'a ContentEntry> {
|
||||
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)?;
|
||||
@@ -86,9 +91,8 @@ fn toggle_entry(
|
||||
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))
|
||||
})?;
|
||||
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!(
|
||||
@@ -98,7 +102,7 @@ fn toggle_entry(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
crate::instance::mods::toggle_mod(entry)?;
|
||||
crate::instance::content::mods::toggle_entry(entry)?;
|
||||
println!(
|
||||
"{}d '{}'.",
|
||||
if should_enable { "Enable" } else { "Disable" },
|
||||
@@ -107,21 +111,14 @@ fn toggle_entry(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> {
|
||||
matches
|
||||
.get_one::<String>(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 crate::instance::ContentEntry;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn entry(file_stem: &str) -> ModEntry {
|
||||
ModEntry {
|
||||
fn entry(file_stem: &str) -> ContentEntry {
|
||||
ContentEntry {
|
||||
file_stem: file_stem.to_string(),
|
||||
name: file_stem.to_string(),
|
||||
description: String::new(),
|
||||
|
||||
+17
-15
@@ -19,13 +19,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
||||
|
||||
let mrpack_path = match parsed {
|
||||
modrinth::ModrinthInput::LocalFile(ref path) => {
|
||||
let resolved = if let Some(stripped) = path.strip_prefix("~/") {
|
||||
dirs_next::home_dir()
|
||||
.map(|h| h.join(stripped))
|
||||
.unwrap_or_else(|| std::path::PathBuf::from(path))
|
||||
} else {
|
||||
std::path::PathBuf::from(path)
|
||||
};
|
||||
let resolved = crate::config::settings::resolve_path(path);
|
||||
if !resolved.exists() {
|
||||
return Err(format!("File not found: {}", resolved.display()).into());
|
||||
}
|
||||
@@ -33,11 +27,13 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
||||
}
|
||||
modrinth::ModrinthInput::ProjectSlug(ref slug) => {
|
||||
println!("Fetching project '{slug}'...");
|
||||
let project = modrinth::fetch_project(&client, slug).await
|
||||
let project = modrinth::fetch_project(&client, slug)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to fetch project: {e}"))?;
|
||||
println!("Found: {}", project.title);
|
||||
|
||||
let versions = modrinth::fetch_versions(&client, slug).await
|
||||
let versions = modrinth::fetch_versions(&client, slug)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to fetch versions: {e}"))?;
|
||||
|
||||
if versions.is_empty() {
|
||||
@@ -61,13 +57,17 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
||||
|
||||
let tmp_dir = manager.meta_dir.join("tmp");
|
||||
std::fs::create_dir_all(&tmp_dir)?;
|
||||
modrinth::download_mrpack(&client, version, &tmp_dir).await
|
||||
modrinth::download_mrpack(&client, version, &tmp_dir)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to download .mrpack: {e}"))?
|
||||
}
|
||||
modrinth::ModrinthInput::VersionId { ref slug, ref version_id } => {
|
||||
modrinth::ModrinthInput::VersionId {
|
||||
slug: _,
|
||||
ref version_id,
|
||||
} => {
|
||||
println!("Fetching version '{version_id}'...");
|
||||
let _slug = slug;
|
||||
let version = modrinth::fetch_version(&client, version_id).await
|
||||
let version = modrinth::fetch_version(&client, version_id)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to fetch version: {e}"))?;
|
||||
|
||||
println!(
|
||||
@@ -78,7 +78,8 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
||||
|
||||
let tmp_dir = manager.meta_dir.join("tmp");
|
||||
std::fs::create_dir_all(&tmp_dir)?;
|
||||
modrinth::download_mrpack(&client, &version, &tmp_dir).await
|
||||
modrinth::download_mrpack(&client, &version, &tmp_dir)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to download .mrpack: {e}"))?
|
||||
}
|
||||
};
|
||||
@@ -102,7 +103,8 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
||||
summary.override_count
|
||||
);
|
||||
|
||||
let config = crate::instance::import::execute_import(&summary, &manager).await
|
||||
let config = crate::instance::import::execute_import(&summary, &manager)
|
||||
.await
|
||||
.map_err(|e| format!("Import failed: {e}"))?;
|
||||
|
||||
println!("Instance '{}' created successfully.", config.name);
|
||||
|
||||
+14
-22
@@ -1,8 +1,9 @@
|
||||
use std::io::{self, Write};
|
||||
use std::io;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::ArgMatches;
|
||||
|
||||
use super::utils::{confirm, required_arg};
|
||||
use crate::cli::output::{format_datetime, print_table};
|
||||
use crate::instance::{InstanceManager, ModLoader};
|
||||
use crate::running::RunState;
|
||||
@@ -87,13 +88,16 @@ fn list_instances() -> CliResult {
|
||||
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(io::Error::other)?;
|
||||
let loader_version = matches.get_one::<String>("loader-version").map(String::as_str);
|
||||
let loader = parse_loader(required_arg(matches, "loader")?).map_err(io::Error::other)?;
|
||||
let loader_version = matches
|
||||
.get_one::<String>("loader-version")
|
||||
.map(String::as_str);
|
||||
let manager = manager();
|
||||
|
||||
println!("Creating instance '{}'...", name);
|
||||
let config = manager.create(name, version, loader, loader_version).await?;
|
||||
let config = manager
|
||||
.create(name, version, loader, loader_version)
|
||||
.await?;
|
||||
println!(
|
||||
"Created '{}' ({} {})",
|
||||
config.name, config.game_version, config.loader
|
||||
@@ -140,7 +144,7 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
|
||||
break;
|
||||
}
|
||||
Some(RunState::Crashed(None)) => {
|
||||
println!("Game exited with status terminated.");
|
||||
println!("Game was terminated.");
|
||||
break;
|
||||
}
|
||||
Some(_) => tokio::time::sleep(Duration::from_millis(500)).await,
|
||||
@@ -278,28 +282,16 @@ fn apply_config_update(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn confirm(message: &str) -> Result<bool, io::Error> {
|
||||
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::<String>(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));
|
||||
assert_eq!(
|
||||
parse_resolution("1920x1080").expect("should parse"),
|
||||
(1920, 1080)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+10
-17
@@ -16,20 +16,15 @@ pub async fn handle_log(matches: &ArgMatches) -> CliResult {
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
let size = std::fs::metadata(&entry.path)
|
||||
.map(|meta| meta.len())
|
||||
.unwrap_or(0);
|
||||
vec![entry.name, size.to_string()]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -86,12 +81,7 @@ pub(crate) fn resolve_log_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::<String>(name)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name)))
|
||||
}
|
||||
use super::utils::{require_instance, required_arg};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -131,9 +121,12 @@ mod tests {
|
||||
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 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);
|
||||
}
|
||||
|
||||
+25
-12
@@ -1,9 +1,10 @@
|
||||
mod account;
|
||||
mod content;
|
||||
mod import;
|
||||
mod instance;
|
||||
mod log;
|
||||
mod output;
|
||||
mod import;
|
||||
mod utils;
|
||||
mod version;
|
||||
|
||||
use clap::{Arg, ArgAction, ArgGroup, Command};
|
||||
@@ -12,7 +13,7 @@ pub async fn init() {
|
||||
let matches = build_command().get_matches();
|
||||
|
||||
if matches.subcommand().is_none() {
|
||||
let _ = &*crate::tui::theme::THEME;
|
||||
let _ = &*crate::config::theme::THEME;
|
||||
if let Err(e) = crate::tui::show().await {
|
||||
tracing::error!("TUI error: {}", e);
|
||||
}
|
||||
@@ -21,9 +22,9 @@ pub async fn init() {
|
||||
|
||||
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(("mod", sub_matches)) => content::handle_mod(sub_matches),
|
||||
Some(("pack", sub_matches)) => content::handle_pack(sub_matches),
|
||||
Some(("shader", sub_matches)) => content::handle_shader(sub_matches),
|
||||
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,
|
||||
@@ -40,7 +41,7 @@ pub async fn init() {
|
||||
fn build_command() -> Command {
|
||||
Command::new("mcl")
|
||||
.about("Minecraft CLI Launcher")
|
||||
.version("1.0.0")
|
||||
.version(env!("CARGO_PKG_VERSION"))
|
||||
.subcommand_required(false)
|
||||
.arg_required_else_help(false)
|
||||
.subcommand(
|
||||
@@ -184,12 +185,24 @@ fn build_command() -> Command {
|
||||
Command::new("import")
|
||||
.about("Import a modpack")
|
||||
.arg_required_else_help(true)
|
||||
.arg(Arg::new("source").required(true).action(ArgAction::Set)
|
||||
.help("Modrinth URL, project slug, or local .mrpack file path"))
|
||||
.arg(Arg::new("version").long("version").action(ArgAction::Set)
|
||||
.help("Modpack version to import (default: latest)"))
|
||||
.arg(Arg::new("name").long("name").action(ArgAction::Set)
|
||||
.help("Override instance name")),
|
||||
.arg(
|
||||
Arg::new("source")
|
||||
.required(true)
|
||||
.action(ArgAction::Set)
|
||||
.help("Modrinth URL, project slug, or local .mrpack file path"),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("version")
|
||||
.long("version")
|
||||
.action(ArgAction::Set)
|
||||
.help("Modpack version to import (default: latest)"),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("name")
|
||||
.long("name")
|
||||
.action(ArgAction::Set)
|
||||
.help("Override instance name"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
use std::io::{self, Write};
|
||||
|
||||
use clap::ArgMatches;
|
||||
|
||||
pub fn confirm(message: &str) -> Result<bool, io::Error> {
|
||||
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"))
|
||||
}
|
||||
|
||||
pub fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> {
|
||||
matches
|
||||
.get_one::<String>(name)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| io::Error::other(format!("missing required argument '{name}'")))
|
||||
}
|
||||
|
||||
pub fn require_instance(instances_dir: &std::path::Path, name: &str) -> Result<(), io::Error> {
|
||||
if !instances_dir.join(name).join("instance.json").exists() {
|
||||
return Err(io::Error::other(format!("Instance '{name}' not found")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+1
-1
@@ -6,8 +6,8 @@ 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};
|
||||
use crate::net::HttpClient;
|
||||
|
||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
|
||||
Reference in new issue
Block a user