From 8050cfcd70a16273cc2814fe29c8ee08320d85d3 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Thu, 20 Apr 2023 15:13:58 +0200 Subject: cargo fmt --- src/apis/modrinth.rs | 56 +++--- src/commands/download.rs | 38 +++- src/commands/io.rs | 51 ++++-- src/commands/list.rs | 38 +++- src/commands/mod.rs | 16 +- src/commands/modification.rs | 181 ++++++++++++++---- src/commands/setup.rs | 12 +- src/commands/update.rs | 116 +++++++++--- src/config.rs | 16 +- src/db.rs | 423 +++++++++++++++++++++++++++++-------------- src/error.rs | 37 +++- src/files.rs | 59 ++++-- src/lib.rs | 10 +- src/main.rs | 115 +++++++----- 14 files changed, 823 insertions(+), 345 deletions(-) (limited to 'src') diff --git a/src/apis/modrinth.rs b/src/apis/modrinth.rs index bb5ee19..9afe7f3 100644 --- a/src/apis/modrinth.rs +++ b/src/apis/modrinth.rs @@ -2,7 +2,10 @@ use chrono::{DateTime, FixedOffset}; use reqwest::Client; use serde::Deserialize; -use crate::{Modloader, List, error::{MLE, MLError, ErrorType}}; +use crate::{ + error::{ErrorType, MLError, MLE}, + List, Modloader, +}; #[derive(Debug, Deserialize, Clone)] pub struct Project { @@ -47,7 +50,7 @@ pub struct ModeratorMessage { pub enum Side { required, optional, - unsupported + unsupported, } #[allow(non_camel_case_types)] @@ -55,7 +58,7 @@ pub enum Side { pub enum Type { r#mod, modpack, - recourcepack + recourcepack, } #[allow(non_camel_case_types)] @@ -63,9 +66,11 @@ pub enum Type { pub enum Status { approved, rejected, - draft, unlisted, archived, + draft, + unlisted, + archived, processing, - unknown + unknown, } #[derive(Debug, Clone, Deserialize)] @@ -90,7 +95,7 @@ pub struct Version { pub enum VersionType { release, beta, - alpha + alpha, } #[derive(Debug, Clone, Deserialize)] @@ -110,22 +115,19 @@ pub struct Hash { async fn get(api: &str, path: String) -> Result>, Box> { let url = format!(r#"{}{}"#, api, path); - + let client = Client::builder() - .user_agent(format!("fxqnlr/modlistcli/{} (fxqnlr@gmail.com)", env!("CARGO_PKG_VERSION"))) + .user_agent(format!( + "fxqnlr/modlistcli/{} (fxqnlr@gmail.com)", + env!("CARGO_PKG_VERSION") + )) .build()?; - let res = client.get(url) - .send() - .await?; - + let res = client.get(url).send().await?; + let mut data: Option> = None; if res.status() == 200 { - data = Some(res - .bytes() - .await? - .to_vec() - ); + data = Some(res.bytes().await?.to_vec()); } Ok(data) @@ -143,7 +145,7 @@ pub async fn projects(api: &str, ids: Vec) -> Vec { let url = format!(r#"projects?ids=["{}"]"#, all); let data = get(api, url).await.unwrap().unwrap(); - + serde_json::from_slice(&data).unwrap() } @@ -154,7 +156,10 @@ pub async fn versions(api: &str, id: String, list: List) -> Vec { Modloader::Fabric => String::from("fabric"), }; - let url = format!(r#"project/{}/version?loaders=["{}"]&game_versions=["{}"]"#, id, loaderstr, list.mc_version); + let url = format!( + r#"project/{}/version?loaders=["{}"]&game_versions=["{}"]"#, + id, loaderstr, list.mc_version + ); let data = get(api, url).await.unwrap(); @@ -185,7 +190,7 @@ pub fn extract_current_version(versions: Vec) -> MLE { times.sort_by_key(|t| t.1); times.reverse(); Ok(times[0].0.to_string()) - }, + } _ => panic!("available_versions should never be negative"), } } @@ -205,16 +210,19 @@ pub struct MCVersion { } pub async fn get_minecraft_version(api: &str, version: MCVersionType) -> String { - let data = get(api, String::from("tag/game_version")).await.unwrap().unwrap(); + let data = get(api, String::from("tag/game_version")) + .await + .unwrap() + .unwrap(); let mc_versions: Vec = serde_json::from_slice(&data).unwrap(); let ver = match version { MCVersionType::Release => { let mut i = 0; - while !mc_versions[i].major { + while !mc_versions[i].major { i += 1; - }; + } &mc_versions[i] - }, + } MCVersionType::Latest => &mc_versions[0], MCVersionType::Specific => { println!("Not inplemented"); diff --git a/src/commands/download.rs b/src/commands/download.rs index 4baecee..9434591 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -1,8 +1,14 @@ -use crate::{files::{get_downloaded_versions, download_versions, delete_version, disable_version, clean_list_dir}, db::{userlist_get_all_current_versions_with_mods, lists_get_all_ids, lists_get}, modrinth::get_raw_versions, error::{MLE, ErrorType, MLError}}; -use crate::{List, get_current_list, config::Cfg}; +use crate::{config::Cfg, get_current_list, List}; +use crate::{ + db::{lists_get, lists_get_all_ids, userlist_get_all_current_versions_with_mods}, + error::{ErrorType, MLError, MLE}, + files::{ + clean_list_dir, delete_version, disable_version, download_versions, get_downloaded_versions, + }, + modrinth::get_raw_versions, +}; pub async fn download(config: Cfg, all_lists: bool, clean: bool, delete_old: bool) -> MLE<()> { - let mut liststack: Vec = vec![]; if all_lists { let list_ids = lists_get_all_ids(config.clone())?; @@ -18,7 +24,10 @@ pub async fn download(config: Cfg, all_lists: bool, clean: bool, delete_old: boo for current_list in liststack { let downloaded_versions = get_downloaded_versions(current_list.clone())?; println!("To download: {:#?}", downloaded_versions); - let current_version_ids = match userlist_get_all_current_versions_with_mods(config.clone(), String::from(¤t_list.id)) { + let current_version_ids = match userlist_get_all_current_versions_with_mods( + config.clone(), + String::from(¤t_list.id), + ) { Ok(i) => Ok(i), Err(e) => Err(MLError::new(ErrorType::DBError, e.to_string().as_str())), }?; @@ -36,28 +45,37 @@ pub async fn download(config: Cfg, all_lists: bool, clean: bool, delete_old: boo if current_download.is_none() || clean { to_download.push(current_version); } else { - let downloaded_version = current_download.ok_or("SOMETHING_HAS_REALLY_GONE_WRONG").unwrap(); + let downloaded_version = current_download + .ok_or("SOMETHING_HAS_REALLY_GONE_WRONG") + .unwrap(); if ¤t_version != downloaded_version { to_disable.push((mod_id.clone(), String::from(downloaded_version))); to_download.push(current_version); } } } - - if clean { clean_list_dir(¤t_list)? }; + + if clean { + clean_list_dir(¤t_list)? + }; if !to_download.is_empty() { - download_versions(current_list.clone(), config.clone(), get_raw_versions(&config.apis.modrinth, to_download).await).await?; + download_versions( + current_list.clone(), + config.clone(), + get_raw_versions(&config.apis.modrinth, to_download).await, + ) + .await?; } else { println!("There are no new versions to download"); } - + if !to_disable.is_empty() { for ver in to_disable { if delete_old { println!("Deleting version {} for mod {}", ver.1, ver.0); delete_version(current_list.clone(), ver.1)?; - } else { + } else { disable_version(config.clone(), current_list.clone(), ver.1, ver.0)?; }; } diff --git a/src/commands/io.rs b/src/commands/io.rs index 5de8dd1..7f03eec 100644 --- a/src/commands/io.rs +++ b/src/commands/io.rs @@ -1,12 +1,18 @@ +use serde::{Deserialize, Serialize}; use std::fs::File; use std::io::prelude::*; -use serde::{Serialize, Deserialize}; -use crate::{db::{lists_get, userlist_get_all_ids, lists_get_all_ids, lists_insert}, config::Cfg, Modloader, List, devdir, error::MLE, mod_add, IDSelector}; +use crate::{ + config::Cfg, + db::{lists_get, lists_get_all_ids, lists_insert, userlist_get_all_ids}, + devdir, + error::MLE, + mod_add, IDSelector, List, Modloader, +}; #[derive(Debug, Serialize, Deserialize)] struct Export { - lists: Vec + lists: Vec, } #[derive(Debug, Serialize, Deserialize)] @@ -20,15 +26,22 @@ struct ExportList { impl ExportList { pub fn from(config: Cfg, list_id: String, download: bool) -> MLE { - let list = lists_get(config.clone(), String::from(&list_id))?; let mut dl_folder = None; - if download{ dl_folder = Some(list.download_folder) }; + if download { + dl_folder = Some(list.download_folder) + }; let mods = userlist_get_all_ids(config, list_id)?.join("|"); - Ok(Self { id: list.id, mods, launcher: list.modloader.to_string(), 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, + }) } } @@ -43,32 +56,44 @@ pub fn export(config: Cfg, list: Option) -> MLE<()> { for list_id in list_ids { lists.push(ExportList::from(config.clone(), list_id, true)?); } - - let toml = toml::to_string( &Export { lists } )?; + + let toml = toml::to_string(&Export { lists })?; let filestr = dirs::home_dir().unwrap().join("mlexport.toml"); - let mut file = File::create(devdir(filestr.into_os_string().into_string().unwrap().as_str()))?; + let mut file = File::create(devdir( + filestr.into_os_string().into_string().unwrap().as_str(), + ))?; file.write_all(toml.as_bytes())?; Ok(()) } pub async fn import(config: Cfg, file_str: String, direct_download: bool) -> MLE<()> { - let mut file = File::open(file_str)?; let mut content = String::new(); file.read_to_string(&mut content)?; let export: Export = toml::from_str(&content)?; for exportlist in export.lists { - let list = List { id: exportlist.id, mc_version: exportlist.mc_version, modloader: Modloader::from(&exportlist.launcher)?, download_folder: exportlist.download_folder.ok_or("NO_DL").unwrap() }; - lists_insert(config.clone(), list.id.clone(), list.mc_version.clone(), list.modloader.clone(), String::from(&list.download_folder))?; + let list = List { + id: exportlist.id, + mc_version: exportlist.mc_version, + modloader: Modloader::from(&exportlist.launcher)?, + download_folder: exportlist.download_folder.ok_or("NO_DL").unwrap(), + }; + lists_insert( + config.clone(), + list.id.clone(), + list.mc_version.clone(), + list.modloader.clone(), + String::from(&list.download_folder), + )?; let mods: Vec<&str> = exportlist.mods.split('|').collect(); let mut mod_ids = vec![]; for mod_id in mods { mod_ids.push(IDSelector::ModificationID(String::from(mod_id))); - }; + } //TODO impl set_version and good direct download //TODO impl all at once, dafuck mod_add(config.clone(), mod_ids, list, direct_download, false).await?; diff --git a/src/commands/list.rs b/src/commands/list.rs index 80e801a..13176f4 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -1,4 +1,12 @@ -use crate::{db::{lists_insert, lists_remove, config_change_current_list, config_get_current_list, lists_get, lists_version}, Modloader, config::Cfg, update, error::MLE}; +use crate::{ + config::Cfg, + db::{ + config_change_current_list, config_get_current_list, lists_get, lists_insert, lists_remove, + lists_version, + }, + error::MLE, + update, Modloader, +}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct List { @@ -13,7 +21,13 @@ pub fn get_current_list(config: Cfg) -> MLE { lists_get(config, id) } -pub fn list_add(config: Cfg, id: String, mc_version: String, modloader: Modloader, directory: String) -> MLE<()> { +pub fn list_add( + config: Cfg, + id: String, + mc_version: String, + modloader: Modloader, + directory: String, +) -> MLE<()> { lists_insert(config, id, mc_version, modloader, directory) } @@ -30,15 +44,27 @@ pub fn list_remove(config: Cfg, id: String) -> MLE<()> { ///Changing the current lists version and updating it /// /// #Arguments -/// +/// /// * `config` - The current config /// * `args` - All args, to extract the new version -pub async fn list_version(config: Cfg, id: String, mc_version: String, download: bool, delete: bool) -> MLE<()> { - println!("Change version for list {} to minecraft version: {}", id, mc_version); +pub async fn list_version( + config: Cfg, + id: String, + mc_version: String, + download: bool, + delete: bool, +) -> MLE<()> { + println!( + "Change version for list {} to minecraft version: {}", + id, mc_version + ); lists_version(config.clone(), &id, &mc_version)?; - println!("\nCheck for updates for new minecraft version in list {}", id); + println!( + "\nCheck for updates for new minecraft version in list {}", + id + ); let list = lists_get(config.clone(), id)?; update(config, vec![list], true, download, delete).await } diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 0d5bd00..1c7c012 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,13 +1,13 @@ -pub mod modification; -pub mod list; -pub mod update; -pub mod setup; pub mod download; pub mod io; +pub mod list; +pub mod modification; +pub mod setup; +pub mod update; -pub use modification::*; -pub use list::*; -pub use update::*; -pub use setup::*; pub use download::*; pub use io::*; +pub use list::*; +pub use modification::*; +pub use setup::*; +pub use update::*; diff --git a/src/commands/modification.rs b/src/commands/modification.rs index 454e148..ffc4e10 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -1,9 +1,19 @@ -use crate::{modrinth::{versions, extract_current_version, Version, projects, get_raw_versions, project}, config::Cfg, db::{mods_insert, userlist_remove, mods_get_id, userlist_insert, userlist_get_all_ids, userlist_get_current_version, lists_get_all_ids, mods_remove}, files::{delete_version, download_versions}, List, error::{MLE, ErrorType, MLError}}; +use crate::{ + config::Cfg, + db::{ + lists_get_all_ids, mods_get_id, mods_insert, mods_remove, userlist_get_all_ids, + userlist_get_current_version, userlist_insert, userlist_remove, + }, + error::{ErrorType, MLError, MLE}, + files::{delete_version, download_versions}, + modrinth::{extract_current_version, get_raw_versions, project, projects, versions, Version}, + List, +}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum IDSelector { ModificationID(String), - VersionID(String) + VersionID(String), } #[derive(Debug, Clone)] @@ -16,10 +26,16 @@ pub struct ProjectInfo { pub download_link: String, } -pub async fn mod_add(config: Cfg, ids: Vec, list: List, direct_download: bool, set_version: bool) -> MLE<()> { +pub async fn mod_add( + config: Cfg, + ids: Vec, + list: List, + direct_download: bool, + set_version: bool, +) -> MLE<()> { println!("Add mods to {}", list.id); println!(" └Add mods:"); - + let mut mod_ids: Vec = Vec::new(); let mut ver_ids: Vec = Vec::new(); @@ -32,11 +48,17 @@ pub async fn mod_add(config: Cfg, ids: Vec, list: List, direct_downl } let mut projectinfo: Vec = Vec::new(); - if !mod_ids.is_empty() { projectinfo.append(&mut get_mod_infos(config.clone(), mod_ids, list.clone()).await?) }; - if !ver_ids.is_empty() { projectinfo.append(&mut get_ver_info(config.clone(), ver_ids).await?) }; + if !mod_ids.is_empty() { + projectinfo.append(&mut get_mod_infos(config.clone(), mod_ids, list.clone()).await?) + }; + if !ver_ids.is_empty() { + projectinfo.append(&mut get_ver_info(config.clone(), ver_ids).await?) + }; + + if projectinfo.is_empty() { + return Err(MLError::new(ErrorType::ArgumentError, "NO_IDS?")); + }; - if projectinfo.is_empty() { return Err(MLError::new(ErrorType::ArgumentError, "NO_IDS?")) }; - let mut downloadstack: Vec = Vec::new(); //Adding each mod to the lists and downloadstack @@ -45,29 +67,59 @@ pub async fn mod_add(config: Cfg, ids: Vec, list: List, direct_downl } else { println!(" └Insert mods in list {} and save infos", list.id); } - + for project in projectinfo { - let current_version_id = if project.current_version.is_none() { String::from("NONE") } else { project.current_version.clone().unwrap().id }; - match userlist_insert(config.clone(), &list.id, &project.mod_id, ¤t_version_id, project.clone().applicable_versions, &project.download_link, set_version) { + let current_version_id = if project.current_version.is_none() { + String::from("NONE") + } else { + project.current_version.clone().unwrap().id + }; + match userlist_insert( + config.clone(), + &list.id, + &project.mod_id, + ¤t_version_id, + project.clone().applicable_versions, + &project.download_link, + set_version, + ) { Err(e) => { let expected_err = format!("SQL: UNIQUE constraint failed: {}.mod_id", list.id); - if e.to_string() == expected_err { Err(MLError::new(ErrorType::ModError, "MOD_ALREADY_ON_SELECTED_LIST")) } else { Err(e) } - }, - Ok(..) => { Ok(..) }, + if e.to_string() == expected_err { + Err(MLError::new( + ErrorType::ModError, + "MOD_ALREADY_ON_SELECTED_LIST", + )) + } else { + Err(e) + } + } + Ok(..) => Ok(..), }?; - - match mods_insert(config.clone(), &project.mod_id, &project.slug, &project.title) { + + match mods_insert( + config.clone(), + &project.mod_id, + &project.slug, + &project.title, + ) { Err(e) => { - if e.to_string() == "SQL: UNIQUE constraint failed: mods.id" { Ok(..) } else { Err(e) } - }, + if e.to_string() == "SQL: UNIQUE constraint failed: mods.id" { + Ok(..) + } else { + Err(e) + } + } Ok(..) => Ok(..), }?; - if project.current_version.is_some() { downloadstack.push(project.current_version.unwrap()) }; + if project.current_version.is_some() { + downloadstack.push(project.current_version.unwrap()) + }; } //Download all the added mods - if direct_download { + if direct_download { download_versions(list.clone(), config.clone(), downloadstack).await?; }; @@ -86,7 +138,12 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec, list: List) -> MLE = Vec::new(); let current_version: Option; @@ -95,36 +152,63 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec, list: List) -> MLE) -> MLE> { let mut projectinfo: Vec = Vec::new(); - + //Get required information from ver_ids let mut v_versions = get_raw_versions(&config.apis.modrinth, ver_ids).await; let mut v_mod_ids: Vec = Vec::new(); for ver in v_versions.clone() { v_mod_ids.push(ver.project_id); - }; + } let mut v_projects = projects(&config.apis.modrinth, v_mod_ids).await; v_versions.sort_by(|a, b| a.project_id.cmp(&b.project_id)); v_projects.sort_by(|a, b| a.id.cmp(&b.id)); @@ -132,9 +216,22 @@ async fn get_ver_info(config: Cfg, ver_ids: Vec) -> MLE for (i, project) in v_projects.into_iter().enumerate() { let version = &v_versions[i]; println!("\t└{}({})", project.title, version.id); - let file = version.clone().files.into_iter().find(|f| f.primary).unwrap().url; - projectinfo.push(ProjectInfo { mod_id: project.id, slug: project.slug, title: project.title, current_version: Some(version.clone()), applicable_versions: vec![String::from(&version.id)], download_link: file }) - }; + let file = version + .clone() + .files + .into_iter() + .find(|f| f.primary) + .unwrap() + .url; + projectinfo.push(ProjectInfo { + mod_id: project.id, + slug: project.slug, + title: project.title, + current_version: Some(version.clone()), + applicable_versions: vec![String::from(&version.id)], + download_link: file, + }) + } Ok(projectinfo) } @@ -145,24 +242,28 @@ async fn get_ver_info(config: Cfg, ver_ids: Vec) -> MLE /// * `id` - name, slug or id of the mod /// * `list` - List struct pub fn mod_remove(config: Cfg, id: &str, list: List) -> MLE<()> { - let mod_id = mods_get_id(&config.data, id)?; - + let version = userlist_get_current_version(config.clone(), &list.id, &mod_id)?; userlist_remove(config.clone(), &list.id, &mod_id)?; delete_version(list, version)?; - + let list_ids = lists_get_all_ids(config.clone())?; - + // Remove mod from main list if not used elsewhere let mut mod_used = false; for id in list_ids { let mods = userlist_get_all_ids(config.clone(), id)?; - if mods.contains(&mod_id) { mod_used = true; break; }; - }; + if mods.contains(&mod_id) { + mod_used = true; + break; + }; + } - if !mod_used { mods_remove(config, mod_id)?; }; + if !mod_used { + mods_remove(config, mod_id)?; + }; Ok(()) } diff --git a/src/commands/setup.rs b/src/commands/setup.rs index 0161bd7..40e8c0a 100644 --- a/src/commands/setup.rs +++ b/src/commands/setup.rs @@ -1,14 +1,14 @@ use std::{fs::File, path::Path}; -use crate::{config::Cfg, db::db_setup, error::MLE, devdir}; +use crate::{config::Cfg, db::db_setup, devdir, error::MLE}; pub async fn setup(config: Cfg) -> MLE<()> { let db_file = devdir(format!("{}/data.db", config.data).as_str()); - + if !Path::new(&db_file).exists() { create(config, db_file)?; } - + /* match s_config_get_version(config.clone()) { Ok(ver) => { @@ -21,12 +21,11 @@ pub async fn setup(config: Cfg) -> MLE<()> { Err(..) => to_02(config).await? }; */ - + Ok(()) } fn create(config: Cfg, db_file: String) -> MLE<()> { - println!("Create database"); File::create(db_file)?; @@ -44,7 +43,7 @@ fn create(config: Cfg, db_file: String) -> MLE<()> { // let full_list = lists_get(config.clone(), String::from(&list))?; // // let versions = userlist_get_all_current_version_ids(config.clone(), full_list.clone().id)?; -// +// // let raw_versions = get_raw_versions(String::from(&config.apis.modrinth), versions).await; // // for ver in raw_versions { @@ -69,4 +68,3 @@ fn create(config: Cfg, db_file: String) -> MLE<()> { // } // s_config_update_version(config, String::from("0.4")) //} - diff --git a/src/commands/update.rs b/src/commands/update.rs index e5751c0..3d9578b 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -1,14 +1,30 @@ -use crate::{config::Cfg, modrinth::{versions, extract_current_version, Version}, db::{userlist_get_all_ids, userlist_get_applicable_versions, userlist_change_versions, userlist_get_current_version, userlist_get_set_version, mods_get_info}, List, files::{delete_version, download_versions, disable_version, clean_list_dir}, error::{MLE, MLError, ErrorType}}; - -pub async fn update(config: Cfg, liststack: Vec, clean: bool, direct_download: bool, delete_old: bool) -> MLE<()> { +use crate::{ + config::Cfg, + db::{ + mods_get_info, userlist_change_versions, userlist_get_all_ids, + userlist_get_applicable_versions, userlist_get_current_version, userlist_get_set_version, + }, + error::{ErrorType, MLError, MLE}, + files::{clean_list_dir, delete_version, disable_version, download_versions}, + modrinth::{extract_current_version, versions, Version}, + List, +}; + +pub async fn 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)?; - + let mut current_versions: Vec<(String, String)> = vec![]; - + println!(" └Update mods:"); let mut updatestack: Vec = vec![]; - + for id in mods { let info = mods_get_info(config.clone(), &id)?; println!("\t└{}", info.title); @@ -19,27 +35,39 @@ pub async fn update(config: Cfg, liststack: Vec, clean: bool, direct_downl } //Getting current installed version for disable or delete - let disable_version = userlist_get_current_version(config.clone(), ¤t_list.id, &id)?; + let disable_version = + userlist_get_current_version(config.clone(), ¤t_list.id, &id)?; updatestack.push( - match specific_update(config.clone(), clean, current_list.clone(), String::from(&id)).await { + match specific_update( + config.clone(), + clean, + current_list.clone(), + String::from(&id), + ) + .await + { Ok(ver) => { current_versions.push((disable_version, id)); ver - }, + } Err(e) => { if e.to_string() == "Mod: NO_UPDATE_AVAILABLE" { - println!("\t └No new version found for the specified minecraft version"); + println!( + "\t └No new version found for the specified minecraft version" + ); } else { return Err(e); }; continue; } - } + }, ) - }; + } - if clean { clean_list_dir(¤t_list)?; }; + if clean { + clean_list_dir(¤t_list)?; + }; if direct_download && !updatestack.is_empty() { download_versions(current_list.clone(), config.clone(), updatestack).await?; @@ -50,7 +78,7 @@ pub async fn update(config: Cfg, liststack: Vec, clean: bool, direct_downl if delete_old { println!("\t └Delete version {}", ver.0); delete_version(current_list.clone(), ver.0)?; - } else if ver.0 != "NONE" { + } else if ver.0 != "NONE" { println!("\t └Disable version {}", ver.0); disable_version(config.clone(), current_list.clone(), ver.0, ver.1)?; }; @@ -63,10 +91,11 @@ pub async fn update(config: Cfg, liststack: Vec, clean: bool, direct_downl } async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> MLE { - let applicable_versions = versions(&config.apis.modrinth, String::from(&id), list.clone()).await; - + let applicable_versions = + versions(&config.apis.modrinth, String::from(&id), list.clone()).await; + let mut versions: Vec = vec![]; - + if !applicable_versions.is_empty() { for ver in &applicable_versions { versions.push(String::from(&ver.id)); @@ -77,8 +106,14 @@ async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> ML let mut current: Vec = vec![]; //TODO Split clean and no match - if clean || (versions.join("|") != userlist_get_applicable_versions(config.clone(), String::from(&list.id), String::from(&id))?) { - + if clean + || (versions.join("|") + != userlist_get_applicable_versions( + config.clone(), + String::from(&list.id), + String::from(&id), + )?) + { let current_str = extract_current_version(applicable_versions.clone())?; if clean { @@ -89,35 +124,54 @@ async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> ML }; //get new versions - let current_ver = match applicable_versions.into_iter().find(|ver| ver.id == current_str).ok_or("!no current version in applicable_versions") { + let current_ver = match applicable_versions + .into_iter() + .find(|ver| ver.id == current_str) + .ok_or("!no current version in applicable_versions") + { Ok(v) => Ok(v), Err(e) => Err(MLError::new(ErrorType::Other, e)), }?; current.push(current_ver.clone()); //TODO implement version selection if no primary - let link = match current_ver.files.into_iter().find(|f| f.primary).ok_or("!no primary in links") { + let link = match current_ver + .files + .into_iter() + .find(|f| f.primary) + .ok_or("!no primary in links") + { Ok(p) => Ok(p), Err(e) => Err(MLError::new(ErrorType::Other, e)), - }?.url; + }? + .url; userlist_change_versions(config, list.id, current_str, versions.join("|"), link, id)?; } - if current.is_empty() { return Err(MLError::new(ErrorType::ModError, "NO_UPDATE_AVAILABLE")) }; - + if current.is_empty() { + return Err(MLError::new(ErrorType::ModError, "NO_UPDATE_AVAILABLE")); + }; + //println!(" └✔️"); Ok(current[0].clone()) } #[tokio::test] async fn download_updates_test() { + use crate::{ + modrinth::{Hash, Version, VersionFile, VersionType}, + List, Modloader, + }; - use crate::{modrinth::{Version, VersionFile, Hash, VersionType}, Modloader, List}; - let config = Cfg::init("modlist.toml").unwrap(); - let current_list = List { id: String::from("..."), mc_version: String::from("..."), modloader: Modloader::Fabric, download_folder: String::from("./dev/tests/dl") }; - - let versions = vec![Version { + let current_list = List { + id: String::from("..."), + mc_version: String::from("..."), + modloader: Modloader::Fabric, + download_folder: String::from("./dev/tests/dl"), + }; + + let versions = vec![Version { id: "dEqtGnT9".to_string(), project_id: "kYuIpRLv".to_string(), author_id: "Qnt13hO8".to_string(), @@ -147,5 +201,7 @@ async fn download_updates_test() { "fabric".to_string() ] }]; - assert!(download_versions(current_list, config, versions).await.is_ok()) + assert!(download_versions(current_list, config, versions) + .await + .is_ok()) } diff --git a/src/config.rs b/src/config.rs index 075d884..1b54d5f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,8 +1,11 @@ -use std::{fs::File, io::{Read, Write}}; +use std::{ + fs::File, + io::{Read, Write}, +}; -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; -use crate::{error::MLE, devdir}; +use crate::{devdir, error::MLE}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Cfg { @@ -24,7 +27,12 @@ impl Cfg { Err(err) => { if err.kind() == std::io::ErrorKind::NotFound { println!("No config file found, creating one"); - let default_cfg = Cfg { data: String::from("./"), apis: Apis { modrinth: String::from("https://api.modrinth.com/v2/") } }; + let default_cfg = Cfg { + data: String::from("./"), + apis: Apis { + modrinth: String::from("https://api.modrinth.com/v2/"), + }, + }; let mut file = File::create(devdir(configfile.to_str().unwrap()))?; println!("Created config file"); file.write_all(toml::to_string(&default_cfg)?.as_bytes())?; diff --git a/src/db.rs b/src/db.rs index 2c48cab..09d54c2 100644 --- a/src/db.rs +++ b/src/db.rs @@ -2,17 +2,21 @@ use std::io::{Error, ErrorKind}; use rusqlite::Connection; -use crate::{Modloader, config::Cfg, List, devdir, error::{MLE, MLError, ErrorType}}; +use crate::{ + config::Cfg, + devdir, + error::{ErrorType, MLError, MLE}, + List, Modloader, +}; //MODS pub fn mods_insert(config: Cfg, id: &str, slug: &str, name: &str) -> MLE<()> { - let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; connection.execute( "INSERT INTO mods (id, slug, title) VALUES (?1, ?2, ?3)", - [id, slug, name.replace('\'', "").as_str()] + [id, slug, name.replace('\'', "").as_str()], )?; Ok(()) @@ -21,13 +25,11 @@ pub fn mods_insert(config: Cfg, id: &str, slug: &str, name: &str) -> MLE<()> { pub fn mods_get_all_ids(config: Cfg) -> Result, Box> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); - + let mut mods: Vec = Vec::new(); let mut stmt = connection.prepare("SELECT id FROM mods")?; - let id_iter = stmt.query_map([], |row| { - row.get::(0) - })?; + let id_iter = stmt.query_map([], |row| row.get::(0))?; for id in id_iter { mods.push(id?); @@ -49,36 +51,33 @@ pub fn mods_get_all_ids(config: Cfg) -> Result, Box MLE { - //TODO check if "slug" is id let data = devdir(format!("{}/data.db", data).as_str()); let connection = Connection::open(data)?; - + let mut mod_id = String::new(); //get from slug let mut stmt = connection.prepare("SELECT id FROM mods WHERE slug = ?")?; - let id_iter = stmt.query_map([slug], |row| { - row.get::(0) - })?; + let id_iter = stmt.query_map([slug], |row| row.get::(0))?; for id in id_iter { mod_id = id?; - }; + } //get from title if no id found from slug if mod_id.is_empty() { let mut stmt = connection.prepare("SELECT id FROM mods WHERE title = ?")?; - let id_iter = stmt.query_map([slug], |row| { - row.get::(0) - })?; + let id_iter = stmt.query_map([slug], |row| row.get::(0))?; for id in id_iter { mod_id = id?; - }; + } } - if mod_id.is_empty() { return Err(MLError::new(ErrorType::DBError, "GI_MOD_NOT_FOUND")) }; + if mod_id.is_empty() { + return Err(MLError::new(ErrorType::DBError, "GI_MOD_NOT_FOUND")); + }; Ok(mod_id) } @@ -91,17 +90,23 @@ pub struct ModInfo { pub fn mods_get_info(config: Cfg, id: &str) -> MLE { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; - + let mut mod_info: Option = None; let mut stmt = connection.prepare("SELECT title, slug FROM mods WHERE id = ?")?; let name_iter = stmt.query_map([id], |row| { - Ok(vec![row.get::(0)?, row.get::(1)?]) + Ok(vec![ + row.get::(0)?, + row.get::(1)?, + ]) })?; for info in name_iter { let i = info?; - mod_info = Some(ModInfo { title: String::from(&i[0]), slug: String::from(&i[1]) }); - }; + mod_info = Some(ModInfo { + title: String::from(&i[0]), + slug: String::from(&i[1]), + }); + } match mod_info.is_none() { true => Err(MLError::new(ErrorType::DBError, "GN_MOD_NOT_FOUND")), @@ -110,7 +115,6 @@ pub fn mods_get_info(config: Cfg, id: &str) -> MLE { } pub fn mods_remove(config: Cfg, id: String) -> MLE<()> { - println!("Removing mod {} from database", id); let data = devdir(format!("{}/data.db", config.data).as_str()); @@ -131,27 +135,42 @@ pub fn mods_get_versions(config: Cfg, mods: Vec) -> MLE = Vec::new(); - let mut stmt = connection.prepare(format!("SELECT id, versions, title FROM mods {}", wherestr).as_str())?; + let mut stmt = connection + .prepare(format!("SELECT id, versions, title FROM mods {}", wherestr).as_str())?; let id_iter = stmt.query_map([], |row| { - Ok(vec![row.get::(0)?, row.get::(1)?, row.get::(2)?]) + Ok(vec![ + row.get::(0)?, + row.get::(1)?, + row.get::(2)?, + ]) })?; for ver in id_iter { let version = ver?; - println!("\t({}) Get versions from the database", String::from(&version[2])); + println!( + "\t({}) Get versions from the database", + String::from(&version[2]) + ); //println!("Found versions {} for mod {}", version[1], version[0]); - versionmaps.push(DBModlistVersions { mod_id: String::from(&version[0]), versions: String::from(&version[1]) }) - }; + versionmaps.push(DBModlistVersions { + mod_id: String::from(&version[0]), + versions: String::from(&version[1]), + }) + } match versionmaps.is_empty() { true => Err(MLError::new(ErrorType::DBError, "MODS_MODS_NOT_FOUND")), @@ -160,16 +179,37 @@ pub fn mods_get_versions(config: Cfg, mods: Vec) -> MLE, current_link: &str, set_version: bool) -> MLE<()> { +pub fn userlist_insert( + config: Cfg, + list_id: &str, + mod_id: &str, + current_version: &str, + applicable_versions: Vec, + current_link: &str, + set_version: bool, +) -> MLE<()> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; - + let sv = match set_version { true => "1", false => "0", }; - - connection.execute(format!("INSERT INTO {} VALUES (?1, ?2, ?3, ?4, 'NONE', ?5)", list_id).as_str(), [mod_id, current_version, applicable_versions.join("|").as_str(), current_link, sv])?; + + connection.execute( + format!( + "INSERT INTO {} VALUES (?1, ?2, ?3, ?4, 'NONE', ?5)", + list_id + ) + .as_str(), + [ + mod_id, + current_version, + applicable_versions.join("|").as_str(), + current_link, + sv, + ], + )?; Ok(()) } @@ -180,14 +220,12 @@ pub fn userlist_get_all_ids(config: Cfg, list_id: String) -> MLE> { let mut mod_ids: Vec = Vec::new(); let mut stmt = connection.prepare(format!("SELECT mod_id FROM {}", list_id).as_str())?; - let id_iter = stmt.query_map([], |row| { - row.get::(0) - })?; + let id_iter = stmt.query_map([], |row| row.get::(0))?; for id in id_iter { //println!("Found id {:?}", id.as_ref().unwrap()); mod_ids.push(id?) - }; + } match mod_ids.is_empty() { true => Err(MLError::new(ErrorType::DBError, "NO_MODS")), @@ -199,24 +237,34 @@ pub fn userlist_remove(config: Cfg, list_id: &str, mod_id: &str) -> MLE<()> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; - connection.execute(format!("DELETE FROM {} WHERE mod_id = ?", list_id).as_str(), [mod_id])?; + connection.execute( + format!("DELETE FROM {} WHERE mod_id = ?", list_id).as_str(), + [mod_id], + )?; Ok(()) } - -pub fn userlist_get_applicable_versions(config: Cfg, list_id: String, mod_id: String) -> MLE { +pub fn userlist_get_applicable_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(); let mut version: String = String::new(); - let mut stmt = connection.prepare(format!("SELECT applicable_versions FROM {} WHERE mod_id = ?", list_id).as_str())?; - let ver_iter = stmt.query_map([mod_id], |row| { - row.get::(0) - })?; + let mut stmt = connection.prepare( + format!( + "SELECT applicable_versions FROM {} WHERE mod_id = ?", + list_id + ) + .as_str(), + )?; + let ver_iter = stmt.query_map([mod_id], |row| row.get::(0))?; for ver in ver_iter { version = ver?; - }; + } match version.is_empty() { true => Err(MLError::new(ErrorType::DBError, "GAV_MOD_NOT_FOUND")), @@ -224,22 +272,31 @@ pub fn userlist_get_applicable_versions(config: Cfg, list_id: String, mod_id: St } } -pub fn userlist_get_all_applicable_versions_with_mods(config: Cfg, list_id: String) -> MLE> { +pub fn userlist_get_all_applicable_versions_with_mods( + config: Cfg, + list_id: String, +) -> MLE> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; let mut versions: Vec<(String, String)> = Vec::new(); - let mut stmt = connection.prepare(format!("SELECT mod_id, applicable_versions FROM {}", list_id).as_str())?; + let mut stmt = connection + .prepare(format!("SELECT mod_id, applicable_versions FROM {}", list_id).as_str())?; let id_iter = stmt.query_map([], |row| { - Ok(vec![row.get::(0)?, row.get::(1)?]) + Ok(vec![ + row.get::(0)?, + row.get::(1)?, + ]) })?; for ver in id_iter { let out = ver?; versions.push((out[0].to_owned(), out[1].to_owned())); - }; + } - if versions.is_empty() { return Err(MLError::new(ErrorType::DBError, "NO_MODS_ON_LIST")); }; + if versions.is_empty() { + return Err(MLError::new(ErrorType::DBError, "NO_MODS_ON_LIST")); + }; Ok(versions) } @@ -249,14 +306,13 @@ pub fn userlist_get_current_version(config: Cfg, list_id: &str, mod_id: &str) -> let connection = Connection::open(data).unwrap(); let mut version: String = String::new(); - let mut stmt = connection.prepare(format!("SELECT current_version FROM {} WHERE mod_id = ?", list_id).as_str())?; - let ver_iter = stmt.query_map([&mod_id], |row| { - row.get::(0) - })?; + let mut stmt = connection + .prepare(format!("SELECT current_version FROM {} WHERE mod_id = ?", list_id).as_str())?; + let ver_iter = stmt.query_map([&mod_id], |row| row.get::(0))?; for ver in ver_iter { version = ver?; - }; + } match version.is_empty() { true => Err(MLError::new(ErrorType::DBError, "GCV_MOD_NOT_FOUND")), @@ -264,63 +320,88 @@ pub fn userlist_get_current_version(config: Cfg, list_id: &str, mod_id: &str) -> } } -pub fn userlist_get_all_current_version_ids(config: Cfg, list_id: String) -> Result, Box> { +pub fn userlist_get_all_current_version_ids( + config: Cfg, + list_id: String, +) -> Result, Box> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; let mut versions: Vec = Vec::new(); - let mut stmt = connection.prepare(format!("SELECT current_version FROM {}", list_id).as_str())?; - let id_iter = stmt.query_map([], |row| { - row.get::(0) - })?; + let mut stmt = + connection.prepare(format!("SELECT current_version FROM {}", list_id).as_str())?; + let id_iter = stmt.query_map([], |row| row.get::(0))?; for id in id_iter { versions.push(id?); - }; + } - if versions.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::Other, "NO_MODS_ON_LIST"))); }; + if versions.is_empty() { + return Err(Box::new(std::io::Error::new( + ErrorKind::Other, + "NO_MODS_ON_LIST", + ))); + }; Ok(versions) } -pub fn userlist_get_all_current_versions_with_mods(config: Cfg, list_id: String) -> Result, Box> { +pub fn userlist_get_all_current_versions_with_mods( + config: Cfg, + list_id: String, +) -> Result, Box> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; let mut versions: Vec<(String, String)> = Vec::new(); - let mut stmt = connection.prepare(format!("SELECT mod_id, current_version FROM {}", list_id).as_str())?; + let mut stmt = + connection.prepare(format!("SELECT mod_id, current_version FROM {}", list_id).as_str())?; let id_iter = stmt.query_map([], |row| { - Ok(vec![row.get::(0)?, row.get::(1)?]) + Ok(vec![ + row.get::(0)?, + row.get::(1)?, + ]) })?; for ver in id_iter { let out = ver?; versions.push((out[0].to_owned(), out[1].to_owned())); - }; + } - if versions.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::Other, "NO_MODS_ON_LIST"))); }; + if versions.is_empty() { + return Err(Box::new(std::io::Error::new( + ErrorKind::Other, + "NO_MODS_ON_LIST", + ))); + }; Ok(versions) } -pub fn userlist_get_set_version(config:Cfg, list_id: &str, mod_id: &str) -> MLE { +pub fn userlist_get_set_version(config: Cfg, list_id: &str, mod_id: &str) -> MLE { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); let mut set_version: bool = false; - let mut stmt = connection.prepare(format!("SELECT set_version FROM {} WHERE mod_id = ?", list_id).as_str())?; - let ver_iter = stmt.query_map([&mod_id], |row| { - row.get::(0) - })?; + let mut stmt = connection + .prepare(format!("SELECT set_version FROM {} WHERE mod_id = ?", list_id).as_str())?; + let ver_iter = stmt.query_map([&mod_id], |row| row.get::(0))?; for ver in ver_iter { set_version = ver?; - }; + } Ok(set_version) } -pub fn userlist_change_versions(config: Cfg, list_id: String, current_version: String, versions: String, link: String, mod_id: String) -> MLE<()> { +pub fn userlist_change_versions( + config: Cfg, + list_id: String, + current_version: String, + versions: String, + link: String, + mod_id: String, +) -> MLE<()> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; @@ -328,33 +409,45 @@ 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) -> MLE<()> { +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)?; - - 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" { + + 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), }; - - connection.execute(format!("UPDATE {} SET disabled_versions = ?1 WHERE mod_id = ?2", list_id).as_str(), [disabled_versions, mod_id])?; + + connection.execute( + format!( + "UPDATE {} SET disabled_versions = ?1 WHERE mod_id = ?2", + list_id + ) + .as_str(), + [disabled_versions, mod_id], + )?; Ok(()) } -pub fn userlist_get_disabled_versions(config:Cfg, list_id: String, mod_id: String) -> MLE { +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(); let mut version: String = String::new(); - let mut stmt = connection.prepare(format!("SELECT disabled_versions FROM {} WHERE mod_id = ?", list_id).as_str())?; - let ver_iter = stmt.query_map([mod_id], |row| { - row.get::(0) - })?; + let mut stmt = connection + .prepare(format!("SELECT disabled_versions FROM {} WHERE mod_id = ?", list_id).as_str())?; + let ver_iter = stmt.query_map([mod_id], |row| row.get::(0))?; for ver in ver_iter { version = ver?; - }; + } match version.is_empty() { true => Err(MLError::new(ErrorType::DBError, "GDV_MOD_NOT_FOUND")), @@ -362,36 +455,57 @@ pub fn userlist_get_disabled_versions(config:Cfg, list_id: String, mod_id: Strin } } -pub fn userlist_get_all_downloads(config: Cfg, list_id: String) -> Result, Box> { +pub fn userlist_get_all_downloads( + config: Cfg, + list_id: String, +) -> Result, Box> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); let mut links: Vec = Vec::new(); - let mut stmt = connection.prepare(format!("SELECT current_download FROM {}", list_id).as_str())?; - let link_iter = stmt.query_map([], |row| { - row.get::(0) - })?; + 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 { let l = link?; println!("Found link {}", String::from(&l)); links.push(l) - }; + } - if links.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::Other, "NO_MODS_ON_LIST"))); }; + if links.is_empty() { + return Err(Box::new(std::io::Error::new( + ErrorKind::Other, + "NO_MODS_ON_LIST", + ))); + }; Ok(links) } //lists ///Inserts into lists table and creates new table -pub fn lists_insert(config: Cfg, id: String, mc_version: String, mod_loader: Modloader, download_folder: String) -> MLE<()> { +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.to_string(), 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', 'set_version' INTEGER, CONSTRAINT {}_PK PRIMARY KEY (mod_id) )", id, id).as_str(), [])?; Ok(()) @@ -410,20 +524,37 @@ 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(); - let mut list = List { id: String::new(), mc_version: String::new(), modloader: Modloader::Fabric, download_folder: String::new() }; - let mut stmt = connection.prepare("SELECT mc_version, modloader, download_folder FROM lists WHERE id = ?")?; + let mut list = List { + id: String::new(), + mc_version: String::new(), + modloader: Modloader::Fabric, + download_folder: String::new(), + }; + let mut stmt = connection + .prepare("SELECT mc_version, modloader, download_folder FROM lists WHERE id = ?")?; let list_iter = stmt.query_map([&list_id], |row| { - Ok(vec![row.get::(0)?, row.get::(1)?, row.get::(2)?]) + Ok(vec![ + row.get::(0)?, + row.get::(1)?, + row.get::(2)?, + ]) })?; for l in list_iter { let li = l?; - list = List { id: String::from(&list_id), mc_version: String::from(&li[0]), modloader: Modloader::from(&li[1])?, download_folder: String::from(&li[2]) }; - }; + list = List { + id: String::from(&list_id), + mc_version: String::from(&li[0]), + modloader: Modloader::from(&li[1])?, + download_folder: String::from(&li[2]), + }; + } + + if list.id.is_empty() { + return Err(MLError::new(ErrorType::DBError, "LIST_NOT_FOUND")); + } - if list.id.is_empty() { return Err(MLError::new(ErrorType::DBError, "LIST_NOT_FOUND")); } - Ok(list) } @@ -431,23 +562,24 @@ pub fn lists_version(config: Cfg, list_id: &str, version: &str) -> MLE<()> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data).unwrap(); - connection.execute("UPDATE lists SET mc_version = ? WHERE id = ?", [version, list_id])?; + connection.execute( + "UPDATE lists SET mc_version = ? WHERE id = ?", + [version, list_id], + )?; Ok(()) } 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(); - + let mut list_ids: Vec = Vec::new(); let mut stmt = connection.prepare("SELECT id FROM lists")?; - let id_iter = stmt.query_map([], |row| { - row.get::(0) - })?; + let id_iter = stmt.query_map([], |row| row.get::(0))?; for id in id_iter { list_ids.push(id?) - }; + } match list_ids.is_empty() { true => Err(MLError::new(ErrorType::DBError, "NO_LISTS")), @@ -460,35 +592,50 @@ pub fn config_change_current_list(config: Cfg, id: String) -> MLE<()> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; - connection.execute("UPDATE user_config SET value = ? WHERE id = 'current_list'", [id])?; + connection.execute( + "UPDATE user_config SET value = ? WHERE id = 'current_list'", + [id], + )?; Ok(()) } 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(); - + let mut list_id = String::new(); let mut stmt = connection.prepare("SELECT value FROM user_config WHERE id = 'current_list'")?; - let list_iter = stmt.query_map([], |row| { - row.get::(0) - })?; + let list_iter = stmt.query_map([], |row| row.get::(0))?; for list in list_iter { list_id = list?; - }; + } + + if list_id.is_empty() { + return Err(MLError::new(ErrorType::DBError, "NO_CURRENT_LIST")); + } - if list_id.is_empty() { return Err(MLError::new(ErrorType::DBError, "NO_CURRENT_LIST")); } - Ok(list_id) } //SETUP(UPDATES) -pub fn s_userlist_update_download(config: Cfg, list_id: String, mod_id: String, link: String) -> Result<(), Box> { +pub fn s_userlist_update_download( + config: Cfg, + list_id: String, + mod_id: String, + link: String, +) -> Result<(), Box> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; - connection.execute(format!("UPDATE {} SET current_download = ?1 WHERE mod_id = ?2", list_id).as_str(), [link, mod_id])?; + connection.execute( + format!( + "UPDATE {} SET current_download = ?1 WHERE mod_id = ?2", + list_id + ) + .as_str(), + [link, mod_id], + )?; Ok(()) } @@ -496,7 +643,10 @@ pub fn s_config_create_version(config: Cfg) -> Result<(), Box Result<(), Box Result> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; - + let mut version: String = String::new(); let mut stmt = connection.prepare("SELECT value FROM user_config WHERE id = 'db_version'")?; - let ver_iter = stmt.query_map([], |row| { - row.get::(0) - })?; + let ver_iter = stmt.query_map([], |row| row.get::(0))?; for ver in ver_iter { version = ver?; - }; + } - if version.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::Other, "NO_DBVERSION"))); }; + if version.is_empty() { + return Err(Box::new(std::io::Error::new( + ErrorKind::Other, + "NO_DBVERSION", + ))); + }; Ok(version) } -pub fn s_insert_column(config: Cfg, table: String, column: String, c_type: String, default: Option) -> Result<(), Box> { +pub fn s_insert_column( + config: Cfg, + table: String, + column: String, + c_type: String, + default: Option, +) -> Result<(), Box> { let data = devdir(format!("{}/data.db", config.data).as_str()); let connection = Connection::open(data)?; let mut sql = format!("ALTER TABLE {} ADD '{}' {}", table, column, c_type); - + if default.is_some() { sql = format!("{} DEFAULT {}", sql, default.unwrap()); } @@ -541,7 +703,6 @@ pub fn s_insert_column(config: Cfg, table: String, column: String, c_type: Strin } pub fn db_setup(config: Cfg) -> MLE<()> { - println!("Initiating database"); let data = devdir(format!("{}/data.db", config.data).as_str()); @@ -554,6 +715,6 @@ pub fn db_setup(config: Cfg) -> MLE<()> { INSERT INTO 'user_config' VALUES ( 'db_version', '0.5' ); INSERT INTO 'user_config' VALUES ( 'current_list', '...' )", )?; - + Ok(()) } diff --git a/src/error.rs b/src/error.rs index 794a919..bd6e3da 100644 --- a/src/error.rs +++ b/src/error.rs @@ -43,49 +43,70 @@ impl fmt::Display for MLError { ErrorType::LibReq => write!(f, "REQWEST"), ErrorType::LibChrono => write!(f, "Chrono error: {}", self.message), ErrorType::IoError => write!(f, "IO"), - ErrorType::Other => write!(f, "OTHER") + ErrorType::Other => write!(f, "OTHER"), } } } impl From for MLError { fn from(error: reqwest::Error) -> Self { - Self { etype: ErrorType::LibReq, message: error.to_string() } + 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() } + 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() } + 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() } + Self { + etype: ErrorType::LibToml, + message: error.to_string(), + } } } impl From for MLError { fn from(error: chrono::ParseError) -> Self { - Self { etype: ErrorType::LibChrono, message: error.to_string() } + Self { + etype: ErrorType::LibChrono, + message: error.to_string(), + } } } impl From for MLError { fn from(error: std::io::Error) -> Self { - Self { etype: ErrorType::IoError, message: error.to_string() } + Self { + etype: ErrorType::IoError, + message: error.to_string(), + } } } impl MLError { pub fn new(etype: ErrorType, message: &str) -> Self { - Self { etype, message: String::from(message) } + Self { + etype, + message: String::from(message), + } } } diff --git a/src/files.rs b/src/files.rs index 6519c6a..6160cb4 100644 --- a/src/files.rs +++ b/src/files.rs @@ -1,11 +1,20 @@ -use std::{fs::{File, read_dir, remove_file, rename}, io::Write, collections::HashMap}; use futures_util::StreamExt; use reqwest::Client; - -use crate::{List, modrinth::Version, db::{userlist_add_disabled_versions, mods_get_info}, config::Cfg, error::{MLE, MLError, ErrorType}}; +use std::{ + collections::HashMap, + fs::{read_dir, remove_file, rename, File}, + io::Write, +}; + +use crate::{ + config::Cfg, + db::{mods_get_info, userlist_add_disabled_versions}, + error::{ErrorType, MLError, MLE}, + modrinth::Version, + List, +}; pub async fn download_versions(list: List, config: Cfg, versions: Vec) -> MLE { - let dl_path = String::from(&list.download_folder); println!(" └Download mods to {}", dl_path); @@ -21,7 +30,13 @@ pub async fn download_versions(list: List, config: Cfg, versions: Vec) 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); + let filename = format!( + "{}.mr.{}.{}.{}", + splitname.join("."), + ver.project_id, + ver.id, + extension + ); download_file(primary_file.url, list.clone().download_folder, filename).await?; //tokio::time::sleep(std::time::Duration::new(3, 0)).await; println!(" ✓"); @@ -32,10 +47,7 @@ pub async fn download_versions(list: List, config: Cfg, versions: Vec) async fn download_file(url: String, path: String, name: String) -> MLE<()> { let dl_path_file = format!("{}/{}", path, name); - let res = Client::new() - .get(String::from(&url)) - .send() - .await?; + let res = Client::new().get(String::from(&url)).send().await?; // download chunks let mut file = File::create(&dl_path_file)?; @@ -49,7 +61,12 @@ async fn download_file(url: String, path: String, name: String) -> MLE<()> { Ok(()) } -pub fn disable_version(config: Cfg, current_list: List, versionid: String, mod_id: String) -> MLE<()> { +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); @@ -63,7 +80,7 @@ pub fn disable_version(config: Cfg, current_list: List, versionid: String, mod_i pub fn delete_version(list: List, version: String) -> MLE<()> { let file = get_file_path(list, version)?; - + remove_file(file)?; Ok(()) @@ -76,19 +93,24 @@ pub fn get_file_path(list: List, versionid: String) -> MLE { if path.is_file() { let pathstr = match path.to_str().ok_or("") { Ok(s) => s, - Err(..) => return Err(MLError::new(ErrorType::Other, "INVALID_PATH")) + 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 = match names.get(&versionid).ok_or("") { Ok(n) => n, - Err(..) => return Err(MLError::new(ErrorType::ArgumentError, "VERSION_NOT_FOUND_IN_FILES")) + Err(..) => { + return Err(MLError::new( + ErrorType::ArgumentError, + "VERSION_NOT_FOUND_IN_FILES", + )) + } }; - + Ok(filename.to_owned()) } @@ -99,7 +121,10 @@ pub fn get_downloaded_versions(list: List) -> MLE> { if path.is_file() && path.extension().ok_or("BAH").unwrap() == "jar" { let pathstr = path.to_str().ok_or("BAH").unwrap(); let namesplit: Vec<&str> = pathstr.split('.').collect(); - versions.insert(String::from(namesplit[namesplit.len() - 3]), String::from(namesplit[namesplit.len() - 2])); + versions.insert( + String::from(namesplit[namesplit.len() - 3]), + String::from(namesplit[namesplit.len() - 2]), + ); } } Ok(versions) @@ -111,6 +136,6 @@ pub fn clean_list_dir(list: &List) -> MLE<()> { for entry in std::fs::read_dir(dl_path)? { let entry = entry?; std::fs::remove_file(entry.path())?; - }; + } Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index 9db907d..43f0fe7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,20 +1,20 @@ pub mod apis; -pub mod config; pub mod commands; +pub mod config; pub mod db; pub mod error; pub mod files; -use std::{path::Path, fmt::Display}; +use std::{fmt::Display, path::Path}; pub use apis::*; pub use commands::*; -use error::{MLE, ErrorType, MLError}; +use error::{ErrorType, MLError, MLE}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Modloader { Fabric, - Forge + Forge, } impl Modloader { @@ -22,7 +22,7 @@ impl Modloader { match string { "forge" => Ok(Modloader::Forge), "fabric" => Ok(Modloader::Fabric), - _ => Err(MLError::new(ErrorType::ArgumentError, "UNKNOWN_MODLOADER")) + _ => Err(MLError::new(ErrorType::ArgumentError, "UNKNOWN_MODLOADER")), } } } diff --git a/src/main.rs b/src/main.rs index e845be1..eb5ee0b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,10 @@ use clap::{Parser, Subcommand}; -use modlist::{config::Cfg, mod_add, mod_remove, db::{lists_get, config_get_current_list, lists_get_all_ids}, IDSelector, download, update, List, get_current_list, import, devdir, export, list_add, Modloader, list_version, list_remove, list_change}; +use modlist::{ + config::Cfg, + db::{config_get_current_list, lists_get, lists_get_all_ids}, + devdir, download, export, get_current_list, import, list_add, list_change, list_remove, + list_version, mod_add, mod_remove, update, IDSelector, List, Modloader, +}; //TODO make default list optional #[derive(Parser)] @@ -17,13 +22,13 @@ enum Commands { }, List { #[command(subcommand)] - command: ListCommands + command: ListCommands, }, Download { /// download all lists #[arg(short, long)] all: bool, - + /// clean all mods before downloading them #[arg(short, long)] clean: bool, @@ -36,11 +41,11 @@ enum Commands { /// download all lists #[arg(short, long)] all: bool, - + /// directly download updated mods #[arg(short, long)] download: bool, - + /// clean all mods before downloading them #[arg(short, long)] clean: bool, @@ -59,7 +64,7 @@ enum Commands { }, Export { /// the list you want to export - list: Option + list: Option, }, } @@ -68,7 +73,7 @@ enum ModCommands { Add { /// id of the mod/version id: String, - + /// set id mode to version #[arg(short, long)] version: bool, @@ -83,7 +88,7 @@ enum ModCommands { /// optional List selection, else default list will be used #[arg(short, long)] - list: Option + list: Option, }, Remove { /// id, name or title of the mod @@ -91,8 +96,8 @@ enum ModCommands { /// optional List selection, else default list will be used #[arg(short, long)] - list: Option - } + list: Option, + }, } #[derive(Subcommand)] @@ -109,12 +114,12 @@ enum ListCommands { }, Remove { /// id, name or title of the list - id: String + id: String, }, List, Change { /// id of the list to change to - id: String + id: String, }, Version { /// list id @@ -129,12 +134,11 @@ enum ListCommands { /// delete disabled versions #[arg(short, long)] remove: bool, - } + }, } #[tokio::main] async fn main() { - let cli = Cli::parse(); let config = Cfg::init("modlist.toml").unwrap(); @@ -143,13 +147,22 @@ async fn main() { //TODO setup? maybe setup on install match cli.command { Commands::Mod { command } => { - match command { #[allow(unused_variables)] - ModCommands::Add { id, version, list, download, lock } => { + ModCommands::Add { + id, + version, + list, + download, + lock, + } => { let listf = match list { Some(list) => lists_get(config.clone(), list).unwrap(), - None => lists_get(config.clone(), config_get_current_list(config.clone()).unwrap()).unwrap(), + None => lists_get( + config.clone(), + config_get_current_list(config.clone()).unwrap(), + ) + .unwrap(), }; let marked_id = match version { @@ -164,15 +177,24 @@ async fn main() { //TODO add success even if no file found let listf = match list { Some(list) => lists_get(config.clone(), list).unwrap(), - None => lists_get(config.clone(), config_get_current_list(config.clone()).unwrap()).unwrap(), + None => lists_get( + config.clone(), + config_get_current_list(config.clone()).unwrap(), + ) + .unwrap(), }; mod_remove(config, &id, listf) } } - }, + } Commands::List { command } => { match command { - ListCommands::Add { id, directory, modloader, version } => { + ListCommands::Add { + id, + directory, + modloader, + version, + } => { let ml = match modloader { Some(ml) => Modloader::from(&ml).unwrap(), //TODO add default modloader to config @@ -187,23 +209,27 @@ async fn main() { }; list_add(config, id, ver, ml, directory) - }, - ListCommands::Remove { id } => { - list_remove(config, id) - }, + } + ListCommands::Remove { id } => list_remove(config, id), ListCommands::List => { todo!() - }, - ListCommands::Change { id } => { - list_change(config, id) - }, - ListCommands::Version { id, version, download, remove } => { - list_version(config, id, version, download, remove).await } + ListCommands::Change { id } => list_change(config, id), + ListCommands::Version { + id, + version, + download, + remove, + } => list_version(config, id, version, download, remove).await, } - }, + } //TODO a add specific list - Commands::Update { all, download, clean, remove } => { + Commands::Update { + all, + download, + clean, + remove, + } => { let mut liststack: Vec = vec![]; if all { let list_ids = lists_get_all_ids(config.clone()).unwrap(); @@ -216,21 +242,26 @@ async fn main() { liststack.push(current) } update(config, liststack, clean, download, remove).await - }, + } //TODO add specific list - Commands::Download { all, clean, remove } => { - download(config, all, clean, remove).await - }, + Commands::Download { all, clean, remove } => download(config, all, clean, remove).await, Commands::Import { file, download } => { let filestr: String = match file { Some(args) => args, - None => devdir(dirs::home_dir().unwrap().join("mlexport.toml").into_os_string().into_string().unwrap().as_str()), + None => devdir( + dirs::home_dir() + .unwrap() + .join("mlexport.toml") + .into_os_string() + .into_string() + .unwrap() + .as_str(), + ), }; import(config, filestr, download).await - }, - Commands::Export { list } => { - export(config, list) - }, - }.unwrap(); + } + Commands::Export { list } => export(config, list), + } + .unwrap(); } -- cgit v1.2.3