From 89193143f90e1b8cbb91445d14942fa39509acbb Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Mon, 9 Jan 2023 23:12:52 +0100 Subject: implemented more Error (dumb) --- src/commands/io.rs | 2 +- src/commands/list.rs | 32 +++++++++++++++++++++++--------- src/commands/update.rs | 8 ++++---- src/db.rs | 42 +++++++++++++++++++++--------------------- src/error.rs | 22 +++++++++++++++++++++- src/files.rs | 29 +++++++++++++++++++---------- src/input.rs | 5 ++++- src/lib.rs | 9 +++++---- 8 files changed, 98 insertions(+), 51 deletions(-) (limited to 'src') diff --git a/src/commands/io.rs b/src/commands/io.rs index 39f92d5..6c4a4d3 100644 --- a/src/commands/io.rs +++ b/src/commands/io.rs @@ -28,7 +28,7 @@ impl ExportList { let mods = userlist_get_all_ids(config, list_id)?.join("|"); - Ok(Self { id: list.id, mods, launcher: list.modloader.stringify(), mc_version: list.mc_version, download_folder: dl_folder }) + Ok(Self { id: list.id, mods, launcher: list.modloader.to_string(), mc_version: list.mc_version, download_folder: dl_folder }) } } diff --git a/src/commands/list.rs b/src/commands/list.rs index 585efe2..526b434 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -1,6 +1,6 @@ use std::io::{Error, ErrorKind}; -use crate::{db::{lists_insert, lists_remove, config_change_current_list, lists_get_all_ids, config_get_current_list, lists_get, lists_version}, Modloader, config::Cfg, input::{Input, Subcmd}}; +use crate::{db::{lists_insert, lists_remove, config_change_current_list, lists_get_all_ids, config_get_current_list, lists_get, lists_version}, Modloader, config::Cfg, input::{Input, Subcmd}, cmd_update, error::{MLE, ErrorType, MLError}}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct List { @@ -14,7 +14,10 @@ pub async fn list(config: Cfg, input: Input) -> Result<(), Box { - add(config, input.args.ok_or("")?) + match add(config, input.args.ok_or("")?) { + Ok(..) => Ok(()), + Err(e) => Err(Box::new(e)) + } }, Subcmd::Change => { change(config, input.args) @@ -23,7 +26,10 @@ pub async fn list(config: Cfg, input: Input) -> Result<(), Box { - version(config, input.args.ok_or("NO_VERSION")?) + match version(config, input.args.ok_or("NO_VERSION")?).await { + Ok(..) => Ok(()), + Err(e) => Err(Box::new(e)) + } } _ => { Err(Box::new(Error::new(ErrorKind::InvalidInput, "WRONG_SUBCOMMAND"))) @@ -31,14 +37,14 @@ pub async fn list(config: Cfg, input: Input) -> Result<(), Box Result> { +pub fn get_current_list(config: Cfg) -> MLE { let id = config_get_current_list(config.clone())?; lists_get(config, id) } -fn add(config: Cfg, args: Vec) -> Result<(), Box> { +fn add(config: Cfg, args: Vec) -> MLE<()> { match args.len() { - 1 | 2 | 3 => Err(Box::new(Error::new(ErrorKind::InvalidInput, "TOO_FEW_ARGUMENTS"))), + 1 | 2 | 3 => Err(MLError::new(ErrorType::ArgumentCountError, "TOO_FEW_ARGUMENTS")), 4 => { let id = String::from(&args[0]); let mc_version = String::from(&args[1]); @@ -46,7 +52,7 @@ fn add(config: Cfg, args: Vec) -> Result<(), Box> let download_folder = String::from(&args[3]); lists_insert(config, id, mc_version, mod_loader, download_folder) }, - 5.. => Err(Box::new(Error::new(ErrorKind::InvalidInput, "TOO_MANY_ARGUMENTS"))), + 5.. => Err(MLError::new(ErrorType::ArgumentCountError, "TOO_MANY_ARGUMENTS")), _ => panic!("list arguments should never be zero or lower"), } } @@ -74,7 +80,15 @@ fn remove(config: Cfg, args: Vec) -> Result<(), Box) -> Result<(), Box> { - lists_version(config.clone(), config_get_current_list(config.clone())?, String::from(&args[0])) +///Changing the current lists version and updating it +/// #Arguments +/// +/// * `config` - The current config +/// * `args` - All args, to extract the new version +async fn version(config: Cfg, args: Vec) -> MLE<()> { + let current_list = lists_get(config.clone(), config_get_current_list(config.clone())?)?; + + lists_version(config.clone(), String::from(¤t_list.id), String::from(&args[0]))?; //update the list & with -- args + cmd_update(config, vec![current_list], true, true, false).await } diff --git a/src/commands/update.rs b/src/commands/update.rs index 11f283e..ca28130 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -1,8 +1,8 @@ use std::io::{Error, ErrorKind}; -use crate::{config::Cfg, modrinth::{projects, Project, versions, extract_current_version, Version}, get_current_list, db::{userlist_get_all_ids, mods_get_versions, userlist_get_applicable_versions, userlist_change_versions, lists_get_all_ids, lists_get, userlist_get_current_version, mods_change_versions}, List, input::Input, files::{delete_version, download_versions, disable_version}}; +use crate::{config::Cfg, modrinth::{projects, Project, versions, extract_current_version, Version}, get_current_list, db::{userlist_get_all_ids, mods_get_versions, userlist_get_applicable_versions, userlist_change_versions, lists_get_all_ids, lists_get, userlist_get_current_version, mods_change_versions}, List, input::Input, files::{delete_version, download_versions, disable_version}, error::{MLE, MLError, ErrorType}}; -pub async fn update(config: Cfg, input: Input) -> Result<(), Box> { +pub async fn update(config: Cfg, input: Input) -> MLE<()> { let mut liststack: Vec = vec![]; if input.all_lists { @@ -19,7 +19,7 @@ pub async fn update(config: Cfg, input: Input) -> Result<(), Box, clean: bool, direct_download: bool, delete_old: bool) -> Result<(), Box> { +pub async fn cmd_update(config: Cfg, liststack: Vec, clean: bool, direct_download: bool, delete_old: bool) -> MLE<()> { for current_list in liststack { let mods = userlist_get_all_ids(config.clone(), current_list.clone().id)?; @@ -37,7 +37,7 @@ pub async fn cmd_update(config: Cfg, liststack: Vec, clean: bool, direct_d let current_version = &versions[index]; let p_id = String::from(&project.id); let v_id = ¤t_version.mod_id; - if &p_id != v_id { return Err(Box::new(Error::new(ErrorKind::Other, "SORTING_ERROR"))) }; + if &p_id != v_id { return Err(MLError::new(ErrorType::Other, "SORTING_ERROR")) }; //Getting current installed version for disable or delete let disable_version = userlist_get_current_version(config.clone(), String::from(¤t_list.id), String::from(&project.id))?; diff --git a/src/db.rs b/src/db.rs index d823018..c5a972f 100644 --- a/src/db.rs +++ b/src/db.rs @@ -2,7 +2,7 @@ use std::io::{Error, ErrorKind}; use rusqlite::Connection; -use crate::{Modloader, config::Cfg, List, devdir}; +use crate::{Modloader, config::Cfg, List, devdir, error::{MLE, MLError, ErrorType}}; //mods pub fn mods_insert(config: Cfg, id: String, name: String, versions: Vec) -> Result<(), Box> { @@ -81,7 +81,7 @@ pub fn mods_get_name(config: Cfg, id: String) -> Result Result<(), Box> { +pub fn mods_change_versions(config: Cfg, versions: String, mod_id: String) -> MLE<()> { println!("Updating versions for {} with \n {}", mod_id, versions); @@ -110,11 +110,11 @@ pub struct DBModlistVersions { pub versions: String, } -pub fn mods_get_versions(config: Cfg, mods: Vec) -> Result, Box> { +pub fn mods_get_versions(config: Cfg, mods: Vec) -> MLE> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; - if mods.is_empty() { return Err(Box::new(Error::new(ErrorKind::Other, "MODS_NO_INPUT"))); } + if mods.is_empty() { return Err(MLError::new(ErrorType::ArgumentError, "MODS_NO_INPUT")); } let mut wherestr = String::from("WHERE"); for (i, id) in mods.iter().enumerate() { @@ -137,7 +137,7 @@ pub fn mods_get_versions(config: Cfg, mods: Vec) -> Result Err(Box::new(Error::new(ErrorKind::NotFound, "MODS_MODS_NOT_FOUND"))), + true => Err(MLError::new(ErrorType::DBError, "MODS_MODS_NOT_FOUND")), false => Ok(versionmaps), } } @@ -155,7 +155,7 @@ pub fn userlist_insert(config: Cfg, list_id: String, mod_id: String, current_ver Ok(()) } -pub fn userlist_get_all_ids(config: Cfg, list_id: String) -> Result, Box> { +pub fn userlist_get_all_ids(config: Cfg, list_id: String) -> MLE> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); @@ -171,7 +171,7 @@ pub fn userlist_get_all_ids(config: Cfg, list_id: String) -> Result, }; match mod_ids.is_empty() { - true => Err(Box::new(std::io::Error::new(ErrorKind::NotFound, "NO_MODS"))), + true => Err(MLError::new(ErrorType::DBError, "NO_MODS")), false => Ok(mod_ids), } } @@ -226,7 +226,7 @@ pub fn userlist_get_all_applicable_versions_with_mods(config: Cfg, list_id: Stri Ok(versions) } -pub fn userlist_get_current_version(config: Cfg, list_id: String, mod_id: String) -> Result> { +pub fn userlist_get_current_version(config: Cfg, list_id: String, mod_id: String) -> MLE { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); @@ -241,7 +241,7 @@ pub fn userlist_get_current_version(config: Cfg, list_id: String, mod_id: String }; match version.is_empty() { - true => Err(Box::new(Error::new(ErrorKind::NotFound, "MOD_NOT_FOUND"))), + true => Err(MLError::new(ErrorType::DBError, "MOD_NOT_FOUND")), false => Ok(version), } } @@ -293,7 +293,7 @@ pub fn userlist_change_versions(config: Cfg, list_id: String, current_version: S Ok(()) } -pub fn userlist_add_disabled_versions(config: Cfg, list_id: String, disabled_version: String, mod_id: String) -> Result<(), Box> { +pub fn userlist_add_disabled_versions(config: Cfg, list_id: String, disabled_version: String, mod_id: String) -> MLE<()> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; @@ -307,7 +307,7 @@ pub fn userlist_add_disabled_versions(config: Cfg, list_id: String, disabled_ver Ok(()) } -pub fn userlist_get_disabled_versions(config:Cfg, list_id: String, mod_id: String) -> Result> { +pub fn userlist_get_disabled_versions(config:Cfg, list_id: String, mod_id: String) -> MLE { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); @@ -322,7 +322,7 @@ pub fn userlist_get_disabled_versions(config:Cfg, list_id: String, mod_id: Strin }; match version.is_empty() { - true => Err(Box::new(Error::new(ErrorKind::NotFound, "MOD_NOT_FOUND"))), + true => Err(MLError::new(ErrorType::DBError, "MOD_NOT_FOUND")), false => Ok(version), } } @@ -349,13 +349,13 @@ pub fn userlist_get_all_downloads(config: Cfg, list_id: String) -> Result Result<(), Box> { +pub fn lists_insert(config: Cfg, id: String, mc_version: String, mod_loader: Modloader, download_folder: String) -> MLE<()> { println!("Creating list {}", id); let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; - connection.execute("INSERT INTO lists VALUES (?1, ?2, ?3, ?4)", [id.clone(), mc_version, mod_loader.stringify(), download_folder])?; + connection.execute("INSERT INTO lists VALUES (?1, ?2, ?3, ?4)", [id.clone(), mc_version, mod_loader.to_string(), download_folder])?; connection.execute(format!("CREATE TABLE {}( 'mod_id' TEXT, 'current_version' TEXT, 'applicable_versions' BLOB, 'current_download' TEXT, 'disabled_versions' TEXT DEFAULT 'NONE' )", id).as_str(), [])?; Ok(()) @@ -370,7 +370,7 @@ pub fn lists_remove(config: Cfg, id: String) -> Result<(), Box Result> { +pub fn lists_get(config: Cfg, list_id: String) -> MLE { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); @@ -386,12 +386,12 @@ pub fn lists_get(config: Cfg, list_id: String) -> Result Result<(), Box> { +pub fn lists_version(config: Cfg, list_id: String, version: String) -> MLE<()> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); @@ -399,7 +399,7 @@ pub fn lists_version(config: Cfg, list_id: String, version: String) -> Result<() Ok(()) } -pub fn lists_get_all_ids(config: Cfg) -> Result, Box> { +pub fn lists_get_all_ids(config: Cfg) -> MLE> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); @@ -414,7 +414,7 @@ pub fn lists_get_all_ids(config: Cfg) -> Result, Box Err(Box::new(std::io::Error::new(ErrorKind::NotFound, "NO_LISTS"))), + true => Err(MLError::new(ErrorType::DBError, "NO_LISTS")), false => Ok(list_ids), } } @@ -428,7 +428,7 @@ pub fn config_change_current_list(config: Cfg, id: String) -> Result<(), Box Result> { +pub fn config_get_current_list(config: Cfg) -> MLE { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); @@ -442,7 +442,7 @@ pub fn config_get_current_list(config: Cfg) -> Result write!(f, "Wrong argument"), ErrorType::ArgumentCountError => write!(f, "Too many/too few arguments"), ErrorType::ConfigError => write!(f, "CONFIG"), + ErrorType::DBError => write!(f, "DATABASE"), ErrorType::LibToml => write!(f, "TOML"), - ErrorType::IoError => write!(f, "IO") + ErrorType::LibSql => write!(f, "SQL"), + ErrorType::LibReq => write!(f, "REQWEST"), + ErrorType::IoError => write!(f, "IO"), + ErrorType::Other => write!(f, "OTHER") } } } +impl From for MLError { + fn from(error: reqwest::Error) -> Self { + Self { etype: ErrorType::LibReq, message: error.to_string() } + } +} + impl From for MLError { fn from(error: toml::de::Error) -> Self { Self { etype: ErrorType::LibToml, message: error.to_string() } } } +impl From for MLError { + fn from(error: rusqlite::Error) -> Self { + Self { etype: ErrorType::LibSql, message: error.to_string() } + } +} + impl From for MLError { fn from(error: toml::ser::Error) -> Self { Self { etype: ErrorType::LibToml, message: error.to_string() } diff --git a/src/files.rs b/src/files.rs index a3f838a..998ed32 100644 --- a/src/files.rs +++ b/src/files.rs @@ -2,16 +2,19 @@ use std::{fs::{File, read_dir, remove_file, rename}, io::Write, collections::Has use futures_util::StreamExt; use reqwest::Client; -use crate::{List, modrinth::Version, db::userlist_add_disabled_versions, config::Cfg}; +use crate::{List, modrinth::Version, db::userlist_add_disabled_versions, config::Cfg, error::{MLE, MLError, ErrorType}}; -pub async fn download_versions(current_list: List, versions: Vec) -> Result> { +pub async fn download_versions(current_list: List, versions: Vec) -> MLE { let dl_path = String::from(¤t_list.download_folder); for ver in versions { let primary_file = ver.files.into_iter().find(|file| file.primary).unwrap(); let mut splitname: Vec<&str> = primary_file.filename.split('.').collect(); - let extension = splitname.pop().ok_or("NO_FILE_EXTENSION")?; + let extension = match splitname.pop().ok_or("") { + Ok(e) => e, + Err(..) => return Err(MLError::new(ErrorType::Other, "NO_FILE_EXTENSION")), + }; let filename = format!("{}.mr.{}.{}.{}", splitname.join("."), ver.project_id, ver.id, extension); download_file(primary_file.url, current_list.clone().download_folder, filename).await?; } @@ -19,14 +22,14 @@ pub async fn download_versions(current_list: List, versions: Vec) -> Re Ok(dl_path) } -async fn download_file(url: String, path: String, name: String) -> Result<(), Box> { +async fn download_file(url: String, path: String, name: String) -> MLE<()> { println!("Downloading {}", url); let dl_path_file = format!("{}/{}", path, name); let res = Client::new() .get(String::from(&url)) .send() .await?; - + // download chunks let mut file = File::create(&dl_path_file)?; let mut stream = res.bytes_stream(); @@ -39,7 +42,7 @@ async fn download_file(url: String, path: String, name: String) -> Result<(), Bo Ok(()) } -pub fn disable_version(config: Cfg, current_list: List, versionid: String, mod_id: String) -> Result<(), Box> { +pub fn disable_version(config: Cfg, current_list: List, versionid: String, mod_id: String) -> MLE<()> { println!("Disabling version {} for mod {}", versionid, mod_id); let file = get_file_path(current_list.clone(), String::from(&versionid))?; let disabled = format!("{}.disabled", file); @@ -51,7 +54,7 @@ pub fn disable_version(config: Cfg, current_list: List, versionid: String, mod_i Ok(()) } -pub fn delete_version(list: List, version: String) -> Result<(), Box> { +pub fn delete_version(list: List, version: String) -> MLE<()> { let file = get_file_path(list, version)?; remove_file(file)?; @@ -59,19 +62,25 @@ pub fn delete_version(list: List, version: String) -> Result<(), Box Result> { +pub fn get_file_path(list: List, versionid: String) -> 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 = path.to_str().ok_or("BAH")?; + let pathstr = match path.to_str().ok_or("") { + Ok(s) => s, + Err(..) => return Err(MLError::new(ErrorType::Other, "INVALID_PATH")) + }; let namesplit: Vec<&str> = pathstr.split('.').collect(); let ver_id = namesplit[namesplit.len() - 2]; names.insert(String::from(ver_id), String::from(pathstr)); } }; - let filename = names.get(&versionid).ok_or("VERSION_NOT_FOUND_IN_FILES")?; + let filename = match names.get(&versionid).ok_or("") { + Ok(n) => n, + Err(..) => return Err(MLError::new(ErrorType::ArgumentError, "VERSION_NOT_FOUND_IN_FILES")) + }; Ok(filename.to_owned()) } diff --git a/src/input.rs b/src/input.rs index d048775..28a0b7b 100644 --- a/src/input.rs +++ b/src/input.rs @@ -148,7 +148,10 @@ pub async fn get_input(config: Cfg) -> Result<(), Box> { list(config, input).await }, Cmd::Update => { - update(config, input).await + match update(config, input).await { + Ok(..) => Ok(()), + Err(..) => Err(Box::new(MLError::new(ErrorType::Other, "UPDATE_ERR"))) + } }, Cmd::Setup => { setup(config).await diff --git a/src/lib.rs b/src/lib.rs index 17ad6b9..eb845d8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,10 +6,11 @@ pub mod db; pub mod error; pub mod files; -use std::{io::{Error, ErrorKind}, path::Path}; +use std::path::Path; pub use apis::*; pub use commands::*; +use error::{MLE, ErrorType, MLError}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Modloader { @@ -18,18 +19,18 @@ pub enum Modloader { } impl Modloader { - fn stringify(&self) -> String { + fn to_string(&self) -> String { match self { Modloader::Fabric => String::from("fabric"), Modloader::Forge => String::from("forge"), } } - fn from(string: &str) -> Result> { + fn from(string: &str) -> MLE { match string { "forge" => Ok(Modloader::Forge), "fabric" => Ok(Modloader::Fabric), - _ => Err(Box::new(Error::new(ErrorKind::InvalidData, "UNKNOWN_MODLOADER"))) + _ => Err(MLError::new(ErrorType::ArgumentError, "UNKNOWN_MODLOADER")) } } } -- cgit v1.2.3