From 6a91d0a864f9edd9d9fe50ca89ccbce4fc98e043 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Wed, 4 Sep 2024 11:12:04 +0200 Subject: do nearly anything to shut clippy up --- src/apis/modrinth.rs | 18 +++- src/commands/download.rs | 30 +++--- src/commands/io.rs | 24 ++++- src/commands/list.rs | 33 +++++-- src/commands/modification.rs | 57 ++++++----- src/commands/update.rs | 39 ++++---- src/config.rs | 13 +-- src/db.rs | 222 ++++++++++++++++++++++++------------------- src/error.rs | 70 +++++++------- src/files.rs | 66 +++++++------ src/lib.rs | 52 +++++++--- src/main.rs | 13 ++- 12 files changed, 385 insertions(+), 252 deletions(-) (limited to 'src') diff --git a/src/apis/modrinth.rs b/src/apis/modrinth.rs index 5366f3d..75e65e6 100644 --- a/src/apis/modrinth.rs +++ b/src/apis/modrinth.rs @@ -3,7 +3,7 @@ use reqwest::Client; use serde::{Deserialize, Serialize}; use crate::{ - error::{ErrorType, MLError, MLE}, + error::{EType, MLErr, MLE}, List, }; @@ -130,6 +130,8 @@ pub enum GameVersionType { beta, } +/// # Errors +/// # Panics async fn get( api: &str, path: &str, @@ -153,6 +155,8 @@ async fn get( Ok(data) } +/// # Errors +/// # Panics pub async fn project(api: &str, name: &str) -> Project { let url = format!("project/{name}"); let data = get(api, &url).await.unwrap().unwrap(); @@ -160,6 +164,8 @@ pub async fn project(api: &str, name: &str) -> Project { serde_json::from_slice(&data).unwrap() } +/// # Errors +/// # Panics pub async fn projects(api: &str, ids: Vec) -> Vec { let all = ids.join(r#"",""#); let url = format!(r#"projects?ids=["{all}"]"#); @@ -170,6 +176,8 @@ pub async fn projects(api: &str, ids: Vec) -> Vec { } ///Get applicable versions from `mod_id` with list context +/// # Errors +/// # Panics pub async fn versions(api: &str, id: String, list: List) -> Vec { let url = format!( r#"project/{}/version?loaders=["{}"]&game_versions=["{}"]"#, @@ -185,6 +193,8 @@ pub async fn versions(api: &str, id: String, list: List) -> Vec { } ///Get version with the version ids +/// # Errors +/// # Panics pub async fn get_raw_versions( api: &str, versions: Vec, @@ -196,9 +206,10 @@ pub async fn get_raw_versions( serde_json::from_slice(&data).unwrap() } +/// # Errors pub fn extract_current_version(versions: Vec) -> MLE { match versions.len() { - 0 => Err(MLError::new(ErrorType::ModError, "NO_VERSIONS_AVAILABLE")), + 0 => Err(MLErr::new(EType::ModError, "NO_VERSIONS_AVAILABLE")), 1.. => { let mut times: Vec<(String, DateTime)> = vec![]; for ver in versions { @@ -209,10 +220,11 @@ pub fn extract_current_version(versions: Vec) -> MLE { times.reverse(); Ok(times[0].0.to_string()) } - _ => panic!("available_versions should never be negative"), } } +/// # Errors +/// # Panics pub async fn get_game_versions() -> Vec { let data = get("https://api.modrinth.com/v2/", "tag/game_version") .await diff --git a/src/commands/download.rs b/src/commands/download.rs index 3e50c87..7321832 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -1,9 +1,11 @@ +#![allow(clippy::too_many_lines)] + use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use crate::{config::Cfg, List}; use crate::{ db::userlist_get_all_current_versions_with_mods, - error::{ErrorType, MLError, MLE}, + error::{EType, MLErr, MLE}, files::{ clean_list_dir, delete_version, disable_version, download_versions, get_downloaded_versions, @@ -12,6 +14,8 @@ use crate::{ }; use crate::{PROGRESS_CHARS, STYLE_BAR_POS}; +/// # Errors +/// # Panics pub async fn download( config: &Cfg, liststack: Vec, @@ -31,15 +35,15 @@ pub async fn download( download_p.set_message(format!("Download in {}", current_list.id)); let downloaded_versions = - get_downloaded_versions(current_list.clone())?; + get_downloaded_versions(¤t_list)?; let current_version_ids = match userlist_get_all_current_versions_with_mods( config, - String::from(¤t_list.id), + ¤t_list.id, ) { Ok(i) => Ok(i), - Err(e) => Err(MLError::new( - ErrorType::DBError, + Err(e) => Err(MLErr::new( + EType::DBError, e.to_string().as_str(), )), }?; @@ -74,7 +78,12 @@ pub async fn download( clean_list_dir(¤t_list)?; }; - if !to_download.is_empty() { + if to_download.is_empty() { + download_p.println(format!( + "There are no new versions to download for {}", + current_list.id + )); + } else { download_versions( current_list.clone(), config.clone(), @@ -83,11 +92,6 @@ pub async fn download( &download_p, ) .await?; - } else { - download_p.println(format!( - "There are no new versions to download for {}", - current_list.id - )); } if !to_disable.is_empty() { @@ -104,13 +108,13 @@ pub async fn download( if delete_old { d_p.set_message(format!("Delete version {}", ver.1)); d_p.inc(1); - delete_version(¤t_list, ver.1)?; + delete_version(¤t_list, &ver.1)?; } else { d_p.set_message(format!("Disable version {}", ver.1)); d_p.inc(1); disable_version( config, - current_list.clone(), + ¤t_list, ver.1, ver.0, )?; diff --git a/src/commands/io.rs b/src/commands/io.rs index 1d17f7c..c9691c4 100644 --- a/src/commands/io.rs +++ b/src/commands/io.rs @@ -9,7 +9,7 @@ use crate::{ lists_get, lists_get_all_ids, lists_insert, userlist_get_all_ids, userlist_get_current_version, userlist_get_set_version, }, - error::MLE, + error::{EType, MLErr, MLE}, mod_add, AddMod, IDSelector, List, Modloader, STYLE_OPERATION, }; @@ -67,15 +67,26 @@ impl ExportList { } } +/// # Errors +/// # Panics pub fn export(config: &Cfg, list: Option) -> MLE<()> { let progress = ProgressBar::new_spinner(); - progress.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + progress.set_style( + ProgressStyle::with_template(STYLE_OPERATION) + .map_err(|_| MLErr::new(EType::LibIndicatif, "template error"))?, + ); let mut list_ids: Vec = vec![]; if list.is_none() { list_ids = lists_get_all_ids(config)?; } else { - list_ids.push(lists_get(config, &list.unwrap())?.id); + list_ids.push( + lists_get( + config, + &list.ok_or(MLErr::new(EType::Other, "nolist"))?, + )? + .id, + ); } let mut lists: Vec = vec![]; @@ -88,7 +99,7 @@ pub fn export(config: &Cfg, list: Option) -> MLE<()> { let toml = toml::to_string(&Export { lists })?; let filestr = dirs::home_dir() - .unwrap() + .ok_or(MLErr::new(EType::Other, "no home"))? .join("mlexport.toml") .into_os_string() .into_string() @@ -102,6 +113,7 @@ pub fn export(config: &Cfg, list: Option) -> MLE<()> { Ok(()) } +/// # Errors pub async fn import( config: &Cfg, file_str: &str, @@ -117,7 +129,9 @@ pub async fn import( id: exportlist.id, mc_version: exportlist.mc_version, modloader: Modloader::from(&exportlist.launcher)?, - download_folder: exportlist.download_folder.ok_or("NO_DL").unwrap(), + download_folder: exportlist + .download_folder + .ok_or(MLErr::new(EType::Other, "NO_DL"))?, }; lists_insert( config, diff --git a/src/commands/list.rs b/src/commands/list.rs index 63105cf..47c1dc6 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -1,3 +1,4 @@ +#![allow(clippy::module_name_repetitions)] use indicatif::{ProgressBar, ProgressStyle}; use crate::{ @@ -6,7 +7,7 @@ use crate::{ config_change_current_list, config_get_current_list, lists_get, lists_get_all_ids, lists_insert, lists_remove, lists_version, }, - error::{ErrorType, MLError, MLE}, + error::{EType, MLErr, MLE}, update, Modloader, STYLE_OPERATION, }; @@ -18,11 +19,13 @@ pub struct List { pub download_folder: String, } +/// # Errors pub fn get_current_list(config: &Cfg) -> MLE { let id = config_get_current_list(config)?; lists_get(config, &id) } +/// # Errors pub fn list_add( config: &Cfg, id: &str, @@ -31,20 +34,27 @@ pub fn list_add( directory: &str, ) -> MLE<()> { let p = ProgressBar::new_spinner(); - p.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + 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 list_change(config: &Cfg, id: &str) -> MLE<()> { let p = ProgressBar::new_spinner(); - p.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + 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(MLError::new(ErrorType::ArgumentError, "List not found")); + return Err(MLErr::new(EType::ArgumentError, "List not found")); }; config_change_current_list(config, id)?; @@ -52,9 +62,13 @@ pub fn list_change(config: &Cfg, id: &str) -> MLE<()> { Ok(()) } +/// # Errors pub fn list_remove(config: &Cfg, id: &str) -> MLE<()> { let p = ProgressBar::new_spinner(); - p.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + 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}")); @@ -67,6 +81,7 @@ pub fn list_remove(config: &Cfg, id: &str) -> MLE<()> { /// /// * `config` - The current config /// * `args` - All args, to extract the new version +/// # Errors pub async fn list_version( config: &Cfg, id: &str, @@ -75,7 +90,10 @@ pub async fn list_version( delete: bool, ) -> MLE<()> { let p = ProgressBar::new_spinner(); - p.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + 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}" )); @@ -90,7 +108,8 @@ pub async fn list_version( update(config, vec![list], true, download, delete).await } -pub fn list_list(config: &Cfg) -> MLE<()> { +/// # Errors +pub fn list_lists(config: &Cfg) -> MLE<()> { let lists = lists_get_all_ids(config)?; for list in lists { let l = lists_get(config, &list)?; diff --git a/src/commands/modification.rs b/src/commands/modification.rs index e0e54b2..6e6213f 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -1,3 +1,5 @@ +#![allow(clippy::too_many_lines)] + use std::collections::HashMap; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; @@ -9,7 +11,7 @@ use crate::{ mods_remove, userlist_get_all_ids, userlist_get_current_version, userlist_insert, userlist_remove, }, - error::{ErrorType, MLError, MLE}, + error::{EType, MLErr, MLE}, files::{delete_version, download_versions}, modrinth::{ extract_current_version, get_raw_versions, project, projects, versions, @@ -41,6 +43,8 @@ pub struct ProjectInfo { pub set_version: bool, } +/// # Errors +/// # Panics pub async fn mod_add( config: &Cfg, mods: Vec, @@ -52,10 +56,11 @@ pub async fn mod_add( let mut mod_ids: Vec<(String, bool)> = Vec::new(); let mut ver_ids: Vec<(String, bool)> = Vec::new(); - let add_p = mp.add(ProgressBar::new(mods.len().try_into().unwrap())); + let add_p = mp.add(ProgressBar::new(mods.len().try_into().map_err(|_| MLErr::new(EType::Other, "MODSLENTRY"))?)); add_p.set_style( - ProgressStyle::with_template(STYLE_BAR_POS) - .unwrap() + ProgressStyle::with_template(STYLE_BAR_POS).map_err(|_| { + MLErr::new(EType::LibIndicatif, "template error") + })? .progress_chars(PROGRESS_CHARS), ); add_p.set_message("Sort ids"); @@ -83,7 +88,7 @@ pub async fn mod_add( }; if projectinfo.is_empty() { - return Err(MLError::new(ErrorType::ArgumentError, "NO_IDS?")); + return Err(MLErr::new(EType::ArgumentError, "NO_IDS?")); }; add_p.set_message("Add mods to database"); @@ -115,7 +120,7 @@ pub async fn mod_add( &list.id, &project.mod_id, ¤t_version_id, - project.clone().applicable_versions, + &project.applicable_versions, &project.download_link, project.set_version, ) { @@ -125,8 +130,8 @@ pub async fn mod_add( list.id ); if e.to_string() == expected_err { - Err(MLError::new( - ErrorType::ModError, + Err(MLErr::new( + EType::ModError, "MOD_ALREADY_ON_SELECTED_LIST", )) } else { @@ -212,7 +217,20 @@ async fn get_mod_infos( let mut available_versions_vec: Vec = Vec::new(); let current_version: Option; let file: String; - if !available_versions.is_empty() { + if available_versions.is_empty() { + current_version = None; + file = String::from("NONE"); + available_versions_vec.push(String::from("NONE")); + projectinfo.push(ProjectInfo { + mod_id: String::from(&project.id), + slug: project.slug, + title: project.title, + current_version, + applicable_versions: available_versions_vec, + download_link: file, + set_version: *setmap.get(&project.id).unwrap(), + }); + } else { let current_id = extract_current_version(available_versions.clone())?; @@ -246,19 +264,6 @@ async fn get_mod_infos( download_link: file, set_version: *setmap.get(&project.slug).unwrap(), }); - } else { - current_version = None; - file = String::from("NONE"); - available_versions_vec.push(String::from("NONE")); - projectinfo.push(ProjectInfo { - mod_id: String::from(&project.id), - slug: project.slug, - title: project.title, - current_version, - applicable_versions: available_versions_vec, - download_link: file, - set_version: *setmap.get(&project.id).unwrap(), - }); } } @@ -319,9 +324,13 @@ async fn get_ver_info( /// * `config` - config struct /// * `id` - name, slug or id of the mod /// * `list` - List struct +/// +/// # Errors pub fn mod_remove(config: &Cfg, id: &str, list: &List) -> MLE<()> { let progress = ProgressBar::new_spinner(); - progress.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + progress.set_style(ProgressStyle::with_template(STYLE_OPERATION).map_err(|_| { + MLErr::new(EType::LibIndicatif, "template error") + })?); let mod_id = mods_get_id(&config.data, id)?; @@ -334,7 +343,7 @@ pub fn mod_remove(config: &Cfg, id: &str, list: &List) -> MLE<()> { userlist_remove(config, &list.id, &mod_id)?; progress.set_message("Delete file"); - match delete_version(list, version) { + match delete_version(list, &version) { Ok(()) => (), Err(err) => { if err.to_string() diff --git a/src/commands/update.rs b/src/commands/update.rs index c19c02c..d0b930d 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -1,3 +1,5 @@ +#![allow(clippy::too_many_lines)] + use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use crate::{ @@ -7,7 +9,7 @@ use crate::{ userlist_get_applicable_versions, userlist_get_current_version, userlist_get_set_version, }, - error::{ErrorType, MLError, MLE}, + error::{EType, MLErr, MLE}, files::{ clean_list_dir, delete_version, disable_version, download_versions, }, @@ -15,6 +17,8 @@ use crate::{ List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION, }; +/// # Errors +/// # Panics pub async fn update( config: &Cfg, liststack: Vec, @@ -24,11 +28,15 @@ pub async fn update( ) -> MLE<()> { let mp = MultiProgress::new(); - let update_p = - mp.add(ProgressBar::new(liststack.len().try_into().unwrap())); + let update_p = mp.add(ProgressBar::new( + liststack + .len() + .try_into() + .map_err(|_| MLErr::new(EType::Other, "ListStackLen"))?, + )); update_p.set_style( ProgressStyle::with_template(STYLE_BAR_POS) - .unwrap() + .map_err(|_| MLErr::new(EType::LibIndicatif, "template error"))? .progress_chars(PROGRESS_CHARS), ); @@ -133,16 +141,11 @@ pub async fn update( if delete_old { d_p.set_message(format!("Delete version {}", ver.0)); d_p.inc(1); - delete_version(¤t_list, ver.0)?; + delete_version(¤t_list, &ver.0)?; } else if ver.0 != "NONE" { d_p.set_message(format!("Disable version {}", ver.0)); d_p.inc(1); - disable_version( - config, - current_list.clone(), - ver.0, - ver.1, - )?; + disable_version(config, ¤t_list, ver.0, ver.1)?; }; } @@ -176,12 +179,12 @@ async fn specific_update( let mut versions: Vec = vec![]; - if !applicable_versions.is_empty() { + if applicable_versions.is_empty() { + versions.push(String::from("NONE")); + } else { for ver in &applicable_versions { versions.push(String::from(&ver.id)); } - } else { - versions.push(String::from("NONE")); } let mut current: Vec = vec![]; @@ -189,7 +192,7 @@ async fn specific_update( || (versions.join("|") != userlist_get_applicable_versions( config, - String::from(&list.id), + &list.id, String::from(id), )?) { @@ -209,7 +212,7 @@ async fn specific_update( .ok_or("!no current version in applicable_versions") { Ok(v) => Ok(v), - Err(e) => Err(MLError::new(ErrorType::Other, e)), + Err(e) => Err(MLErr::new(EType::Other, e)), }?; current.push(current_ver.clone()); @@ -223,7 +226,7 @@ async fn specific_update( userlist_change_versions( config, - list.id, + &list.id, current_str, versions.join("|"), link, @@ -232,7 +235,7 @@ async fn specific_update( } if current.is_empty() { - return Err(MLError::new(ErrorType::ModError, "NO_UPDATE_AVAILABLE")); + return Err(MLErr::new(EType::ModError, "NO_UPDATE_AVAILABLE")); }; Ok(current[0].clone()) diff --git a/src/config.rs b/src/config.rs index 3538a69..6280932 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,7 +8,7 @@ use indicatif::{ProgressBar, ProgressStyle}; use serde::{Deserialize, Serialize}; use crate::{ - check_game_versions, db::db_setup, error::MLE, Modloader, VersionLevel, + check_game_versions, db::setup, error::{EType, MLErr, MLE}, Modloader, VersionLevel, }; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -32,11 +32,12 @@ pub struct Defaults { } impl Cfg { + /// # Errors pub async fn init(path: Option) -> MLE { let configfile = match path.clone() { Some(p) => p, None => dirs::config_dir() - .unwrap() + .ok_or(MLErr::new(EType::Other, "config_dir"))? .join("modlist") .join("config.toml") .to_string_lossy() @@ -70,8 +71,8 @@ impl Cfg { }; //Check versions let versionfile = format!("{}/versions.json", config.versions); - if let Ok(..) = File::open(&versionfile) { } else { - create_versions_dummy(&versionfile).await?; + if File::open(&versionfile).is_err() { + create_versions_dummy(&versionfile)?; check_game_versions(&versionfile, true).await?; } @@ -114,7 +115,7 @@ fn create_database(path: &str) -> MLE<()> { p.set_message("Create database"); File::create(path)?; - db_setup(path)?; + setup(path)?; p.finish_with_message(format!("Created database ({path})")); Ok(()) } @@ -129,7 +130,7 @@ fn create_cache(path: &str) -> MLE<()> { Ok(()) } -async fn create_versions_dummy(path: &str) -> MLE<()> { +fn create_versions_dummy(path: &str) -> MLE<()> { let p = ProgressBar::new(1); p.set_style(ProgressStyle::with_template("{wide_msg}").unwrap()); p.set_message("Create version file"); diff --git a/src/db.rs b/src/db.rs index 6a3c9af..b150023 100644 --- a/src/db.rs +++ b/src/db.rs @@ -4,11 +4,12 @@ use rusqlite::Connection; use crate::{ config::Cfg, - error::{ErrorType, MLError, MLE}, + error::{EType, MLErr, MLE}, List, Modloader, }; //MODS +/// # Errors pub fn mods_insert(config: &Cfg, id: &str, slug: &str, name: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -21,11 +22,12 @@ pub fn mods_insert(config: &Cfg, id: &str, slug: &str, name: &str) -> MLE<()> { Ok(()) } +/// # Errors pub fn mods_get_all_ids( config: &Cfg, ) -> Result, Box> { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut mods: Vec = Vec::new(); @@ -36,21 +38,22 @@ pub fn mods_get_all_ids( mods.push(id?); } - match mods.is_empty() { - true => Err(Box::new(Error::new(ErrorKind::NotFound, "NO_MODS_ALL"))), - false => Ok(mods), + if mods.is_empty() { + Err(Box::new(Error::new(ErrorKind::NotFound, "NO_MODS_ALL"))) + } else { + Ok(mods) } } -///Get mod id based on the slug or name -///# Arguments +/// Get mod id based on the slug or name +/// # Arguments /// ///* `data` - file directory of the database ///* `slug` - Slug or Name of a mod /// -///# Failure +/// # Errors /// -///Will return `MLError` when no mod id is found +/// Will return `MLError` when no mod id is found pub fn mods_get_id(data: &str, slug: &str) -> MLE { let data = format!("{data}/data.db"); let connection = Connection::open(data)?; @@ -88,7 +91,7 @@ pub fn mods_get_id(data: &str, slug: &str) -> MLE { } if mod_id.is_empty() { - return Err(MLError::new(ErrorType::DBError, "GI_MOD_NOT_FOUND")); + return Err(MLErr::new(EType::DBError, "GI_MOD_NOT_FOUND")); }; Ok(mod_id) @@ -99,6 +102,7 @@ pub struct ModInfo { pub title: String, } +/// # Errors pub fn mods_get_info(config: &Cfg, id: &str) -> MLE { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -121,12 +125,14 @@ pub fn mods_get_info(config: &Cfg, id: &str) -> MLE { }); } - match mod_info.is_none() { - true => Err(MLError::new(ErrorType::DBError, "GN_MOD_NOT_FOUND")), - false => Ok(mod_info.unwrap()), + if mod_info.is_none() { + Err(MLErr::new(EType::DBError, "GN_MOD_NOT_FOUND")) + } else { + Ok(mod_info.ok_or(MLErr::new(EType::Other, "mod_info"))?) } } +/// # Errors pub fn mods_remove(config: &Cfg, id: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -142,15 +148,16 @@ pub struct DBModlistVersions { pub versions: String, } +/// # Errors pub fn mods_get_versions( config: &Cfg, - mods: Vec, + mods: &[String], ) -> MLE> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; if mods.is_empty() { - return Err(MLError::new(ErrorType::ArgumentError, "MODS_NO_INPUT")); + return Err(MLErr::new(EType::ArgumentError, "MODS_NO_INPUT")); } let mut wherestr = String::from("WHERE"); @@ -182,35 +189,32 @@ pub fn mods_get_versions( }); } - match versionmaps.is_empty() { - true => Err(MLError::new(ErrorType::DBError, "MODS_MODS_NOT_FOUND")), - false => Ok(versionmaps), + if versionmaps.is_empty() { + Err(MLErr::new(EType::DBError, "MODS_MODS_NOT_FOUND")) + } else { + Ok(versionmaps) } } //userlist +/// # Errors pub fn userlist_insert( config: &Cfg, list_id: &str, mod_id: &str, current_version: &str, - applicable_versions: Vec, + applicable_versions: &[String], current_link: &str, set_version: bool, ) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; - let sv = match set_version { - true => "1", - false => "0", - }; + let sv = if set_version { "1" } else { "0" }; connection.execute( - format!( - "INSERT INTO {list_id} VALUES (?1, ?2, ?3, ?4, 'NONE', ?5)" - ) - .as_str(), + format!("INSERT INTO {list_id} VALUES (?1, ?2, ?3, ?4, 'NONE', ?5)") + .as_str(), [ mod_id, current_version, @@ -223,28 +227,31 @@ pub fn userlist_insert( Ok(()) } +/// # Errors pub fn userlist_get_all_ids(config: &Cfg, list_id: &str) -> MLE> { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut mod_ids: Vec = Vec::new(); - let mut stmt = connection - .prepare(format!("SELECT mod_id FROM {list_id}").as_str())?; + let mut stmt = + connection.prepare(format!("SELECT mod_id FROM {list_id}").as_str())?; let id_iter = stmt.query_map([], |row| row.get::(0))?; for id in id_iter { mod_ids.push(id?); } - match mod_ids.is_empty() { - true => Err(MLError::new( - ErrorType::DBError, + if mod_ids.is_empty() { + Err(MLErr::new( + EType::DBError, &format!("NO_MODS_USERLIST{list_id}"), - )), - false => Ok(mod_ids), + )) + } else { + Ok(mod_ids) } } +/// # Errors pub fn userlist_remove(config: &Cfg, list_id: &str, mod_id: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -256,20 +263,19 @@ pub fn userlist_remove(config: &Cfg, list_id: &str, mod_id: &str) -> MLE<()> { Ok(()) } +/// # Errors pub fn userlist_get_applicable_versions( config: &Cfg, - list_id: String, + list_id: &str, mod_id: String, ) -> MLE { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut version: String = String::new(); let mut stmt = connection.prepare( - format!( - "SELECT applicable_versions FROM {list_id} WHERE mod_id = ?" - ) - .as_str(), + format!("SELECT applicable_versions FROM {list_id} WHERE mod_id = ?") + .as_str(), )?; let ver_iter = stmt.query_map([mod_id], |row| row.get::(0))?; @@ -278,15 +284,17 @@ pub fn userlist_get_applicable_versions( version = ver?; } - match version.is_empty() { - true => Err(MLError::new(ErrorType::DBError, "GAV_MOD_NOT_FOUND")), - false => Ok(version), + if version.is_empty() { + Err(MLErr::new(EType::DBError, "GAV_MOD_NOT_FOUND")) + } else { + Ok(version) } } +/// # Errors pub fn userlist_get_all_applicable_versions_with_mods( config: &Cfg, - list_id: String, + list_id: &str, ) -> MLE> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -308,19 +316,20 @@ pub fn userlist_get_all_applicable_versions_with_mods( } if versions.is_empty() { - return Err(MLError::new(ErrorType::DBError, "NO_MODS_ON_LIST")); + return Err(MLErr::new(EType::DBError, "NO_MODS_ON_LIST")); }; Ok(versions) } +/// # Errors pub fn userlist_get_current_version( config: &Cfg, list_id: &str, mod_id: &str, ) -> MLE { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut version: String = String::new(); let mut stmt = connection.prepare( @@ -334,15 +343,17 @@ pub fn userlist_get_current_version( version = ver?; } - match version.is_empty() { - true => Err(MLError::new(ErrorType::DBError, "GCV_MOD_NOT_FOUND")), - false => Ok(version), + if version.is_empty() { + Err(MLErr::new(EType::DBError, "GCV_MOD_NOT_FOUND")) + } else { + Ok(version) } } +/// # Errors pub fn userlist_get_all_current_version_ids( config: &Cfg, - list_id: String, + list_id: &str, ) -> MLE> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -357,15 +368,16 @@ pub fn userlist_get_all_current_version_ids( } if versions.is_empty() { - return Err(MLError::new(ErrorType::DBError, "NO_MODS_ON_LIST")); + return Err(MLErr::new(EType::DBError, "NO_MODS_ON_LIST")); }; Ok(versions) } +/// # Errors pub fn userlist_get_all_current_versions_with_mods( config: &Cfg, - list_id: String, + list_id: &str, ) -> Result, Box> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -396,18 +408,18 @@ pub fn userlist_get_all_current_versions_with_mods( Ok(versions) } +/// # Errors pub fn userlist_get_set_version( config: &Cfg, list_id: &str, mod_id: &str, ) -> MLE { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut set_version: bool = false; let mut stmt = connection.prepare( - format!("SELECT set_version FROM {list_id} WHERE mod_id = ?") - .as_str(), + format!("SELECT set_version FROM {list_id} WHERE mod_id = ?").as_str(), )?; let ver_iter = stmt.query_map([&mod_id], |row| row.get::(0))?; @@ -419,9 +431,10 @@ pub fn userlist_get_set_version( Ok(set_version) } +/// # Errors pub fn userlist_change_versions( config: &Cfg, - list_id: String, + list_id: &str, current_version: String, versions: String, link: String, @@ -434,25 +447,22 @@ pub fn userlist_change_versions( Ok(()) } +/// # Errors pub fn userlist_add_disabled_versions( config: &Cfg, - list_id: String, + list_id: &str, disabled_version: String, mod_id: String, ) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; - let currently_disabled_versions = userlist_get_disabled_versions( - config, - String::from(&list_id), - String::from(&mod_id), - )?; - let disabled_versions = match currently_disabled_versions == "NONE" { - true => disabled_version, - false => { - format!("{currently_disabled_versions}|{disabled_version}") - } + let currently_disabled_versions = + userlist_get_disabled_versions(config, list_id, String::from(&mod_id))?; + let disabled_versions = if currently_disabled_versions == "NONE" { + disabled_version + } else { + format!("{currently_disabled_versions}|{disabled_version}") }; connection.execute( @@ -465,13 +475,14 @@ pub fn userlist_add_disabled_versions( Ok(()) } +/// # Errors pub fn userlist_get_disabled_versions( config: &Cfg, - list_id: String, + list_id: &str, mod_id: String, ) -> MLE { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut version: String = String::new(); let mut stmt = connection.prepare( @@ -485,23 +496,24 @@ pub fn userlist_get_disabled_versions( version = ver?; } - match version.is_empty() { - true => Err(MLError::new(ErrorType::DBError, "GDV_MOD_NOT_FOUND")), - false => Ok(version), + if version.is_empty() { + Err(MLErr::new(EType::DBError, "GDV_MOD_NOT_FOUND")) + } else { + Ok(version) } } +/// # Errors pub fn userlist_get_all_downloads( config: &Cfg, - list_id: String, + list_id: &str, ) -> Result, Box> { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut links: Vec = Vec::new(); - let mut stmt = connection.prepare( - format!("SELECT current_download FROM {list_id}").as_str(), - )?; + let mut stmt = connection + .prepare(format!("SELECT current_download FROM {list_id}").as_str())?; let link_iter = stmt.query_map([], |row| row.get::(0))?; for link in link_iter { @@ -521,6 +533,7 @@ pub fn userlist_get_all_downloads( //lists ///Inserts into lists table and creates new table +/// # Errors pub fn lists_insert( config: &Cfg, id: &str, @@ -540,6 +553,7 @@ pub fn lists_insert( Ok(()) } +/// # Errors pub fn lists_remove(config: &Cfg, id: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -549,9 +563,10 @@ pub fn lists_remove(config: &Cfg, id: &str) -> MLE<()> { Ok(()) } +/// # Errors pub fn lists_get(config: &Cfg, list_id: &str) -> MLE { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut list = List { id: String::new(), @@ -582,15 +597,16 @@ pub fn lists_get(config: &Cfg, list_id: &str) -> MLE { } if list.id.is_empty() { - return Err(MLError::new(ErrorType::DBError, "LIST_NOT_FOUND")); + return Err(MLErr::new(EType::DBError, "LIST_NOT_FOUND")); } Ok(list) } +/// # Errors pub fn lists_version(config: &Cfg, list_id: &str, version: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; connection.execute( "UPDATE lists SET mc_version = ? WHERE id = ?", @@ -599,9 +615,10 @@ pub fn lists_version(config: &Cfg, list_id: &str, version: &str) -> MLE<()> { Ok(()) } +/// # Errors pub fn lists_get_all_ids(config: &Cfg) -> MLE> { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut list_ids: Vec = Vec::new(); let mut stmt = connection.prepare("SELECT id FROM lists")?; @@ -611,13 +628,15 @@ pub fn lists_get_all_ids(config: &Cfg) -> MLE> { list_ids.push(id?); } - match list_ids.is_empty() { - true => Err(MLError::new(ErrorType::DBError, "NO_LISTS")), - false => Ok(list_ids), + if list_ids.is_empty() { + Err(MLErr::new(EType::DBError, "NO_LISTS")) + } else { + Ok(list_ids) } } //config +/// # Errors pub fn config_change_current_list(config: &Cfg, id: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -629,9 +648,10 @@ pub fn config_change_current_list(config: &Cfg, id: &str) -> MLE<()> { Ok(()) } +/// # Errors pub fn config_get_current_list(config: &Cfg) -> MLE { let data = format!("{}/data.db", config.data); - let connection = Connection::open(data).unwrap(); + let connection = Connection::open(data)?; let mut list_id = String::new(); let mut stmt = connection @@ -643,16 +663,17 @@ pub fn config_get_current_list(config: &Cfg) -> MLE { } if list_id.is_empty() { - return Err(MLError::new(ErrorType::DBError, "NO_CURRENT_LIST")); + return Err(MLErr::new(EType::DBError, "NO_CURRENT_LIST")); } Ok(list_id) } //SETUP(UPDATES) +/// # Errors pub fn s_userlist_update_download( config: &Cfg, - list_id: String, + list_id: &str, mod_id: String, link: String, ) -> Result<(), Box> { @@ -660,15 +681,14 @@ pub fn s_userlist_update_download( let connection = Connection::open(data)?; connection.execute( - format!( - "UPDATE {list_id} SET current_download = ?1 WHERE mod_id = ?2" - ) - .as_str(), + format!("UPDATE {list_id} SET current_download = ?1 WHERE mod_id = ?2") + .as_str(), [link, mod_id], )?; Ok(()) } +/// # Errors pub fn s_config_create_version( config: &Cfg, ) -> Result<(), Box> { @@ -682,6 +702,7 @@ pub fn s_config_create_version( Ok(()) } +/// # Errors pub fn s_config_update_version( config: &Cfg, ver: String, @@ -696,6 +717,7 @@ pub fn s_config_update_version( Ok(()) } +/// # Errors pub fn s_config_get_version( config: &Cfg, ) -> Result> { @@ -720,11 +742,12 @@ pub fn s_config_get_version( Ok(version) } +/// # Errors pub fn s_insert_column( config: &Cfg, - table: String, - column: String, - c_type: String, + table: &str, + column: &str, + c_type: &str, default: Option, ) -> Result<(), Box> { let data = format!("{}/data.db", config.data); @@ -733,14 +756,19 @@ pub fn s_insert_column( let mut sql = format!("ALTER TABLE {table} ADD '{column}' {c_type}"); if default.is_some() { - sql = format!("{} DEFAULT {}", sql, default.unwrap()); + sql = format!( + "{} DEFAULT {}", + sql, + default.ok_or(MLErr::new(EType::Other, "errornous default"))? + ); } connection.execute(sql.as_str(), ())?; Ok(()) } -pub fn db_setup(path: &str) -> MLE<()> { +/// # Errors +pub fn setup(path: &str) -> MLE<()> { let connection = Connection::open(path)?; connection.execute_batch( diff --git a/src/error.rs b/src/error.rs index b4cc444..652fa0c 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,16 +1,16 @@ use core::fmt; use serde::Deserialize; -pub type MLE = Result; +pub type MLE = Result; #[derive(Debug, Deserialize)] -pub struct MLError { - etype: ErrorType, +pub struct MLErr { + etype: EType, message: String, } #[derive(Debug, Deserialize)] -pub enum ErrorType { +pub enum EType { ArgumentError, ArgumentCountError, ConfigError, @@ -21,104 +21,106 @@ pub enum ErrorType { LibReq, LibChrono, LibJson, + LibIndicatif, IoError, Other, } -impl std::error::Error for MLError { +impl std::error::Error for MLErr { fn description(&self) -> &str { &self.message } } -impl fmt::Display for MLError { +impl fmt::Display for MLErr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.etype { - ErrorType::ArgumentError => { + EType::ArgumentError => { write!(f, "User input not accepted: {}", self.message) } - ErrorType::ArgumentCountError => { + EType::ArgumentCountError => { write!(f, "Too many/too few arguments") } - ErrorType::ConfigError => write!(f, "CONFIG"), - ErrorType::DBError => write!(f, "Database: {}", self.message), - ErrorType::ModError => write!(f, "Mod: {}", self.message), - ErrorType::LibToml => write!(f, "TOML"), - ErrorType::LibSql => write!(f, "SQL: {}", self.message), - ErrorType::LibReq => write!(f, "REQWEST"), - ErrorType::LibChrono => write!(f, "Chrono error: {}", self.message), - ErrorType::LibJson => write!(f, "JSON: {}", self.message), - ErrorType::IoError => write!(f, "IO"), - ErrorType::Other => write!(f, "OTHER"), + EType::ConfigError => write!(f, "CONFIG"), + EType::DBError => write!(f, "Database: {}", self.message), + EType::ModError => write!(f, "Mod: {}", self.message), + EType::LibToml => write!(f, "TOML"), + EType::LibSql => write!(f, "SQL: {}", self.message), + EType::LibReq => write!(f, "REQWEST"), + EType::LibChrono => write!(f, "Chrono error: {}", self.message), + EType::LibJson => write!(f, "JSON: {}", self.message), + EType::LibIndicatif => write!(f, "Indicativ: {}", self.message), + EType::IoError => write!(f, "IO"), + EType::Other => write!(f, "OTHER"), } } } -impl From for MLError { +impl From for MLErr { fn from(error: reqwest::Error) -> Self { Self { - etype: ErrorType::LibReq, + etype: EType::LibReq, message: error.to_string(), } } } -impl From for MLError { +impl From for MLErr { fn from(error: toml::de::Error) -> Self { Self { - etype: ErrorType::LibToml, + etype: EType::LibToml, message: error.to_string(), } } } -impl From for MLError { +impl From for MLErr { fn from(error: rusqlite::Error) -> Self { Self { - etype: ErrorType::LibSql, + etype: EType::LibSql, message: error.to_string(), } } } -impl From for MLError { +impl From for MLErr { fn from(error: toml::ser::Error) -> Self { Self { - etype: ErrorType::LibToml, + etype: EType::LibToml, message: error.to_string(), } } } -impl From for MLError { +impl From for MLErr { fn from(error: chrono::ParseError) -> Self { Self { - etype: ErrorType::LibChrono, + etype: EType::LibChrono, message: error.to_string(), } } } -impl From for MLError { +impl From for MLErr { fn from(error: std::io::Error) -> Self { Self { - etype: ErrorType::IoError, + etype: EType::IoError, message: error.to_string(), } } } -impl From for MLError { +impl From for MLErr { fn from(value: serde_json::error::Error) -> Self { Self { - etype: ErrorType::LibJson, + etype: EType::LibJson, message: value.to_string(), } } } -impl MLError { - #[must_use] pub fn new(etype: ErrorType, message: &str) -> Self { +impl MLErr { + #[must_use] pub fn new(etype: EType, message: &str) -> Self { Self { etype, message: String::from(message), diff --git a/src/files.rs b/src/files.rs index bf5a0a0..59f9ed1 100644 --- a/src/files.rs +++ b/src/files.rs @@ -13,11 +13,13 @@ use crate::{ cache::{copy_cached_version, get_cached_versions}, config::Cfg, db::{mods_get_info, userlist_add_disabled_versions}, - error::{ErrorType, MLError, MLE}, + error::{EType, MLErr, MLE}, modrinth::Version, List, PROGRESS_CHARS, STYLE_BAR_BYTE, STYLE_BAR_POS, STYLE_SPINNER, }; +/// # Errors +/// # Panics pub async fn download_versions( list: List, config: Cfg, @@ -63,6 +65,8 @@ pub async fn download_versions( Ok(()) } +/// # Errors +/// # Panics async fn download_version( config: Cfg, list: List, @@ -90,11 +94,8 @@ async fn download_version( None => files[0].clone(), }; let mut splitname: Vec<&str> = file.filename.split('.').collect(); - let extension = match splitname.pop().ok_or("") { - Ok(e) => e, - Err(..) => { - return Err(MLError::new(ErrorType::Other, "NO_FILE_EXTENSION")) - } + let Ok(extension) = splitname.pop().ok_or("") else { + return Err(MLErr::new(EType::Other, "NO_FILE_EXTENSION")) }; let filename = format!( "{}.mr.{}.{}.{}", @@ -122,6 +123,8 @@ async fn download_version( Ok(()) } +/// # Errors +/// # Panics async fn download_file( url: &str, path: &str, @@ -162,23 +165,27 @@ async fn download_file( Ok(()) } +/// # Errors +/// # Panics pub fn disable_version( config: &Cfg, - current_list: List, + current_list: &List, versionid: String, mod_id: String, ) -> MLE<()> { - let file = get_file_path(¤t_list, String::from(&versionid))?; + let file = get_file_path(current_list, &versionid)?; let disabled = format!("{file}.disabled"); rename(file, disabled)?; - userlist_add_disabled_versions(config, current_list.id, versionid, mod_id)?; + userlist_add_disabled_versions(config, ¤t_list.id, versionid, mod_id)?; Ok(()) } -pub fn delete_version(list: &List, version: String) -> MLE<()> { +/// # Errors +/// # Panics +pub fn delete_version(list: &List, version: &str) -> MLE<()> { let file = get_file_path(list, version)?; remove_file(file)?; @@ -186,16 +193,15 @@ pub fn delete_version(list: &List, version: String) -> MLE<()> { Ok(()) } -pub fn get_file_path(list: &List, versionid: String) -> MLE { +/// # Errors +/// # Panics +pub fn get_file_path(list: &List, versionid: &str) -> MLE { let mut names: HashMap = HashMap::new(); for file in read_dir(&list.download_folder)? { let path = file?.path(); if path.is_file() { - let pathstr = match path.to_str().ok_or("") { - Ok(s) => s, - Err(..) => { - return Err(MLError::new(ErrorType::Other, "INVALID_PATH")) - } + let Ok(pathstr) = path.to_str().ok_or("") else { + return Err(MLErr::new(EType::Other, "INVALID_PATH")) }; let namesplit: Vec<&str> = pathstr.split('.').collect(); let ver_id = namesplit[namesplit.len() - 2]; @@ -203,25 +209,29 @@ pub fn get_file_path(list: &List, versionid: String) -> MLE { } } - let filename = match names.get(&versionid).ok_or("") { - Ok(n) => n, - Err(..) => { - return Err(MLError::new( - ErrorType::ArgumentError, - "VERSION_NOT_FOUND_IN_FILES", - )) - } + let Ok(filename) = names.get(versionid).ok_or("") else { + return Err(MLErr::new( + EType::ArgumentError, + "VERSION_NOT_FOUND_IN_FILES", + )) }; Ok(filename.to_owned()) } -pub fn get_downloaded_versions(list: List) -> MLE> { +/// # Errors +/// # Panics +pub fn get_downloaded_versions(list: &List) -> MLE> { let mut versions: HashMap = HashMap::new(); for file in read_dir(&list.download_folder)? { let path = file?.path(); - if path.is_file() && path.extension().ok_or("BAH").unwrap() == "jar" { - let pathstr = path.to_str().ok_or("BAH").unwrap(); + if path.is_file() + && path + .extension() + .ok_or(MLErr::new(EType::IoError, "extension"))? + == "jar" + { + let pathstr = path.to_str().ok_or(MLErr::new(EType::IoError, "path_to_str"))?; let namesplit: Vec<&str> = pathstr.split('.').collect(); versions.insert( String::from(namesplit[namesplit.len() - 3]), @@ -232,6 +242,8 @@ pub fn get_downloaded_versions(list: List) -> MLE> { Ok(versions) } +/// # Errors +/// # Panics pub fn clean_list_dir(list: &List) -> MLE<()> { let dl_path = &list.download_folder; for entry in std::fs::read_dir(dl_path)? { diff --git a/src/lib.rs b/src/lib.rs index c51381c..750580f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,7 +16,7 @@ use std::{ use apis::modrinth::{get_game_versions, GameVersion, GameVersionType}; pub use apis::*; pub use commands::*; -use error::{ErrorType, MLError, MLE}; +use error::{EType, MLErr, MLE}; use indicatif::{ProgressBar, ProgressStyle}; use serde::{Deserialize, Serialize}; @@ -39,13 +39,15 @@ pub enum Modloader { } impl Modloader { + /// # Errors + /// # Panics pub fn from(string: &str) -> MLE { match string { "forge" => Ok(Modloader::Forge), "fabric" => Ok(Modloader::Fabric), "quilt" => Ok(Modloader::Quilt), _ => { - Err(MLError::new(ErrorType::ArgumentError, "UNKNOWN_MODLOADER")) + Err(MLErr::new(EType::ArgumentError, "UNKNOWN_MODLOADER")) } } } @@ -72,14 +74,18 @@ pub enum VersionLevel { /// Checks if update needed (time) /// if yes: get versions, update +/// # Errors +/// # Panics pub async fn check_game_versions(path: &str, force: bool) -> MLE<()> { let p = ProgressBar::new(1); - p.set_style(ProgressStyle::with_template(STYLE_MESSAGE).unwrap()); + 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().unwrap() < Duration::from_secs(60 * 60 * 24) + && creation_time.elapsed().map_err(|_| MLErr::new(EType::LibIndicatif, "SystemTimeError"))? < Duration::from_secs(60 * 60 * 24) { return Ok(()); } @@ -94,6 +100,7 @@ pub async fn check_game_versions(path: &str, force: bool) -> MLE<()> { } /// 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(); @@ -103,7 +110,8 @@ pub fn load_game_versions(path: &str) -> MLE> { } impl VersionLevel { - #[must_use] pub fn from(str: &str) -> Self { + #[must_use] + pub fn from(str: &str) -> Self { match str { "release" => VersionLevel::Release, "snapshot" => VersionLevel::Snapshot, @@ -111,6 +119,12 @@ impl VersionLevel { } } + /// . + /// + /// # Panics + /// + /// Panics if . + /// # Errors pub async fn get( self, versions_path: &str, @@ -122,23 +136,35 @@ impl VersionLevel { match self { VersionLevel::Release => { - let release = versions + if let Some(release) = versions .find(|ver| ver.version_type == GameVersionType::release) - .unwrap(); - Ok(release.version) + { + Ok(release.version) + } else { + Err(MLErr::new( + EType::Other, + "no minecraft release version found", + )) + } } VersionLevel::Snapshot => { - let snapshot = versions + if let Some(snapshot) = versions .find(|ver| ver.version_type == GameVersionType::snapshot) - .unwrap(); - Ok(snapshot.version) + { + 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(MLError::new( - ErrorType::ConfigError, + Err(MLErr::new( + EType::ConfigError, "unknown minecraft version", )) } diff --git a/src/main.rs b/src/main.rs index 21f2a30..a478ec7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,11 @@ +#![allow(clippy::too_many_lines)] + use clap::{Parser, Subcommand}; use modlist::{ config::Cfg, db::{config_get_current_list, lists_get, lists_get_all_ids}, download, export, get_current_list, import, list_add, list_change, - list_list, list_remove, list_version, mod_add, mod_remove, update, AddMod, + list_lists, list_remove, list_version, mod_add, mod_remove, update, AddMod, IDSelector, List, Modloader, VersionLevel, }; @@ -178,9 +180,10 @@ async fn main() { .unwrap(), }; - let marked_id = match version { - true => IDSelector::VersionID(id), - false => IDSelector::ModificationID(id), + let marked_id = if version { + IDSelector::VersionID(id) + } else { + IDSelector::ModificationID(id) }; let add_id = AddMod { @@ -235,7 +238,7 @@ async fn main() { list_add(&config, &id, &ver, &ml, &directory) } ListCommands::Remove { id } => list_remove(&config, &id), - ListCommands::List => list_list(&config), + ListCommands::List => list_lists(&config), ListCommands::Change { id } => list_change(&config, &id), ListCommands::Version { id, -- cgit v1.2.3