From 11e64fc7560de3cd0def718edf68c31e3dc8be72 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Wed, 4 Sep 2024 15:08:55 +0200 Subject: move stuff around, remove lib.rs for overview --- src/apis/modrinth.rs | 2 +- src/commands.rs | 5 ++ src/commands/download.rs | 2 +- src/commands/io.rs | 7 +- src/commands/list.rs | 193 +++++++++++++++++++------------------------ src/commands/mod.rs | 11 --- src/commands/modification.rs | 35 +------- src/commands/update.rs | 11 +-- src/config.rs | 5 +- src/data.rs | 13 +++ src/data/gameversion.rs | 118 ++++++++++++++++++++++++++ src/data/list.rs | 19 +++++ src/data/modification.rs | 11 +++ src/data/modloader.rs | 39 +++++++++ src/data/project.rs | 12 +++ src/db.rs | 2 +- src/files.rs | 7 +- src/lib.rs | 170 ------------------------------------- src/main.rs | 34 +++++--- 19 files changed, 337 insertions(+), 359 deletions(-) create mode 100644 src/commands.rs delete mode 100644 src/commands/mod.rs create mode 100644 src/data.rs create mode 100644 src/data/gameversion.rs create mode 100644 src/data/list.rs create mode 100644 src/data/modification.rs create mode 100644 src/data/modloader.rs create mode 100644 src/data/project.rs delete mode 100644 src/lib.rs diff --git a/src/apis/modrinth.rs b/src/apis/modrinth.rs index 7cdc719..7f1fb52 100644 --- a/src/apis/modrinth.rs +++ b/src/apis/modrinth.rs @@ -139,7 +139,7 @@ async fn get( let client = Client::builder() .user_agent(format!( - "fxqnlr/modlistcli/{} (fxqnlr@gmail.com)", + "fxqnlr/modlist/{} (fxqnlr@gmail.com)", env!("CARGO_PKG_VERSION") )) .build()?; diff --git a/src/commands.rs b/src/commands.rs new file mode 100644 index 0000000..a9d2c2c --- /dev/null +++ b/src/commands.rs @@ -0,0 +1,5 @@ +pub mod download; +pub mod io; +pub mod list; +pub mod modification; +pub mod update; diff --git a/src/commands/download.rs b/src/commands/download.rs index 7ea5c29..269d5d3 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -1,5 +1,6 @@ use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; +use crate::apis::modrinth::get_raw_versions; use crate::{config::Cfg, List}; use crate::{ db::userlist_get_all_current_versions_with_mods, @@ -8,7 +9,6 @@ use crate::{ clean_list_dir, delete_version, disable_version, download_versions, get_downloaded_versions, }, - modrinth::get_raw_versions, }; use crate::{PROGRESS_CHARS, STYLE_BAR_POS}; diff --git a/src/commands/io.rs b/src/commands/io.rs index 3e171f1..dea0d84 100644 --- a/src/commands/io.rs +++ b/src/commands/io.rs @@ -4,13 +4,10 @@ use std::fs::File; use std::io::prelude::*; use crate::{ - config::Cfg, - db::{ + config::Cfg, data::modification::{AddMod, IDSelector}, db::{ lists_get, lists_get_all_ids, lists_insert, userlist_get_all_ids, userlist_get_current_version, userlist_get_set_version, - }, - error::{EType, MLErr, MLE}, - mod_add, AddMod, IDSelector, List, Modloader, STYLE_OPERATION, + }, error::{EType, MLErr, MLE}, mod_add, List, Modloader, STYLE_OPERATION }; #[derive(Debug, Serialize, Deserialize)] diff --git a/src/commands/list.rs b/src/commands/list.rs index 148bd16..23a9f0f 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -1,124 +1,105 @@ use indicatif::{ProgressBar, ProgressStyle}; use crate::{ - config::Cfg, - db::{ - config_change_current_list, config_get_current_list, lists_get, + config::Cfg, data::modloader::Modloader, db::{ + config_change_current_list, lists_get, lists_get_all_ids, lists_insert, lists_remove, lists_version, - }, - error::{EType, MLErr, MLE}, - update, Modloader, STYLE_OPERATION, + }, error::{EType, MLErr, MLE}, update, STYLE_OPERATION }; -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct List { - pub id: String, - pub mc_version: String, - pub modloader: Modloader, - pub download_folder: String, +/// # Errors +pub fn add( + config: &Cfg, + id: &str, + mc_version: &str, + modloader: &Modloader, + directory: &str, +) -> MLE<()> { + let p = ProgressBar::new_spinner(); + p.set_style( + ProgressStyle::with_template(STYLE_OPERATION).map_err(|_| { + MLErr::new(EType::LibIndicatif, "template error") + })?, + ); + p.set_message(format!("Create {id}")); + lists_insert(config, id, mc_version, modloader, directory)?; + p.finish_with_message(format!("Created {id}")); + Ok(()) } -impl List { - /// # Errors - pub fn get_current_list(config: &Cfg) -> MLE { - let id = config_get_current_list(config)?; - lists_get(config, &id) - } - - /// # Errors - pub fn add( - config: &Cfg, - id: &str, - mc_version: &str, - modloader: &Modloader, - directory: &str, - ) -> MLE<()> { - let p = ProgressBar::new_spinner(); - p.set_style( - ProgressStyle::with_template(STYLE_OPERATION).map_err(|_| { - MLErr::new(EType::LibIndicatif, "template error") - })?, - ); - p.set_message(format!("Create {id}")); - lists_insert(config, id, mc_version, modloader, directory)?; - p.finish_with_message(format!("Created {id}")); - Ok(()) - } +/// # Errors +pub fn change(config: &Cfg, id: &str) -> MLE<()> { + let p = ProgressBar::new_spinner(); + p.set_style( + ProgressStyle::with_template(STYLE_OPERATION).map_err(|_| { + MLErr::new(EType::LibIndicatif, "template error") + })?, + ); + p.set_message(format!("Change default list to {id}")); - /// # Errors - pub fn change(config: &Cfg, id: &str) -> MLE<()> { - let p = ProgressBar::new_spinner(); - p.set_style( - ProgressStyle::with_template(STYLE_OPERATION).map_err(|_| { - MLErr::new(EType::LibIndicatif, "template error") - })?, - ); - p.set_message(format!("Change default list to {id}")); + if !lists_get_all_ids(config)?.into_iter().any(|l| l == id) { + return Err(MLErr::new(EType::ArgumentError, "List not found")); + }; + config_change_current_list(config, id)?; - if !lists_get_all_ids(config)?.into_iter().any(|l| l == id) { - return Err(MLErr::new(EType::ArgumentError, "List not found")); - }; - config_change_current_list(config, id)?; - - p.finish_with_message(format!("Changed default list to {id}")); - Ok(()) - } + p.finish_with_message(format!("Changed default list to {id}")); + Ok(()) +} - /// # Errors - pub fn remove(config: &Cfg, id: &str) -> MLE<()> { - let p = ProgressBar::new_spinner(); - p.set_style( - ProgressStyle::with_template(STYLE_OPERATION).map_err(|_| { - MLErr::new(EType::LibIndicatif, "template error") - })?, - ); - p.set_message(format!("Remove {id}")); - lists_remove(config, id)?; - p.finish_with_message(format!("Removed {id}")); - Ok(()) - } +/// # Errors +pub fn remove(config: &Cfg, id: &str) -> MLE<()> { + let p = ProgressBar::new_spinner(); + p.set_style( + ProgressStyle::with_template(STYLE_OPERATION).map_err(|_| { + MLErr::new(EType::LibIndicatif, "template error") + })?, + ); + p.set_message(format!("Remove {id}")); + lists_remove(config, id)?; + p.finish_with_message(format!("Removed {id}")); + Ok(()) +} - ///Changing the current lists version and updating it - /// - /// #Arguments - /// - /// * `config` - The current config - /// * `args` - All args, to extract the new version - /// # Errors - pub async fn version( - config: &Cfg, - id: &str, - mc_version: String, - download: bool, - delete: bool, - ) -> MLE<()> { - let p = ProgressBar::new_spinner(); - p.set_style( - ProgressStyle::with_template(STYLE_OPERATION).map_err(|_| { - MLErr::new(EType::LibIndicatif, "template error") - })?, - ); - p.set_message(format!( - "Change version for list {id} to minecraft version: {mc_version}" - )); +///Changing the current lists version and updating it +/// +/// #Arguments +/// +/// * `config` - The current config +/// * `args` - All args, to extract the new version +/// # Errors +pub async fn version( + config: &Cfg, + id: &str, + mc_version: String, + download: bool, + delete: bool, +) -> MLE<()> { + let p = ProgressBar::new_spinner(); + p.set_style( + ProgressStyle::with_template(STYLE_OPERATION).map_err(|_| { + MLErr::new(EType::LibIndicatif, "template error") + })?, + ); + p.set_message(format!( + "Change version for list {id} to minecraft version: {mc_version}" + )); - lists_version(config, id, &mc_version)?; + lists_version(config, id, &mc_version)?; - p.finish_with_message(format!( - "Changed version for list {id} to minecraft version: {mc_version}" - )); + p.finish_with_message(format!( + "Changed version for list {id} to minecraft version: {mc_version}" + )); - let list = lists_get(config, id)?; - update(config, vec![list], true, download, delete).await - } + let list = lists_get(config, id)?; + update(config, vec![list], true, download, delete).await +} - /// # Errors - pub fn list(config: &Cfg) -> MLE<()> { - let lists = lists_get_all_ids(config)?; - for list in lists { - let l = lists_get(config, &list)?; - println!("{}: | {} | {}", l.id, l.mc_version, l.modloader); - } - Ok(()) +/// # Errors +pub fn list(config: &Cfg) -> MLE<()> { + let lists = lists_get_all_ids(config)?; + for list in lists { + let l = lists_get(config, &list)?; + println!("{}: | {} | {}", l.id, l.mc_version, l.modloader); } + Ok(()) } diff --git a/src/commands/mod.rs b/src/commands/mod.rs deleted file mode 100644 index 0f13056..0000000 --- a/src/commands/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -pub mod download; -pub mod io; -pub mod list; -pub mod modification; -pub mod update; - -pub use download::*; -pub use io::*; -pub use list::*; -pub use modification::*; -pub use update::*; diff --git a/src/commands/modification.rs b/src/commands/modification.rs index 8f115ee..d20f575 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -3,44 +3,13 @@ use std::collections::HashMap; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use crate::{ - config::Cfg, - db::{ + apis::modrinth::{extract_current_version, get_raw_versions, project, projects, versions, Version}, config::Cfg, data::{modification::{AddMod, IDSelector}, project::ProjectInfo}, db::{ lists_get_all_ids, mods_get_id, mods_get_info, mods_insert, mods_remove, userlist_get_all_ids, userlist_get_current_version, userlist_insert, userlist_remove, - }, - error::{EType, MLErr, MLE}, - files::{delete_version, download_versions}, - modrinth::{ - extract_current_version, get_raw_versions, project, projects, versions, - Version, - }, - List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION, + }, error::{EType, MLErr, MLE}, files::{delete_version, download_versions}, List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION }; -#[derive(Debug)] -pub struct AddMod { - pub id: IDSelector, - pub set_version: bool, -} - -#[derive(Debug, PartialEq, Eq)] -pub enum IDSelector { - ModificationID(String), - VersionID(String), -} - -#[derive(Debug, Clone)] -pub struct ProjectInfo { - pub mod_id: String, - pub slug: String, - pub title: String, - pub current_version: Option, - pub applicable_versions: Vec, - pub download_link: String, - pub set_version: bool, -} - /// # Errors pub async fn mod_add( config: &Cfg, diff --git a/src/commands/update.rs b/src/commands/update.rs index f83030d..721ced5 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -1,18 +1,13 @@ use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use crate::{ - config::Cfg, - db::{ + apis::modrinth::{extract_current_version, versions, Version}, config::Cfg, data::list::List, db::{ mods_get_info, userlist_change_versions, userlist_get_all_ids, userlist_get_applicable_versions, userlist_get_current_version, userlist_get_set_version, - }, - error::{EType, MLErr, MLE}, - files::{ + }, error::{EType, MLErr, MLE}, files::{ clean_list_dir, delete_version, disable_version, download_versions, - }, - modrinth::{extract_current_version, versions, Version}, - List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION, + }, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION }; /// # Errors diff --git a/src/config.rs b/src/config.rs index 8ecdc69..8312d15 100644 --- a/src/config.rs +++ b/src/config.rs @@ -7,10 +7,7 @@ use std::{ use serde::{Deserialize, Serialize}; use crate::{ - check_game_versions, - db::setup, - error::{EType, MLErr, MLE}, - Modloader, VersionLevel, + data::{gameversion::{check_game_versions, VersionLevel}, modloader::Modloader}, db::setup, error::{EType, MLErr, MLE} }; #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/src/data.rs b/src/data.rs new file mode 100644 index 0000000..cff0f47 --- /dev/null +++ b/src/data.rs @@ -0,0 +1,13 @@ +pub mod list; +pub mod gameversion; +pub mod modloader; +pub mod project; +pub mod modification; + +pub static STYLE_BAR_BYTE: &str = + "{spinner:.green}{wide_msg}{bytes}/{total_bytes} [{bar:.green/lime}]"; +pub static STYLE_BAR_POS: &str = " {wide_msg}{pos}/{len} [{bar:.green/lime}]"; +pub static STYLE_SPINNER: &str = "{spinner:.green}{wide_msg}"; +pub static STYLE_OPERATION: &str = " {wide_msg}"; +pub static STYLE_MESSAGE: &str = "{wide_msg}"; +pub static PROGRESS_CHARS: &str = "#>-"; diff --git a/src/data/gameversion.rs b/src/data/gameversion.rs new file mode 100644 index 0000000..3868502 --- /dev/null +++ b/src/data/gameversion.rs @@ -0,0 +1,118 @@ +use std::{ + fs::{self, remove_file, File}, + io::{Read, Write}, + time::Duration, +}; + +use apis::modrinth::{get_game_versions, GameVersion, GameVersionType}; +use error::{EType, MLErr, MLE}; +use indicatif::{ProgressBar, ProgressStyle}; +use serde::{Deserialize, Serialize}; + +use crate::{apis, error, STYLE_MESSAGE}; + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub enum VersionLevel { + #[serde(rename(serialize = "release", deserialize = "release"))] + Release, + #[serde(rename(serialize = "snapshot", deserialize = "snapshot"))] + Snapshot, + Version(String), +} + +/// Checks if update needed (time) +/// if yes: get versions, update +/// # Errors +pub async fn check_game_versions(path: &str, force: bool) -> MLE<()> { + let p = ProgressBar::new(1); + p.set_style(ProgressStyle::with_template(STYLE_MESSAGE).map_err(|_| { + MLErr::new(EType::LibIndicatif, "template error") + })?); + p.set_message("Update minecraft versions"); + + let creation_time = fs::metadata(path)?.created()?; + if !force + && creation_time.elapsed().map_err(|_| MLErr::new(EType::LibIndicatif, "SystemTimeError"))? < Duration::from_secs(60 * 60 * 24) + { + return Ok(()); + } + + let versions = get_game_versions().await?; + remove_file(path)?; + let mut file = File::create(path)?; + file.write_all(serde_json::to_string_pretty(&versions)?.as_bytes())?; + + p.finish_with_message("Updated minecraft versions"); + Ok(()) +} + +/// Loads game versions from file +/// # Errors +pub fn load_game_versions(path: &str) -> MLE> { + let mut file = File::open(path)?; + let mut data = String::new(); + file.read_to_string(&mut data)?; + let versions: Vec = serde_json::from_str(&data)?; + Ok(versions) +} + +impl VersionLevel { + pub fn from(str: &str) -> Self { + match str { + "release" => VersionLevel::Release, + "snapshot" => VersionLevel::Snapshot, + _ => VersionLevel::Version(String::from(str)), + } + } + + /// . + /// + /// Panics if . + /// # Errors + pub async fn get( + self, + versions_path: &str, + force_update: bool, + ) -> MLE { + let path = format!("{versions_path}/versions.json"); + check_game_versions(&path, force_update).await?; + let mut versions = load_game_versions(&path)?.into_iter(); + + match self { + VersionLevel::Release => { + if let Some(release) = versions + .find(|ver| ver.version_type == GameVersionType::release) + { + Ok(release.version) + } else { + Err(MLErr::new( + EType::Other, + "no minecraft release version found", + )) + } + } + VersionLevel::Snapshot => { + if let Some(snapshot) = versions + .find(|ver| ver.version_type == GameVersionType::snapshot) + { + Ok(snapshot.version) + } else { + Err(MLErr::new( + EType::Other, + "no minecraft snapshot version found", + )) + } + } + VersionLevel::Version(v) => { + if versions.any(|ver| ver.version == v) { + Ok(v) + } else { + Err(MLErr::new( + EType::ConfigError, + "unknown minecraft version", + )) + } + } + } + } +} diff --git a/src/data/list.rs b/src/data/list.rs new file mode 100644 index 0000000..0045b7a --- /dev/null +++ b/src/data/list.rs @@ -0,0 +1,19 @@ +use crate::{config::Cfg, db::{config_get_current_list, lists_get}, error::MLE}; + +use super::modloader::Modloader; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct List { + pub id: String, + pub mc_version: String, + pub modloader: Modloader, + pub download_folder: String, +} + +impl List { + /// # Errors + pub fn get_current_list(config: &Cfg) -> MLE { + let id = config_get_current_list(config)?; + lists_get(config, &id) + } +} diff --git a/src/data/modification.rs b/src/data/modification.rs new file mode 100644 index 0000000..84047ff --- /dev/null +++ b/src/data/modification.rs @@ -0,0 +1,11 @@ +#[derive(Debug)] +pub struct AddMod { + pub id: IDSelector, + pub set_version: bool, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum IDSelector { + ModificationID(String), + VersionID(String), +} diff --git a/src/data/modloader.rs b/src/data/modloader.rs new file mode 100644 index 0000000..050213f --- /dev/null +++ b/src/data/modloader.rs @@ -0,0 +1,39 @@ +use std::fmt::Display; + +use serde::{Deserialize, Serialize}; + +use crate::error::{EType, MLErr, MLE}; + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +pub enum Modloader { + #[serde(rename(serialize = "fabric", deserialize = "fabric"))] + Fabric, + #[serde(rename(serialize = "forge", deserialize = "forge"))] + Forge, + #[serde(rename(serialize = "quilt", deserialize = "quilt"))] + Quilt, +} + +impl Modloader { + /// # Errors + pub fn from(string: &str) -> MLE { + match string { + "forge" => Ok(Modloader::Forge), + "fabric" => Ok(Modloader::Fabric), + "quilt" => Ok(Modloader::Quilt), + _ => { + Err(MLErr::new(EType::ArgumentError, "UNKNOWN_MODLOADER")) + } + } + } +} + +impl Display for Modloader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Modloader::Fabric => write!(f, "fabric"), + Modloader::Forge => write!(f, "forge"), + Modloader::Quilt => write!(f, "quilt"), + } + } +} diff --git a/src/data/project.rs b/src/data/project.rs new file mode 100644 index 0000000..9807867 --- /dev/null +++ b/src/data/project.rs @@ -0,0 +1,12 @@ +use crate::apis::modrinth::Version; + +#[derive(Debug, Clone)] +pub struct ProjectInfo { + pub mod_id: String, + pub slug: String, + pub title: String, + pub current_version: Option, + pub applicable_versions: Vec, + pub download_link: String, + pub set_version: bool, +} diff --git a/src/db.rs b/src/db.rs index b150023..168cbbe 100644 --- a/src/db.rs +++ b/src/db.rs @@ -4,8 +4,8 @@ use rusqlite::Connection; use crate::{ config::Cfg, + data::{list::List, modloader::Modloader}, error::{EType, MLErr, MLE}, - List, Modloader, }; //MODS diff --git a/src/files.rs b/src/files.rs index 636c934..98785fd 100644 --- a/src/files.rs +++ b/src/files.rs @@ -10,12 +10,7 @@ use std::{ use tokio::task::JoinSet; use crate::{ - cache::{copy_cached_version, get_cached_versions}, - config::Cfg, - db::{mods_get_info, userlist_add_disabled_versions}, - error::{EType, MLErr, MLE}, - modrinth::Version, - List, PROGRESS_CHARS, STYLE_BAR_BYTE, STYLE_BAR_POS, STYLE_SPINNER, + apis::modrinth::Version, cache::{copy_cached_version, get_cached_versions}, config::Cfg, data::list::List, db::{mods_get_info, userlist_add_disabled_versions}, error::{EType, MLErr, MLE}, PROGRESS_CHARS, STYLE_BAR_BYTE, STYLE_BAR_POS, STYLE_SPINNER }; /// # Errors diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index be63ff8..0000000 --- a/src/lib.rs +++ /dev/null @@ -1,170 +0,0 @@ -pub mod apis; -pub mod cache; -pub mod commands; -pub mod config; -pub mod db; -pub mod error; -pub mod files; - -use std::{ - fmt::Display, - fs::{self, remove_file, File}, - io::{Read, Write}, - time::Duration, -}; - -use apis::modrinth::{get_game_versions, GameVersion, GameVersionType}; -pub use apis::*; -pub use commands::*; -use error::{EType, MLErr, MLE}; -use indicatif::{ProgressBar, ProgressStyle}; -use serde::{Deserialize, Serialize}; - -pub static STYLE_BAR_BYTE: &str = - "{spinner:.green}{wide_msg}{bytes}/{total_bytes} [{bar:.green/lime}]"; -pub static STYLE_BAR_POS: &str = " {wide_msg}{pos}/{len} [{bar:.green/lime}]"; -pub static STYLE_SPINNER: &str = "{spinner:.green}{wide_msg}"; -pub static STYLE_OPERATION: &str = " {wide_msg}"; -pub static STYLE_MESSAGE: &str = "{wide_msg}"; -pub static PROGRESS_CHARS: &str = "#>-"; - -#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] -pub enum Modloader { - #[serde(rename(serialize = "fabric", deserialize = "fabric"))] - Fabric, - #[serde(rename(serialize = "forge", deserialize = "forge"))] - Forge, - #[serde(rename(serialize = "quilt", deserialize = "quilt"))] - Quilt, -} - -impl Modloader { - /// # Errors - pub fn from(string: &str) -> MLE { - match string { - "forge" => Ok(Modloader::Forge), - "fabric" => Ok(Modloader::Fabric), - "quilt" => Ok(Modloader::Quilt), - _ => { - Err(MLErr::new(EType::ArgumentError, "UNKNOWN_MODLOADER")) - } - } - } -} - -impl Display for Modloader { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Modloader::Fabric => write!(f, "fabric"), - Modloader::Forge => write!(f, "forge"), - Modloader::Quilt => write!(f, "quilt"), - } - } -} - -#[derive(Debug, Clone, Deserialize, Serialize)] -pub enum VersionLevel { - #[serde(rename(serialize = "release", deserialize = "release"))] - Release, - #[serde(rename(serialize = "snapshot", deserialize = "snapshot"))] - Snapshot, - Version(String), -} - -/// Checks if update needed (time) -/// if yes: get versions, update -/// # Errors -pub async fn check_game_versions(path: &str, force: bool) -> MLE<()> { - let p = ProgressBar::new(1); - p.set_style(ProgressStyle::with_template(STYLE_MESSAGE).map_err(|_| { - MLErr::new(EType::LibIndicatif, "template error") - })?); - p.set_message("Update minecraft versions"); - - let creation_time = fs::metadata(path)?.created()?; - if !force - && creation_time.elapsed().map_err(|_| MLErr::new(EType::LibIndicatif, "SystemTimeError"))? < Duration::from_secs(60 * 60 * 24) - { - return Ok(()); - } - - let versions = get_game_versions().await?; - remove_file(path)?; - let mut file = File::create(path)?; - file.write_all(serde_json::to_string_pretty(&versions)?.as_bytes())?; - - p.finish_with_message("Updated minecraft versions"); - Ok(()) -} - -/// Loads game versions from file -/// # Errors -pub fn load_game_versions(path: &str) -> MLE> { - let mut file = File::open(path)?; - let mut data = String::new(); - file.read_to_string(&mut data)?; - let versions: Vec = serde_json::from_str(&data)?; - Ok(versions) -} - -impl VersionLevel { - #[must_use] - pub fn from(str: &str) -> Self { - match str { - "release" => VersionLevel::Release, - "snapshot" => VersionLevel::Snapshot, - _ => VersionLevel::Version(String::from(str)), - } - } - - /// . - /// - /// Panics if . - /// # Errors - pub async fn get( - self, - versions_path: &str, - force_update: bool, - ) -> MLE { - let path = format!("{versions_path}/versions.json"); - check_game_versions(&path, force_update).await?; - let mut versions = load_game_versions(&path)?.into_iter(); - - match self { - VersionLevel::Release => { - if let Some(release) = versions - .find(|ver| ver.version_type == GameVersionType::release) - { - Ok(release.version) - } else { - Err(MLErr::new( - EType::Other, - "no minecraft release version found", - )) - } - } - VersionLevel::Snapshot => { - if let Some(snapshot) = versions - .find(|ver| ver.version_type == GameVersionType::snapshot) - { - Ok(snapshot.version) - } else { - Err(MLErr::new( - EType::Other, - "no minecraft snapshot version found", - )) - } - } - VersionLevel::Version(v) => { - if versions.any(|ver| ver.version == v) { - Ok(v) - } else { - Err(MLErr::new( - EType::ConfigError, - "unknown minecraft version", - )) - } - } - } - } -} diff --git a/src/main.rs b/src/main.rs index a1f0c31..038e2f4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,20 @@ use clap::{Parser, Subcommand}; -use modlist::{ - config::Cfg, - db::{config_get_current_list, lists_get, lists_get_all_ids}, - download, - error::MLE, - export, import, mod_add, mod_remove, update, AddMod, IDSelector, - List, Modloader, VersionLevel, -}; + +pub mod apis; +pub mod cache; +pub mod commands; +pub mod config; +pub mod db; +pub mod error; +pub mod files; +pub mod data; + +use commands::{download::download, io::{export, import}, list, modification::{mod_add, mod_remove}, update::update}; +use config::Cfg; +use data::{gameversion::VersionLevel, list::List, modification::{AddMod, IDSelector}, modloader::Modloader}; +pub use data::{STYLE_BAR_POS, STYLE_MESSAGE, STYLE_SPINNER, STYLE_BAR_BYTE, STYLE_OPERATION, PROGRESS_CHARS}; +use db::{config_get_current_list, lists_get, lists_get_all_ids}; +use error::MLE; #[derive(Parser)] #[command(author, version, about)] @@ -308,16 +316,16 @@ async fn handle_list( .unwrap(), }; - List::add(&config, &id, &ver, &ml, &directory) + list::add(&config, &id, &ver, &ml, &directory) } - ListCommands::Remove { id } => List::remove(&config, &id), - ListCommands::List => List::list(&config), - ListCommands::Change { id } => List::change(&config, &id), + ListCommands::Remove { id } => list::remove(&config, &id), + ListCommands::List => list::list(&config), + ListCommands::Change { id } => list::change(&config, &id), ListCommands::Version { id, version, download, remove, - } => List::version(&config, &id, version, download, remove).await, + } => list::version(&config, &id, version, download, remove).await, } } -- cgit v1.2.3