From 2d7e0a2fbf1c8a4187e2bf3fdcd592631ab273a0 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Fri, 26 May 2023 17:40:27 +0200 Subject: added full progress? cargo fmt --- src/apis/modrinth.rs | 7 +- src/commands/download.rs | 39 +++++++--- src/commands/io.rs | 34 +++++++-- src/commands/list.rs | 54 +++++++++----- src/commands/modification.rs | 114 +++++++++++++++--------------- src/commands/update.rs | 95 ++++++++++++++++--------- src/config.rs | 6 +- src/db.rs | 41 +++++------ src/error.rs | 6 +- src/files.rs | 77 +++++++++++++------- src/lib.rs | 46 +++++++----- src/main.rs | 164 ++++++++++++++++++++++--------------------- 12 files changed, 406 insertions(+), 277 deletions(-) (limited to 'src') diff --git a/src/apis/modrinth.rs b/src/apis/modrinth.rs index 14ff266..fb3952d 100644 --- a/src/apis/modrinth.rs +++ b/src/apis/modrinth.rs @@ -127,7 +127,7 @@ pub enum GameVersionType { release, snapshot, alpha, - beta + beta, } async fn get(api: &str, path: &str) -> Result>, Box> { @@ -208,7 +208,10 @@ pub fn extract_current_version(versions: Vec) -> MLE { } pub async fn get_game_versions() -> Vec { - let data = get("https://api.modrinth.com/v2/", "tag/game_version").await.unwrap().unwrap(); + let data = get("https://api.modrinth.com/v2/", "tag/game_version") + .await + .unwrap() + .unwrap(); serde_json::from_slice(&data).unwrap() } diff --git a/src/commands/download.rs b/src/commands/download.rs index 7aa0156..dd00ffb 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -1,7 +1,5 @@ +use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; -use indicatif::{MultiProgress, ProgressStyle, ProgressBar}; - -use crate::{STYLE_BAR_POS, PROGRESS_CHARS}; use crate::{config::Cfg, List}; use crate::{ db::userlist_get_all_current_versions_with_mods, @@ -11,12 +9,21 @@ use crate::{ }, modrinth::get_raw_versions, }; - -pub async fn download(config: &Cfg, liststack: Vec, clean: bool, delete_old: bool) -> MLE<()> { - +use crate::{PROGRESS_CHARS, STYLE_BAR_POS}; + +pub async fn download( + config: &Cfg, + liststack: Vec, + clean: bool, + delete_old: bool, +) -> MLE<()> { let mp = MultiProgress::new(); let download_p = mp.add(ProgressBar::new(liststack.len().try_into().unwrap())); - download_p.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); + download_p.set_style( + ProgressStyle::with_template(STYLE_BAR_POS) + .unwrap() + .progress_chars(PROGRESS_CHARS), + ); for current_list in liststack { download_p.set_message(format!("Download in {}", current_list.id)); @@ -67,17 +74,27 @@ pub async fn download(config: &Cfg, liststack: Vec, clean: bool, delete_ol ) .await?; } else { - download_p.println(format!("There are no new versions to download for {}", current_list.id)); + download_p.println(format!( + "There are no new versions to download for {}", + current_list.id + )); } if !to_disable.is_empty() { - let d_p = mp.insert_before(&download_p, ProgressBar::new(to_disable.len().try_into().unwrap())); - d_p.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); + let d_p = mp.insert_before( + &download_p, + ProgressBar::new(to_disable.len().try_into().unwrap()), + ); + d_p.set_style( + ProgressStyle::with_template(STYLE_BAR_POS) + .unwrap() + .progress_chars(PROGRESS_CHARS), + ); for ver in to_disable { if delete_old { d_p.set_message(format!("Delete version {}", ver.1)); d_p.inc(1); - delete_version(current_list.clone(), ver.1)?; + delete_version(¤t_list, ver.1)?; } else { d_p.set_message(format!("Disable version {}", ver.1)); d_p.inc(1); diff --git a/src/commands/io.rs b/src/commands/io.rs index 45e363e..2501583 100644 --- a/src/commands/io.rs +++ b/src/commands/io.rs @@ -1,12 +1,16 @@ +use indicatif::{ProgressBar, ProgressStyle}; use serde::{Deserialize, Serialize}; use std::fs::File; use std::io::prelude::*; use crate::{ config::Cfg, - db::{lists_get, lists_get_all_ids, lists_insert, userlist_get_set_version, userlist_get_all_ids, userlist_get_current_version}, + db::{ + lists_get, lists_get_all_ids, lists_insert, userlist_get_all_ids, + userlist_get_current_version, userlist_get_set_version, + }, error::MLE, - mod_add, IDSelector, List, Modloader, AddMod, + mod_add, AddMod, IDSelector, List, Modloader, STYLE_OPERATION, }; #[derive(Debug, Serialize, Deserialize)] @@ -17,14 +21,14 @@ struct Export { #[derive(Debug, Serialize, Deserialize)] struct ExportVersion { version: String, - set: bool + set: bool, } impl ExportVersion { fn from(config: &Cfg, list_id: &str, mod_id: &str) -> MLE { Ok(Self { version: userlist_get_current_version(config, list_id, mod_id)?, - set: userlist_get_set_version(config, list_id, mod_id)? + set: userlist_get_set_version(config, list_id, mod_id)?, }) } } @@ -64,23 +68,36 @@ impl ExportList { } pub fn export(config: &Cfg, list: Option) -> MLE<()> { + let progress = ProgressBar::new_spinner(); + progress.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + 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); } + let mut lists: Vec = vec![]; for list_id in list_ids { + progress.set_message(format!("Export {}", list_id)); + //TODO download option/ new download on import lists.push(ExportList::from(config, &list_id, true)?); } let toml = toml::to_string(&Export { lists })?; - let filestr = dirs::home_dir().unwrap().join("mlexport.toml"); + let filestr = dirs::home_dir() + .unwrap() + .join("mlexport.toml") + .into_os_string() + .into_string() + .unwrap(); - let mut file = File::create(filestr.into_os_string().into_string().unwrap().as_str())?; + progress.set_message("Create file"); + let mut file = File::create(&filestr)?; file.write_all(toml.as_bytes())?; + progress.finish_with_message(format!("Exported to {}", filestr)); Ok(()) } @@ -108,7 +125,10 @@ pub async fn import(config: &Cfg, file_str: &str, direct_download: bool) -> MLE< let mut ver_ids = vec![]; for id in exportlist.versions { - ver_ids.push(AddMod { id: IDSelector::VersionID(id.version), set_version: id.set} ); + ver_ids.push(AddMod { + id: IDSelector::VersionID(id.version), + set_version: id.set, + }); } mod_add(config, ver_ids, list, direct_download).await?; } diff --git a/src/commands/list.rs b/src/commands/list.rs index 52f14f2..b0a082d 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -1,11 +1,13 @@ +use indicatif::{ProgressBar, ProgressStyle}; + use crate::{ config::Cfg, db::{ - config_change_current_list, config_get_current_list, lists_get, lists_insert, lists_remove, - lists_version, lists_get_all_ids, + config_change_current_list, config_get_current_list, lists_get, lists_get_all_ids, + lists_insert, lists_remove, lists_version, }, - error::{MLE, MLError, ErrorType}, - update, Modloader, + error::{ErrorType, MLError, MLE}, + update, Modloader, STYLE_OPERATION, }; #[derive(Debug, Clone, PartialEq, Eq)] @@ -28,20 +30,35 @@ pub fn list_add( modloader: &Modloader, directory: &str, ) -> MLE<()> { - lists_insert(config, id, mc_version, modloader, directory) + let p = ProgressBar::new_spinner(); + p.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + p.set_message(format!("Create {}", id)); + lists_insert(config, id, mc_version, modloader, directory)?; + p.finish_with_message(format!("Created {}", id)); + Ok(()) } -pub fn list_change(config: &Cfg, id: String) -> MLE<()> { +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_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")); }; - println!("Change default list to: {}", id); - config_change_current_list(config, id) + config_change_current_list(config, id)?; + + p.finish_with_message(format!("Changed default list to {}", id)); + Ok(()) } -pub fn list_remove(config: &Cfg, id: String) -> MLE<()> { - //TODO add logging - lists_remove(config, id) +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_message(format!("Remove {}", id)); + lists_remove(config, id)?; + p.finish_with_message(format!("Removed {}", id)); + Ok(()) } ///Changing the current lists version and updating it @@ -57,17 +74,20 @@ pub async fn list_version( download: bool, delete: bool, ) -> MLE<()> { - println!( + let p = ProgressBar::new_spinner(); + p.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + p.set_message(format!( "Change version for list {} to minecraft version: {}", id, mc_version - ); + )); lists_version(config, id, &mc_version)?; - println!( - "\nCheck for updates for new minecraft version in list {}", - id - ); + p.finish_with_message(format!( + "Changed version for list {} to minecraft version: {}", + id, mc_version + )); + let list = lists_get(config, id)?; update(config, vec![list], true, download, delete).await } diff --git a/src/commands/modification.rs b/src/commands/modification.rs index 8abf913..fdb70c7 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -1,23 +1,23 @@ -use std::{io::Write, collections::HashMap}; +use std::collections::HashMap; -use indicatif::{ProgressBar, ProgressStyle, MultiProgress}; +use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; 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, mods_get_info, + lists_get_all_ids, mods_get_id, mods_get_info, mods_insert, mods_remove, + userlist_get_all_ids, userlist_get_current_version, userlist_insert, userlist_remove, }, error::{ErrorType, MLError, MLE}, files::{delete_version, download_versions}, modrinth::{extract_current_version, get_raw_versions, project, projects, versions, Version}, - List, PROGRESS_CHARS, STYLE_BAR_POS, + List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION, }; #[derive(Debug)] pub struct AddMod { pub id: IDSelector, - pub set_version: bool + pub set_version: bool, } #[derive(Debug, PartialEq, Eq)] @@ -47,9 +47,13 @@ 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())); - add_p.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); + add_p.set_style( + ProgressStyle::with_template(STYLE_BAR_POS) + .unwrap() + .progress_chars(PROGRESS_CHARS), + ); add_p.set_message("Sort ids"); //"Sort" project ids from version ids to be able to handle them differently but in a batch @@ -62,7 +66,7 @@ pub async fn mod_add( } add_p.set_message("Get infos"); - + let mut projectinfo: Vec = Vec::new(); if !mod_ids.is_empty() { projectinfo.append(&mut get_mod_infos(config, mod_ids, list.clone()).await?); @@ -80,11 +84,17 @@ pub async fn mod_add( let mut downloadstack: Vec = Vec::new(); //Adding each mod to the lists and downloadstack - let project_p = mp.insert_before(&add_p, ProgressBar::new(projectinfo.len().try_into().unwrap())); - project_p.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); + let project_p = mp.insert_before( + &add_p, + ProgressBar::new(projectinfo.len().try_into().unwrap()), + ); + project_p.set_style( + ProgressStyle::with_template(STYLE_BAR_POS) + .unwrap() + .progress_chars(PROGRESS_CHARS), + ); for project in projectinfo { - project_p.set_message(format!("Add {}", project.title)); let current_version_id = if project.current_version.is_none() { @@ -116,12 +126,7 @@ pub async fn mod_add( Ok(..) => Ok(..), }?; - match mods_insert( - config, - &project.mod_id, - &project.slug, - &project.title, - ) { + match mods_insert(config, &project.mod_id, &project.slug, &project.title) { Err(e) => { if e.to_string() == "SQL: UNIQUE constraint failed: mods.id" { Ok(..) @@ -152,8 +157,11 @@ pub async fn mod_add( Ok(()) } -async fn get_mod_infos(config: &Cfg, mod_ids: Vec<(String, bool)>, list: List) -> MLE> { - +async fn get_mod_infos( + config: &Cfg, + mod_ids: Vec<(String, bool)>, + list: List, +) -> MLE> { let mut setmap: HashMap = HashMap::new(); let mut ids = vec![]; @@ -197,19 +205,15 @@ async fn get_mod_infos(config: &Cfg, mod_ids: Vec<(String, bool)>, list: List) - .find(|v| v.id == current_id) .unwrap(), ); - + // match primary, if none? - let files = current_version - .clone() - .ok_or("") - .unwrap() - .files; + let files = current_version.clone().ok_or("").unwrap().files; file = match files.clone().into_iter().find(|f| f.primary) { - Some(f) => f, - None => { files[0].clone() } - } - .url; + Some(f) => f, + None => files[0].clone(), + } + .url; for ver in available_versions { available_versions_vec.push(ver.id); @@ -247,7 +251,6 @@ async fn get_mod_infos(config: &Cfg, mod_ids: Vec<(String, bool)>, list: List) - } async fn get_ver_info(config: &Cfg, ver_ids: Vec<(String, bool)>) -> MLE> { - let mut setmap: HashMap = HashMap::new(); let mut ids = vec![]; @@ -271,15 +274,13 @@ async fn get_ver_info(config: &Cfg, ver_ids: Vec<(String, bool)>) -> MLE f, - None => { files[0].clone() } - } - .url; + Some(f) => f, + None => files[0].clone(), + } + .url; projectinfo.push(ProjectInfo { mod_id: String::from(&project.id), @@ -300,34 +301,31 @@ async fn get_ver_info(config: &Cfg, ver_ids: Vec<(String, bool)>) -> MLE MLE<()> { +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()); + let mod_id = mods_get_id(&config.data, id)?; - println!("Remove mod {} from {}", mods_get_info(config, &mod_id)?.title, list.id); + let info = mods_get_info(config, &mod_id)?; + + progress.set_message(format!("Remove {} from {}", info.title, list.id)); + let version = userlist_get_current_version(config, &list.id, &mod_id)?; - print!(" └Remove from list"); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush()?; userlist_remove(config, &list.id, &mod_id)?; - println!(" ✓"); - print!(" └Delete file"); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush()?; + progress.set_message("Delete file"); match delete_version(list, version) { Ok(_) => (), Err(err) => { - if err.to_string() != "User input not accepted: VERSION_NOT_FOUND_IN_FILES" { + if err.to_string() != "User input not accepted: VERSION_NOT_FOUND_IN_FILES" { return Err(err); }; - }, + } }; - println!(" ✓"); - print!(" └Clean main db table"); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush()?; + progress.set_message("Check main list"); let list_ids = lists_get_all_ids(config)?; // Remove mod from main list if not used elsewhere @@ -336,11 +334,11 @@ pub fn mod_remove(config: &Cfg, id: &str, list: List) -> MLE<()> { let mods = match userlist_get_all_ids(config, &id) { Ok(m) => m, Err(err) => { - if err.to_string() == "Database: NO_MODS_USERLIST" { + if err.to_string() == "Database: NO_MODS_USERLIST" { println!(" ✓"); return Ok(()); }; - return Err(err) + return Err(err); } }; if mods.contains(&mod_id) { @@ -350,9 +348,11 @@ pub fn mod_remove(config: &Cfg, id: &str, list: List) -> MLE<()> { } if !mod_used { - mods_remove(config, mod_id)?; + progress.set_message("Remove from main list"); + mods_remove(config, &mod_id)?; }; - println!(" ✓"); + + progress.finish_with_message(format!("Removed {} from {}", info.title, list.id)); Ok(()) } diff --git a/src/commands/update.rs b/src/commands/update.rs index 194bbe5..3aae002 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -1,4 +1,4 @@ -use indicatif::{ProgressBar, ProgressStyle, MultiProgress}; +use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use crate::{ config::Cfg, @@ -19,11 +19,14 @@ pub async fn update( direct_download: bool, delete_old: bool, ) -> MLE<()> { - let mp = MultiProgress::new(); let update_p = mp.add(ProgressBar::new(liststack.len().try_into().unwrap())); - update_p.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); + update_p.set_style( + ProgressStyle::with_template(STYLE_BAR_POS) + .unwrap() + .progress_chars(PROGRESS_CHARS), + ); for current_list in liststack { update_p.set_message(format!("Update {}", current_list.id)); @@ -35,7 +38,11 @@ pub async fn update( let mods = userlist_get_all_ids(config, ¤t_list.id)?; let list_u_p = mp.insert_before(&list_p, ProgressBar::new(mods.len().try_into().unwrap())); - list_u_p.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); + list_u_p.set_style( + ProgressStyle::with_template(STYLE_BAR_POS) + .unwrap() + .progress_chars(PROGRESS_CHARS), + ); let mut current_versions: Vec<(String, String)> = vec![]; let mut updatestack: Vec = vec![]; @@ -43,7 +50,7 @@ pub async fn update( for id in mods { let info = mods_get_info(config, &id)?; list_u_p.set_message(format!("Update {}", info.title)); - + //Skip check if version is set if userlist_get_set_version(config, ¤t_list.id, &id)? { list_u_p.inc(1); @@ -51,19 +58,10 @@ pub async fn update( } //Getting current installed version for disable or delete - let disable_version = - userlist_get_current_version(config, ¤t_list.id, &id)?; + let disable_version = userlist_get_current_version(config, ¤t_list.id, &id)?; updatestack.push( - match specific_update( - config, - clean, - current_list.clone(), - &id, - &list_u_p - ) - .await - { + match specific_update(config, clean, current_list.clone(), &id, &list_u_p).await { Ok(ver) => { current_versions.push((disable_version, id)); ver @@ -89,17 +87,31 @@ pub async fn update( }; if direct_download && !updatestack.is_empty() { - download_versions(current_list.clone(), config.clone(), updatestack, &mp, &list_p).await?; + download_versions( + current_list.clone(), + config.clone(), + updatestack, + &mp, + &list_p, + ) + .await?; //Disable old versions if !clean { - let d_p = mp.insert_before(&list_p, ProgressBar::new(current_versions.len().try_into().unwrap())); - d_p.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); + let d_p = mp.insert_before( + &list_p, + ProgressBar::new(current_versions.len().try_into().unwrap()), + ); + d_p.set_style( + ProgressStyle::with_template(STYLE_BAR_POS) + .unwrap() + .progress_chars(PROGRESS_CHARS), + ); for ver in current_versions { if delete_old { d_p.set_message(format!("Delete version {}", ver.0)); d_p.inc(1); - delete_version(current_list.clone(), 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); @@ -125,9 +137,14 @@ pub async fn update( Ok(()) } -async fn specific_update(config: &Cfg, clean: bool, list: List, id: &str, progress: &ProgressBar) -> MLE { - let applicable_versions = - versions(&config.apis.modrinth, String::from(id), list.clone()).await; +async fn specific_update( + config: &Cfg, + clean: bool, + list: List, + id: &str, + progress: &ProgressBar, +) -> MLE { + let applicable_versions = versions(&config.apis.modrinth, String::from(id), list.clone()).await; let mut versions: Vec = vec![]; @@ -142,15 +159,16 @@ async fn specific_update(config: &Cfg, clean: bool, list: List, id: &str, progre let mut current: Vec = vec![]; if clean || (versions.join("|") - != userlist_get_applicable_versions( - config, - String::from(&list.id), - String::from(id), - )?) + != userlist_get_applicable_versions(config, String::from(&list.id), String::from(id))?) { let current_str = extract_current_version(applicable_versions.clone())?; - if !clean { progress.println(format!("Found new version for {}", mods_get_info(config, id).unwrap().title)); } + if !clean { + progress.println(format!( + "Found new version for {}", + mods_get_info(config, id).unwrap().title + )); + } //get new versions let current_ver = match applicable_versions @@ -166,12 +184,19 @@ async fn specific_update(config: &Cfg, clean: bool, list: List, id: &str, progre let files = ¤t_ver.files; let link = match files.clone().into_iter().find(|f| f.primary) { - Some(f) => f, - None => { files[0].clone() } - } - .url; - - userlist_change_versions(config, list.id, current_str, versions.join("|"), link, id.to_string())?; + Some(f) => f, + None => files[0].clone(), + } + .url; + + userlist_change_versions( + config, + list.id, + current_str, + versions.join("|"), + link, + id.to_string(), + )?; } if current.is_empty() { diff --git a/src/config.rs b/src/config.rs index 54cf768..3858484 100644 --- a/src/config.rs +++ b/src/config.rs @@ -7,7 +7,7 @@ use std::{ use indicatif::{ProgressBar, ProgressStyle}; use serde::{Deserialize, Serialize}; -use crate::{db::db_setup, error::MLE, Modloader, VersionLevel, check_game_versions}; +use crate::{check_game_versions, db::db_setup, error::MLE, Modloader, VersionLevel}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Cfg { @@ -72,7 +72,7 @@ impl Cfg { Err(..) => { create_versions_dummy(&versionfile).await?; check_game_versions(&versionfile, true).await?; - }, + } } Ok(config) @@ -95,7 +95,7 @@ fn create_config(path: &str) -> MLE<()> { versions: cache_dir, defaults: Defaults { modloader: Modloader::Fabric, - version: VersionLevel::Release + version: VersionLevel::Release, }, apis: Apis { modrinth: String::from("https://api.modrinth.com/v2/"), diff --git a/src/db.rs b/src/db.rs index 1f3ad4c..f627ef4 100644 --- a/src/db.rs +++ b/src/db.rs @@ -120,9 +120,7 @@ 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); - +pub fn mods_remove(config: &Cfg, id: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -233,7 +231,10 @@ pub fn userlist_get_all_ids(config: &Cfg, list_id: &str) -> MLE> { } match mod_ids.is_empty() { - true => Err(MLError::new(ErrorType::DBError, &format!("NO_MODS_USERLIST{}", list_id))), + true => Err(MLError::new( + ErrorType::DBError, + &format!("NO_MODS_USERLIST{}", list_id), + )), false => Ok(mod_ids), } } @@ -325,10 +326,7 @@ 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, -) -> MLE> { +pub fn userlist_get_all_current_version_ids(config: &Cfg, list_id: String) -> MLE> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -342,10 +340,7 @@ pub fn userlist_get_all_current_version_ids( } if versions.is_empty() { - return Err(MLError::new( - ErrorType::DBError, - "NO_MODS_ON_LIST", - )); + return Err(MLError::new(ErrorType::DBError, "NO_MODS_ON_LIST")); }; Ok(versions) @@ -441,7 +436,11 @@ pub fn userlist_add_disabled_versions( 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 = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -504,19 +503,14 @@ pub fn lists_insert( connection.execute( "INSERT INTO lists VALUES (?1, ?2, ?3, ?4)", - [ - id, - mc_version, - &mod_loader.to_string(), - download_folder, - ], + [id, 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(()) } -pub fn lists_remove(config: &Cfg, id: String) -> MLE<()> { +pub fn lists_remove(config: &Cfg, id: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -593,7 +587,7 @@ pub fn lists_get_all_ids(config: &Cfg) -> MLE> { } //config -pub fn config_change_current_list(config: &Cfg, id: String) -> MLE<()> { +pub fn config_change_current_list(config: &Cfg, id: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -655,7 +649,10 @@ pub fn s_config_create_version(config: &Cfg) -> Result<(), Box Result<(), Box> { +pub fn s_config_update_version( + config: &Cfg, + ver: String, +) -> Result<(), Box> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; diff --git a/src/error.rs b/src/error.rs index e6afeaa..f981f14 100644 --- a/src/error.rs +++ b/src/error.rs @@ -106,9 +106,11 @@ impl From for MLError { impl From for MLError { fn from(value: serde_json::error::Error) -> Self { - Self { etype: ErrorType::LibJson, message: value.to_string() } + Self { + etype: ErrorType::LibJson, + message: value.to_string(), + } } - } impl MLError { diff --git a/src/files.rs b/src/files.rs index 814f06d..e874d9d 100644 --- a/src/files.rs +++ b/src/files.rs @@ -1,12 +1,13 @@ use futures_util::StreamExt; -use indicatif::{ProgressBar, ProgressStyle, MultiProgress}; +use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use reqwest::Client; -use tokio::task::JoinSet; use std::{ + cmp::min, collections::HashMap, fs::{copy, read_dir, remove_file, rename, File}, - io::Write, cmp::min, + io::Write, }; +use tokio::task::JoinSet; use crate::{ cache::{copy_cached_version, get_cached_versions}, @@ -14,34 +15,61 @@ use crate::{ db::{mods_get_info, userlist_add_disabled_versions}, error::{ErrorType, MLError, MLE}, modrinth::Version, - List, PROGRESS_CHARS, STYLE_SPINNER, STYLE_BAR_BYTE, STYLE_BAR_POS, + List, PROGRESS_CHARS, STYLE_BAR_BYTE, STYLE_BAR_POS, STYLE_SPINNER, }; -pub async fn download_versions(list: List, config: Cfg, versions: Vec, progress: &MultiProgress, progress_before: &ProgressBar) -> MLE<()> { +pub async fn download_versions( + list: List, + config: Cfg, + versions: Vec, + progress: &MultiProgress, + progress_before: &ProgressBar, +) -> MLE<()> { let cached = get_cached_versions(&config.cache); let mut js = JoinSet::new(); let style_spinner = ProgressStyle::with_template(STYLE_SPINNER).unwrap(); - let all = progress.insert_before(progress_before, ProgressBar::new(versions.len().try_into().unwrap())); - all.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); + let all = progress.insert_before( + progress_before, + ProgressBar::new(versions.len().try_into().unwrap()), + ); + all.set_style( + ProgressStyle::with_template(STYLE_BAR_POS) + .unwrap() + .progress_chars(PROGRESS_CHARS), + ); all.set_message(format!("✓Downloading {}", list.id)); - + for ver in versions { let p = progress.insert_before(&all, ProgressBar::new(1)); p.set_style(style_spinner.clone()); - js.spawn(download_version(config.clone(), list.clone(), ver, cached.clone(), p)); + js.spawn(download_version( + config.clone(), + list.clone(), + ver, + cached.clone(), + p, + )); + } + + while js.join_next().await.is_some() { + all.inc(1) } - while js.join_next().await.is_some() { all.inc(1) } - all.finish_with_message(format!("✓Downloading {}", list.id)); Ok(()) } -async fn download_version(config: Cfg, list: List, version: Version, mut cached: HashMap, progress: ProgressBar) -> MLE<()> { +async fn download_version( + config: Cfg, + list: List, + version: Version, + mut cached: HashMap, + progress: ProgressBar, +) -> MLE<()> { let project_info = mods_get_info(&config, &version.project_id)?; let dl_path = String::from(&list.download_folder); @@ -59,7 +87,7 @@ async fn download_version(config: Cfg, list: List, version: Version, mut cached: let files = version.files; let file = match files.clone().into_iter().find(|f| f.primary) { Some(f) => f, - None => files[0].clone() + None => files[0].clone(), }; let mut splitname: Vec<&str> = file.filename.split('.').collect(); let extension = match splitname.pop().ok_or("") { @@ -74,13 +102,7 @@ async fn download_version(config: Cfg, list: List, version: Version, mut cached: extension ); - download_file( - &file.url, - &list.download_folder, - &filename, - &progress - ) - .await?; + download_file(&file.url, &list.download_folder, &filename, &progress).await?; progress.set_message(format!("Copy {} to cache", version.id)); let dl_path_file = format!("{}/{}", list.download_folder, filename); @@ -89,7 +111,10 @@ async fn download_version(config: Cfg, list: List, version: Version, mut cached: copy(dl_path_file, cache_path)?; } - progress.finish_with_message(format!("✓{} - {}{}", project_info.title, version.id, cache_msg)); + progress.finish_with_message(format!( + "✓{} - {}{}", + project_info.title, version.id, cache_msg + )); Ok(()) } @@ -117,7 +142,7 @@ async fn download_file(url: &str, path: &str, name: &str, progress: &ProgressBar // progress.inc(1); let chunk = item?; file.write_all(&chunk)?; - + // Progress bar let new = min(downloaded + (chunk.len() as u64), size); downloaded = new; @@ -136,7 +161,7 @@ pub fn disable_version( mod_id: String, ) -> MLE<()> { //println!("Disabling version {} for mod {}", versionid, mod_id); - let file = get_file_path(current_list.clone(), String::from(&versionid))?; + let file = get_file_path(¤t_list, String::from(&versionid))?; let disabled = format!("{}.disabled", file); rename(file, disabled)?; @@ -146,7 +171,7 @@ pub fn disable_version( Ok(()) } -pub fn delete_version(list: List, version: String) -> MLE<()> { +pub fn delete_version(list: &List, version: String) -> MLE<()> { let file = get_file_path(list, version)?; remove_file(file)?; @@ -154,9 +179,9 @@ pub fn delete_version(list: List, version: String) -> MLE<()> { Ok(()) } -pub fn get_file_path(list: List, versionid: String) -> MLE { +pub fn get_file_path(list: &List, versionid: String) -> MLE { let mut names: HashMap = HashMap::new(); - for file in read_dir(list.download_folder)? { + for file in read_dir(&list.download_folder)? { let path = file?.path(); if path.is_file() { let pathstr = match path.to_str().ok_or("") { diff --git a/src/lib.rs b/src/lib.rs index 7287660..8196f1c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,20 +6,26 @@ pub mod db; pub mod error; pub mod files; -use std::{fmt::Display, fs::{File, remove_file, self}, io::{Write, Read}, time::Duration}; +use std::{ + fmt::Display, + fs::{self, remove_file, File}, + io::{Read, Write}, + time::Duration, +}; -pub use apis::*; use apis::modrinth::{get_game_versions, GameVersion, GameVersionType}; +pub use apis::*; pub use commands::*; use error::{ErrorType, MLError, MLE}; -use indicatif::{ProgressStyle, ProgressBar}; +use indicatif::{ProgressBar, ProgressStyle}; use serde::{Deserialize, Serialize}; -pub static STYLE_BAR_BYTE: &str = "{spinner:.green}{wide_msg}{bytes}/{total_bytes} [{bar:.green/lime}]"; +pub static STYLE_BAR_BYTE: &str = + "{spinner:.green}{wide_msg}{bytes}/{total_bytes} [{bar:.green/lime}]"; pub static STYLE_BAR_POS: &str = " {wide_msg}{pos}/{len} [{bar:.green/lime}]"; -pub static STYLE_SPINNER: &str = "{spinner:.green}{wide_msg}"; -pub static STYLE_OPERATION: &str = " {wide_msg}"; -pub static STYLE_MESSAGE: &str = "{wide_msg}"; +pub static STYLE_SPINNER: &str = "{spinner:.green}{wide_msg}"; +pub static STYLE_OPERATION: &str = " {wide_msg}"; +pub static STYLE_MESSAGE: &str = "{wide_msg}"; pub static PROGRESS_CHARS: &str = "#>-"; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] @@ -59,7 +65,7 @@ pub enum VersionLevel { Release, #[serde(rename(serialize = "snapshot", deserialize = "snapshot"))] Snapshot, - Version(String) + Version(String), } /// Checks if update needed (time) @@ -70,7 +76,9 @@ pub async fn check_game_versions(path: &str, force: bool) -> MLE<()> { 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) { return Ok(()); } + if !force && creation_time.elapsed().unwrap() < Duration::from_secs(60 * 60 * 24) { + return Ok(()); + } let versions = get_game_versions().await; remove_file(path)?; @@ -91,7 +99,6 @@ pub fn load_game_versions(path: &str) -> MLE> { } impl VersionLevel { - pub fn from(str: &str) -> Self { match str { "release" => VersionLevel::Release, @@ -107,22 +114,29 @@ impl VersionLevel { match self { VersionLevel::Release => { - let release = versions.find(|ver| ver.version_type == GameVersionType::release).unwrap(); + let release = versions + .find(|ver| ver.version_type == GameVersionType::release) + .unwrap(); println!("{:?}", release); Ok(release.version) - }, + } VersionLevel::Snapshot => { - let snapshot = versions.find(|ver| ver.version_type == GameVersionType::snapshot).unwrap(); + let snapshot = versions + .find(|ver| ver.version_type == GameVersionType::snapshot) + .unwrap(); println!("{:?}", snapshot); Ok(snapshot.version) - }, + } VersionLevel::Version(v) => { if versions.any(|ver| ver.version == v) { Ok(v) } else { - Err(MLError::new(ErrorType::ConfigError, "unknown minecraft version")) + Err(MLError::new( + ErrorType::ConfigError, + "unknown minecraft version", + )) } - }, + } } } } diff --git a/src/main.rs b/src/main.rs index d03f88a..d9ad6af 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,8 @@ 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_remove, list_version, - mod_add, mod_remove, update, IDSelector, List, Modloader, VersionLevel, list_list, AddMod, + download, export, get_current_list, import, list_add, list_change, list_list, list_remove, + list_version, mod_add, mod_remove, update, AddMod, IDSelector, List, Modloader, VersionLevel, }; #[derive(Parser)] @@ -43,7 +43,7 @@ enum Commands { /// remove disabled versions #[arg(short, long)] remove: bool, - + /// optional List selection, else default list will be used #[arg(short, long)] list: Option, @@ -81,7 +81,7 @@ enum Commands { /// the list you want to export list: Option, }, - Test + Test, } #[derive(Subcommand)] @@ -160,86 +160,87 @@ async fn main() { let config = Cfg::init(cli.config).await.unwrap(); match cli.command { - Commands::Mod { command } => { - match command { - ModCommands::Add { - id, - version, - list, - download, - lock, - } => { - let listf = match list { - Some(list) => lists_get(&config, &list).unwrap(), - None => lists_get( - &config, - &config_get_current_list(&config).unwrap(), - ) - .unwrap(), - }; + Commands::Mod { command } => match command { + ModCommands::Add { + id, + version, + list, + download, + lock, + } => { + let listf = match list { + Some(list) => lists_get(&config, &list).unwrap(), + None => lists_get(&config, &config_get_current_list(&config).unwrap()).unwrap(), + }; - let marked_id = match version { - true => IDSelector::VersionID(id), - false => IDSelector::ModificationID(id), - }; + let marked_id = match version { + true => IDSelector::VersionID(id), + false => IDSelector::ModificationID(id), + }; - let add_id = AddMod { id: marked_id, set_version: lock }; + let add_id = AddMod { + id: marked_id, + set_version: lock, + }; - mod_add(&config, vec![add_id], listf, download).await - } - ModCommands::Remove { id, list } => { - let listf = match list { - Some(list) => lists_get(&config, &list).unwrap(), - None => lists_get( - &config, - &config_get_current_list(&config).unwrap(), - ) - .unwrap(), - }; - mod_remove(&config, &id, listf) - } + mod_add(&config, vec![add_id], listf, download).await } - } - Commands::List { command, force_gameupdate } => { - match command { - ListCommands::Add { - id, - directory, - modloader, - version, - } => { - let ml = match modloader { - Some(ml) => Modloader::from(&ml).unwrap(), - None => config.defaults.modloader.clone(), - }; - - let versions_path = &config.versions; - let ver = match version { - Some(ver) => VersionLevel::from(&ver).get(versions_path, force_gameupdate).await.unwrap(), - None => config.defaults.version.clone().get(versions_path, force_gameupdate).await.unwrap(), - }; - - list_add(&config, &id, &ver, &ml, &directory) - } - ListCommands::Remove { id } => list_remove(&config, id), - ListCommands::List => { - list_list(&config) - } - ListCommands::Change { id } => list_change(&config, id), - ListCommands::Version { - id, - version, - download, - remove, - } => list_version(&config, &id, version, download, remove).await, + ModCommands::Remove { id, list } => { + let listf = match list { + Some(list) => lists_get(&config, &list).unwrap(), + None => lists_get(&config, &config_get_current_list(&config).unwrap()).unwrap(), + }; + mod_remove(&config, &id, &listf) } - } + }, + Commands::List { + command, + force_gameupdate, + } => match command { + ListCommands::Add { + id, + directory, + modloader, + version, + } => { + let ml = match modloader { + Some(ml) => Modloader::from(&ml).unwrap(), + None => config.defaults.modloader.clone(), + }; + + let versions_path = &config.versions; + let ver = match version { + Some(ver) => VersionLevel::from(&ver) + .get(versions_path, force_gameupdate) + .await + .unwrap(), + None => config + .defaults + .version + .clone() + .get(versions_path, force_gameupdate) + .await + .unwrap(), + }; + + list_add(&config, &id, &ver, &ml, &directory) + } + ListCommands::Remove { id } => list_remove(&config, &id), + ListCommands::List => list_list(&config), + ListCommands::Change { id } => list_change(&config, &id), + ListCommands::Version { + id, + version, + download, + remove, + } => list_version(&config, &id, version, download, remove).await, + }, Commands::Update { all, download, clean, remove, - list + list, } => { let mut liststack: Vec = vec![]; if all { @@ -248,7 +249,7 @@ async fn main() { liststack.push(lists_get(&config, &id).unwrap()); } } else { - let current = match list { + let current = match list { Some(l) => lists_get(&config, &l).unwrap(), None => get_current_list(&config).unwrap(), }; @@ -257,7 +258,12 @@ async fn main() { update(&config, liststack, clean, download, remove).await } - Commands::Download { all, clean, remove, list } => { + Commands::Download { + all, + clean, + remove, + list, + } => { let mut liststack: Vec = vec![]; if all { let list_ids = lists_get_all_ids(&config).unwrap(); @@ -265,15 +271,15 @@ async fn main() { liststack.push(lists_get(&config, &id).unwrap()); } } else { - let current = match list { + let current = match list { Some(l) => lists_get(&config, &l).unwrap(), None => get_current_list(&config).unwrap(), }; liststack.push(current) } - download(&config, liststack, clean, remove).await - }, + download(&config, liststack, clean, remove).await + } Commands::Import { file, download } => { let filestr: String = match file { Some(args) => args, -- cgit v1.2.3