From 016e1d8d760113a64afcc5d516f08010cb566d68 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Sun, 21 May 2023 13:43:52 +0200 Subject: added multithreaded downloads and progressbar --- src/commands/modification.rs | 8 ++- src/files.rs | 160 +++++++++++++++++++++++++++---------------- 2 files changed, 107 insertions(+), 61 deletions(-) (limited to 'src') diff --git a/src/commands/modification.rs b/src/commands/modification.rs index 9a1a651..d4c49d6 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -140,6 +140,8 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> let mut ids = vec![]; + println!("{:?}", mod_ids); + for id in mod_ids { setmap.insert(id.0.to_string(), id.1); ids.push(id.0); @@ -195,14 +197,16 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> available_versions_vec.push(ver.id); } + println!("{:?}", setmap); + projectinfo.push(ProjectInfo { mod_id: String::from(&project.id), - slug: project.slug, + slug: project.slug.clone(), title: project.title, current_version, applicable_versions: available_versions_vec, download_link: file, - set_version: setmap.get(&project.id).unwrap().clone(), + set_version: setmap.get(&project.slug).unwrap().clone(), }) } else { println!("\t └There's currently no mod version for your specified target"); diff --git a/src/files.rs b/src/files.rs index a4c128e..a4a1d3b 100644 --- a/src/files.rs +++ b/src/files.rs @@ -1,9 +1,11 @@ use futures_util::StreamExt; +use indicatif::{ProgressBar, ProgressStyle, MultiProgress}; use reqwest::Client; +use tokio::task::JoinSet; use std::{ collections::HashMap, fs::{copy, read_dir, remove_file, rename, File}, - io::Write, + io::Write, cmp::min, }; use crate::{ @@ -15,83 +17,123 @@ use crate::{ List, }; -pub async fn download_versions(list: List, config: Cfg, versions: Vec) -> MLE { - let mut cached = get_cached_versions(&config.cache); +pub async fn download_versions(list: List, config: Cfg, versions: Vec) -> MLE<()> { + let cached = get_cached_versions(&config.cache); // println!("{:#?}", cached); - let dl_path = String::from(&list.download_folder); + // println!(" └Download mods to {}", dl_path); + + let mp = MultiProgress::new(); - println!(" └Download mods to {}", dl_path); + let mut js = JoinSet::new(); + let style = ProgressStyle::with_template("{spinner:.green}{msg}\t[{bar:.green/lime}] {bytes}/{total_bytes}") + .unwrap() + .progress_chars("#>-"); for ver in versions { - let project_info = mods_get_info(config.clone(), &ver.project_id)?; - - //Check cache if already downloaded - let c = cached.remove(&ver.id); - if c.is_some() { - print!( - "\t└({})Get version {} from cache", - project_info.title, ver.id - ); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush()?; - copy_cached_version(&c.unwrap(), &dl_path); - println!(" ✓"); - } else { - print!("\t└({})Download version {}", project_info.title, ver.id); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush().unwrap(); - let files = ver.files; - let file = match files.clone().into_iter().find(|f| f.primary) { - Some(f) => f, - None => files[0].clone() - }; - let mut splitname: Vec<&str> = file.filename.split('.').collect(); - let extension = match splitname.pop().ok_or("") { - Ok(e) => e, - Err(..) => return Err(MLError::new(ErrorType::Other, "NO_FILE_EXTENSION")), - }; - let filename = format!( - "{}.mr.{}.{}.{}", - splitname.join("."), - ver.project_id, - ver.id, - extension - ); - download_file( - file.url, - list.clone().download_folder, - filename.clone(), - ) - .await?; - println!(" ✓"); - //Copy file to cache - print!("\t └Copy to cache"); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush().unwrap(); - let dl_path_file = format!("{}/{}", list.download_folder, filename); - let cache_path = format!("{}/{}", &config.clone().cache, filename); - // println!("{}:{}", dl_path_file, cache_path); - copy(dl_path_file, cache_path)?; - println!(" ✓"); - } + let p = mp.add(ProgressBar::new(1)); + p.set_style(style.clone()); + js.spawn(download_version(config.clone(), list.clone(), ver, cached.clone(), p)); + } + + mp.clear().unwrap(); + + while js.join_next().await.is_some() {} + + Ok(()) +} + +async fn download_version(config: Cfg, list: List, version: Version, mut cached: HashMap, progress: ProgressBar) -> MLE<()> { + let project_info = mods_get_info(config.clone(), &version.project_id)?; + + let dl_path = String::from(&list.download_folder); + + progress.set_message(String::from(&version.id)); + + //Check cache if already downloaded + let c = cached.remove(&version.id); + if c.is_some() { + print!( + "\t└({})Get version {} from cache", + project_info.title, version.id + ); + //Force flush of stdout, else print! doesn't print instantly + std::io::stdout().flush()?; + copy_cached_version(&c.unwrap(), &dl_path); + println!(" ✓"); + } else { + // print!("\t└({})Download version {}", project_info.title, version.id); + //Force flush of stdout, else print! doesn't print instantly + std::io::stdout().flush().unwrap(); + let files = version.files; + let file = match files.clone().into_iter().find(|f| f.primary) { + Some(f) => f, + None => files[0].clone() + }; + let mut splitname: Vec<&str> = file.filename.split('.').collect(); + let extension = match splitname.pop().ok_or("") { + Ok(e) => e, + Err(..) => return Err(MLError::new(ErrorType::Other, "NO_FILE_EXTENSION")), + }; + let filename = format!( + "{}.mr.{}.{}.{}", + splitname.join("."), + version.project_id, + version.id, + extension + ); + + download_file( + &file.url, + &list.download_folder, + &filename, + &progress + ) + .await?; + // println!(" ✓"); + //Copy file to cache + // print!("\t └Copy to cache"); + //Force flush of stdout, else print! doesn't print instantly + std::io::stdout().flush().unwrap(); + let dl_path_file = format!("{}/{}", list.download_folder, filename); + let cache_path = format!("{}/{}", &config.clone().cache, filename); + // println!("{}:{}", dl_path_file, cache_path); + copy(dl_path_file, cache_path)?; + // println!(" ✓"); } - Ok(dl_path) + progress.finish_with_message(format!("✓{}", version.id)); + + Ok(()) } -async fn download_file(url: String, path: String, name: String) -> MLE<()> { +async fn download_file(url: &str, path: &str, name: &str, progress: &ProgressBar) -> MLE<()> { let dl_path_file = format!("{}/{}", path, name); - let res = Client::new().get(String::from(&url)).send().await?; + let res = Client::new().get(url).send().await?; + + let size = res.content_length().expect("Couldn't get content length"); + + progress.set_length(size); + // progress.set_style(ProgressStyle::with_template("{spinner:.green}{msg}\t[{wide_bar:.green/lime}] {bytes}/{total_bytes}").unwrap().progress_chars("#>-")); // download chunks let mut file = File::create(&dl_path_file)?; let mut stream = res.bytes_stream(); + let mut downloaded: u64 = 0; + while let Some(item) = stream.next().await { + progress.inc(1); let chunk = item?; file.write_all(&chunk)?; + + // Progress bar + let new = min(downloaded + (chunk.len() as u64), size); + downloaded = new; + progress.set_position(new); + + // std::thread::sleep(std::time::Duration::from_millis(100)); } Ok(()) -- cgit v1.2.3 From 529d52534c300aec4a6e3e9e08f9762a401f7086 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Thu, 25 May 2023 11:16:16 +0200 Subject: added more progress --- src/apis/modrinth.rs | 2 +- src/cache.rs | 1 - src/commands/download.rs | 4 +-- src/commands/io.rs | 2 +- src/commands/list.rs | 2 +- src/commands/modification.rs | 70 +++++++++++++++++++++++++++------------ src/commands/update.rs | 79 ++++++++++++++++++++++++++++++++------------ src/config.rs | 4 +-- src/db.rs | 2 +- src/files.rs | 61 ++++++++++++++++------------------ src/lib.rs | 6 ++-- 11 files changed, 145 insertions(+), 88 deletions(-) (limited to 'src') diff --git a/src/apis/modrinth.rs b/src/apis/modrinth.rs index 525cc0d..14ff266 100644 --- a/src/apis/modrinth.rs +++ b/src/apis/modrinth.rs @@ -170,7 +170,7 @@ pub async fn projects(api: &str, ids: Vec) -> Vec { pub async fn versions(api: &str, id: String, list: List) -> Vec { let url = format!( r#"project/{}/version?loaders=["{}"]&game_versions=["{}"]"#, - id, list.modloader.to_string(), list.mc_version + id, list.modloader, list.mc_version ); let data = get(api, &url).await.unwrap(); diff --git a/src/cache.rs b/src/cache.rs index c928670..1e22091 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -32,6 +32,5 @@ pub fn get_cached_versions(path: &str) -> HashMap { pub fn copy_cached_version(version_path: &str, download_path: &str) { let versplit: Vec<&str> = version_path.split('/').collect(); let download = format!("{}/{}", download_path, versplit[versplit.len() - 1]); - // println!("{:#?}", download); copy(version_path, download).unwrap(); } diff --git a/src/commands/download.rs b/src/commands/download.rs index ebfb4eb..6831714 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -1,3 +1,4 @@ + use crate::{config::Cfg, List}; use crate::{ db::userlist_get_all_current_versions_with_mods, @@ -9,7 +10,6 @@ use crate::{ }; pub async fn download(config: Cfg, liststack: Vec, clean: bool, delete_old: bool) -> MLE<()> { - for current_list in liststack { println!("Downloading current versions of mods in {}", current_list.id); let downloaded_versions = get_downloaded_versions(current_list.clone())?; @@ -63,7 +63,7 @@ pub async fn download(config: Cfg, liststack: Vec, clean: bool, delete_old if !to_disable.is_empty() { for ver in to_disable { if delete_old { - println!("Deleting version {} for mod {}", ver.1, ver.0); + // println!("Deleting version {} for mod {}", ver.1, ver.0); delete_version(current_list.clone(), ver.1)?; } 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 dd294bc..2a26f1d 100644 --- a/src/commands/io.rs +++ b/src/commands/io.rs @@ -24,7 +24,7 @@ impl ExportVersion { fn from(config: Cfg, list_id: &str, mod_id: &str) -> MLE { Ok(Self { version: userlist_get_current_version(config.clone(), list_id, mod_id)?, - set: userlist_get_set_version(config.clone(), list_id, mod_id)? + set: userlist_get_set_version(config, list_id, mod_id)? }) } } diff --git a/src/commands/list.rs b/src/commands/list.rs index 4aa4306..c07823b 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -32,7 +32,7 @@ pub fn list_add( } pub fn list_change(config: Cfg, id: String) -> MLE<()> { - if lists_get_all_ids(config.clone())?.into_iter().find(|l| l == &id).is_none() { + if !lists_get_all_ids(config.clone())?.into_iter().any(|l| l == id) { return Err(MLError::new(ErrorType::ArgumentError, "List not found")); }; println!("Change default list to: {}", id); diff --git a/src/commands/modification.rs b/src/commands/modification.rs index d4c49d6..730583d 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -1,5 +1,7 @@ use std::{io::Write, collections::HashMap}; +use indicatif::{ProgressBar, ProgressStyle}; + use crate::{ config::Cfg, db::{ @@ -12,6 +14,8 @@ use crate::{ List, }; +const PROGRESS_CHARS: &str = "#>-"; + #[derive(Debug, Clone)] pub struct AddMod { pub id: IDSelector, @@ -41,28 +45,45 @@ pub async fn mod_add( list: List, direct_download: bool, ) -> MLE<()> { - println!("Add mods to {}", list.id); - println!(" └Add mods:"); + let spinner_style = ProgressStyle::with_template("{spinner:.green}{msg}").unwrap(); + let bar_style = ProgressStyle::with_template("{spinner:.green}{wide_msg}{pos}/{len} [{bar:.green/lime}]").unwrap().progress_chars(PROGRESS_CHARS); + + // println!("Add mods to {}", list.id); + // println!(" └Add mods:"); let mut mod_ids: Vec<(String, bool)> = Vec::new(); let mut ver_ids: Vec<(String, bool)> = Vec::new(); + let p = ProgressBar::new(mods.len().try_into().unwrap()); + p.set_style(spinner_style.clone()); + p.set_message("Sort ids"); + //"Sort" project ids from version ids to be able to handle them differently but in a batch for m in mods { + p.inc(1); match m.id { IDSelector::ModificationID(pid) => mod_ids.push((pid, m.set_version)), IDSelector::VersionID(vid) => ver_ids.push((vid, m.set_version)), } } - + + p.finish_with_message("Sort ids done"); + + let info_p = ProgressBar::new(2); + info_p.set_message("Get infos"); + info_p.set_style(bar_style.clone()); let mut projectinfo: Vec = Vec::new(); if !mod_ids.is_empty() { - projectinfo.append(&mut get_mod_infos(config.clone(), mod_ids, list.clone()).await?) + projectinfo.append(&mut get_mod_infos(config.clone(), mod_ids, list.clone()).await?); + info_p.inc(1); }; if !ver_ids.is_empty() { - projectinfo.append(&mut get_ver_info(config.clone(), ver_ids).await?) + projectinfo.append(&mut get_ver_info(config.clone(), ver_ids).await?); + info_p.inc(1); }; + info_p.finish_with_message("Get infos done"); + if projectinfo.is_empty() { return Err(MLError::new(ErrorType::ArgumentError, "NO_IDS?")); }; @@ -70,18 +91,19 @@ pub async fn mod_add( let mut downloadstack: Vec = Vec::new(); //Adding each mod to the lists and downloadstack - if projectinfo.len() == 1 { - println!(" └Insert mod in list {} and save infos", list.id); - } else { - println!(" └Insert mods in list {} and save infos", list.id); - } + let add_p = ProgressBar::new(projectinfo.len().try_into().unwrap()); + add_p.set_style(bar_style); for project in projectinfo { + + add_p.set_message(format!("Add {}", project.title)); + 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, @@ -124,8 +146,13 @@ pub async fn mod_add( if project.current_version.is_some() { downloadstack.push(project.current_version.unwrap()) }; + + // add_p.println(format!("Added {}", project.title)); + add_p.inc(1); } + add_p.finish_with_message("Added all mods"); + //Download all the added mods if direct_download { download_versions(list.clone(), config.clone(), downloadstack).await?; @@ -140,7 +167,7 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> let mut ids = vec![]; - println!("{:?}", mod_ids); + // println!("{:?}", mod_ids); for id in mod_ids { setmap.insert(id.0.to_string(), id.1); @@ -156,8 +183,8 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> _ => panic!("PANIC"), }; for project in m_projects { - println!("\t└{}", project.title); - println!("\t └Get versions"); + // println!("\t└{}", project.title); + // println!("\t └Get versions"); let available_versions = versions( &config.apis.modrinth, String::from(&project.id), @@ -170,7 +197,7 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> let file: String; if !available_versions.is_empty() { let current_id = extract_current_version(available_versions.clone())?; - println!("\t └Current version: {}", current_id); + // println!("\t └Current version: {}", current_id); current_version = Some( available_versions @@ -197,7 +224,7 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> available_versions_vec.push(ver.id); } - println!("{:?}", setmap); + // println!("{:?}", setmap); projectinfo.push(ProjectInfo { mod_id: String::from(&project.id), @@ -206,10 +233,10 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> current_version, applicable_versions: available_versions_vec, download_link: file, - set_version: setmap.get(&project.slug).unwrap().clone(), + set_version: *setmap.get(&project.slug).unwrap(), }) } else { - println!("\t └There's currently no mod version for your specified target"); + // println!("\t └There's currently no mod version for your specified target"); current_version = None; file = String::from("NONE"); available_versions_vec.push(String::from("NONE")); @@ -220,7 +247,7 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> current_version, applicable_versions: available_versions_vec, download_link: file, - set_version: setmap.get(&project.id).unwrap().clone(), + set_version: *setmap.get(&project.id).unwrap(), }) } } @@ -252,7 +279,7 @@ async fn get_ver_info(config: Cfg, ver_ids: Vec<(String, bool)>) -> MLE) -> MLE) -> MLE MLE<()> { let mod_id = mods_get_id(&config.data, id)?; - println!("Remove mod {} from {}", mods_get_info(config.clone(), &mod_id)?.title, list.id); + println!("Remove mod {} from {}", mods_get_info(&config, &mod_id)?.title, list.id); let version = userlist_get_current_version(config.clone(), &list.id, &mod_id)?; print!(" └Remove from list"); @@ -300,7 +327,6 @@ pub fn mod_remove(config: Cfg, id: &str, list: List) -> MLE<()> { if err.to_string() != "User input not accepted: VERSION_NOT_FOUND_IN_FILES" { return Err(err); }; - () }, }; println!(" ✓"); diff --git a/src/commands/update.rs b/src/commands/update.rs index d3a282b..2de13f3 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -1,3 +1,5 @@ +use indicatif::{ProgressBar, ProgressStyle, MultiProgress}; + use crate::{ config::Cfg, db::{ @@ -10,6 +12,8 @@ use crate::{ List, }; +const PROGRESS_CHARS: &str = "#>-"; + pub async fn update( config: Cfg, liststack: Vec, @@ -17,20 +21,39 @@ 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())); + let bar_style = ProgressStyle::with_template("{spinner:.green}{wide_msg}{pos}/{len} [{bar:.green/lime}]").unwrap().progress_chars(PROGRESS_CHARS); + let spinner_style = ProgressStyle::with_template("{spinner:.green}{msg}").unwrap(); + update_p.set_style(bar_style.clone()); + update_p.set_message("Update"); + for current_list in liststack { - println!("Update mods in {}", current_list.id); + + // println!("Update mods in {}", current_list.id); let mods = userlist_get_all_ids(config.clone(), ¤t_list.id)?; + let list_p = mp.insert_before(&update_p, ProgressBar::new(mods.len().try_into().unwrap())); + list_p.set_style(bar_style.clone()); + list_p.set_message(format!("Update {}", current_list.id)); + let mut current_versions: Vec<(String, String)> = vec![]; let mut updatestack: Vec = vec![]; for id in mods { - let info = mods_get_info(config.clone(), &id)?; - println!(" ├{}", info.title); + let mod_p = mp.insert_before(&list_p, ProgressBar::new(1)); + mod_p.set_style(spinner_style.clone()); + + let info = mods_get_info(&config, &id)?; + mod_p.set_message(format!("Update {}", info.title)); + // println!(" ├{}", info.title); if userlist_get_set_version(config.clone(), ¤t_list.id, &id)? { - println!(" │ └Set version, skipping update"); + // println!(" │ └Set version, skipping update"); + list_p.inc(1); continue; } @@ -38,12 +61,15 @@ pub async fn update( let disable_version = userlist_get_current_version(config.clone(), ¤t_list.id, &id)?; + mod_p.inc(1); + updatestack.push( match specific_update( config.clone(), clean, current_list.clone(), String::from(&id), + &mod_p ) .await { @@ -53,19 +79,25 @@ pub async fn update( } Err(e) => { if e.to_string() == "Mod: NO_UPDATE_AVAILABLE" { - println!( - " │ └No new version found for the specified minecraft version" - ); + // println!( + // " │ └No new version found for the specified minecraft version" + // ); } else { return Err(e); }; + list_p.inc(1); continue; } }, - ) + ); + list_p.inc(1); } + list_p.finish_with_message(format!("Updated {}", current_list.id)); + if clean { + update_p.set_message("Cleaning"); + update_p.inc(1); clean_list_dir(¤t_list)?; }; @@ -85,12 +117,16 @@ pub async fn update( } } }; + update_p.inc(1); } + update_p.finish_with_message("Updated all lists"); + + Ok(()) } -async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> MLE { +async fn specific_update(config: Cfg, clean: bool, list: List, id: String, progress: &ProgressBar) -> MLE { let applicable_versions = versions(&config.apis.modrinth, String::from(&id), list.clone()).await; @@ -116,10 +152,11 @@ async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> ML let current_str = extract_current_version(applicable_versions.clone())?; if clean { - println!("\t └Add version to downloadstack"); + // println!("\t └Add version to downloadstack"); } else { - println!("\t └Get versions for specified minecraft versions"); - println!("\t └New current version: {}", current_str); + progress.println(format!("Found new version for {}", mods_get_info(&config, &id).unwrap().title)); + // println!("\t └Get versions for specified minecraft versions"); + // println!("\t └New current version: {}", current_str); }; //get new versions @@ -133,16 +170,14 @@ async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> ML }?; current.push(current_ver.clone()); - 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; + 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)?; } diff --git a/src/config.rs b/src/config.rs index e1049d1..0cb1891 100644 --- a/src/config.rs +++ b/src/config.rs @@ -31,7 +31,7 @@ pub struct Defaults { impl Cfg { pub async fn init(path: Option) -> MLE { let configfile = match path.clone() { - Some(p) => String::from(p), + Some(p) => p, None => dirs::config_dir() .unwrap() .join("modlist") @@ -89,7 +89,7 @@ fn create_config(path: &str) -> MLE<()> { let default_cfg = Cfg { data: cache_dir.clone(), cache: format!("{}/cache", cache_dir), - versions: cache_dir.clone(), + versions: cache_dir, defaults: Defaults { modloader: Modloader::Fabric, version: VersionLevel::Release diff --git a/src/db.rs b/src/db.rs index 8fd21b1..dde00ab 100644 --- a/src/db.rs +++ b/src/db.rs @@ -93,7 +93,7 @@ pub struct ModInfo { pub title: String, } -pub fn mods_get_info(config: Cfg, id: &str) -> MLE { +pub fn mods_get_info(config: &Cfg, id: &str) -> MLE { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; diff --git a/src/files.rs b/src/files.rs index a4a1d3b..04b00f0 100644 --- a/src/files.rs +++ b/src/files.rs @@ -17,55 +17,50 @@ use crate::{ List, }; +const PROGRESS_CHARS: &str = "#>-"; + pub async fn download_versions(list: List, config: Cfg, versions: Vec) -> MLE<()> { let cached = get_cached_versions(&config.cache); - // println!("{:#?}", cached); - - // println!(" └Download mods to {}", dl_path); - let mp = MultiProgress::new(); let mut js = JoinSet::new(); - let style = ProgressStyle::with_template("{spinner:.green}{msg}\t[{bar:.green/lime}] {bytes}/{total_bytes}") - .unwrap() - .progress_chars("#>-"); + let style_spinner = ProgressStyle::with_template("{spinner:.green}{wide_msg}").unwrap(); + + let all = mp.add(ProgressBar::new(versions.len().try_into().unwrap())); + all.set_style(ProgressStyle::with_template("{wide_msg}{pos}/{len} [{bar:.green/lime}]").unwrap().progress_chars(PROGRESS_CHARS)); + all.set_message("Downloading"); + for ver in versions { - let p = mp.add(ProgressBar::new(1)); - p.set_style(style.clone()); + let p = mp.insert_before(&all, ProgressBar::new(1)); + p.set_style(style_spinner.clone()); js.spawn(download_version(config.clone(), list.clone(), ver, cached.clone(), p)); + // std::thread::sleep(std::time::Duration::from_millis(200)); } - mp.clear().unwrap(); + while js.join_next().await.is_some() { all.inc(1) } + + all.finish(); - while js.join_next().await.is_some() {} + // mp.clear().unwrap(); Ok(()) } async fn download_version(config: Cfg, list: List, version: Version, mut cached: HashMap, progress: ProgressBar) -> MLE<()> { - let project_info = mods_get_info(config.clone(), &version.project_id)?; + let project_info = mods_get_info(&config, &version.project_id)?; let dl_path = String::from(&list.download_folder); - progress.set_message(String::from(&version.id)); + progress.set_message(format!("{} - {}", project_info.title, version.id)); //Check cache if already downloaded let c = cached.remove(&version.id); if c.is_some() { - print!( - "\t└({})Get version {} from cache", - project_info.title, version.id - ); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush()?; + progress.set_message(format!("Get {} from cache", version.id)); copy_cached_version(&c.unwrap(), &dl_path); - println!(" ✓"); } else { - // print!("\t└({})Download version {}", project_info.title, version.id); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush().unwrap(); let files = version.files; let file = match files.clone().into_iter().find(|f| f.primary) { Some(f) => f, @@ -91,19 +86,15 @@ async fn download_version(config: Cfg, list: List, version: Version, mut cached: &progress ) .await?; - // println!(" ✓"); - //Copy file to cache - // print!("\t └Copy to cache"); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush().unwrap(); + + progress.set_message(format!("Copy {} to cache", version.id)); let dl_path_file = format!("{}/{}", list.download_folder, filename); let cache_path = format!("{}/{}", &config.clone().cache, filename); - // println!("{}:{}", dl_path_file, cache_path); + copy(dl_path_file, cache_path)?; - // println!(" ✓"); } - progress.finish_with_message(format!("✓{}", version.id)); + progress.finish_with_message(format!("✓{} - {}", project_info.title, version.id)); Ok(()) } @@ -114,8 +105,12 @@ async fn download_file(url: &str, path: &str, name: &str, progress: &ProgressBar let size = res.content_length().expect("Couldn't get content length"); + let style_bar_byte = ProgressStyle::with_template("{spinner:.green}{wide_msg}{bytes}/{total_bytes} [{bar:.green/lime}]") + .unwrap() + .progress_chars(PROGRESS_CHARS); + progress.set_length(size); - // progress.set_style(ProgressStyle::with_template("{spinner:.green}{msg}\t[{wide_bar:.green/lime}] {bytes}/{total_bytes}").unwrap().progress_chars("#>-")); + progress.set_style(style_bar_byte); // download chunks let mut file = File::create(&dl_path_file)?; @@ -124,7 +119,7 @@ async fn download_file(url: &str, path: &str, name: &str, progress: &ProgressBar let mut downloaded: u64 = 0; while let Some(item) = stream.next().await { - progress.inc(1); + // progress.inc(1); let chunk = item?; file.write_all(&chunk)?; diff --git a/src/lib.rs b/src/lib.rs index 1c40ceb..f59ba89 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,6 +14,8 @@ pub use commands::*; use error::{ErrorType, MLError, MLE}; use serde::{Deserialize, Serialize}; +pub static TICK_CHARS: &str = "#>-"; + #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub enum Modloader { #[serde(rename(serialize = "fabric", deserialize = "fabric"))] @@ -64,7 +66,7 @@ pub async fn check_game_versions(path: &str, force: bool) -> MLE<()> { let versions = get_game_versions().await; remove_file(path)?; let mut file = File::create(path)?; - file.write_all(&serde_json::to_string_pretty(&versions)?.as_bytes())?; + file.write_all(serde_json::to_string_pretty(&versions)?.as_bytes())?; println!(" ✓"); Ok(()) } @@ -105,7 +107,7 @@ impl VersionLevel { Ok(snapshot.version) }, VersionLevel::Version(v) => { - if versions.find(|ver| ver.version == v).is_some() { + if versions.any(|ver| ver.version == v) { Ok(v) } else { Err(MLError::new(ErrorType::ConfigError, "unknown minecraft version")) -- cgit v1.2.3 From 48393b209396db9ddd44251b2bb445d3ad7533fb Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Thu, 25 May 2023 17:23:52 +0200 Subject: changed a whole lot og references, fuck rust --- src/commands/download.rs | 6 ++-- src/commands/io.rs | 34 ++++++++++----------- src/commands/list.rs | 33 +++++++++++---------- src/commands/modification.rs | 30 +++++++++---------- src/commands/update.rs | 32 ++++++++++---------- src/config.rs | 1 + src/db.rs | 70 ++++++++++++++++++++++---------------------- src/files.rs | 8 ++--- src/lib.rs | 2 +- src/main.rs | 56 +++++++++++++++++------------------ 10 files changed, 134 insertions(+), 138 deletions(-) (limited to 'src') diff --git a/src/commands/download.rs b/src/commands/download.rs index 6831714..fea3f34 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -9,13 +9,13 @@ use crate::{ modrinth::get_raw_versions, }; -pub async fn download(config: Cfg, liststack: Vec, clean: bool, delete_old: bool) -> MLE<()> { +pub async fn download(config: &Cfg, liststack: Vec, clean: bool, delete_old: bool) -> MLE<()> { for current_list in liststack { println!("Downloading current versions of mods in {}", current_list.id); 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(), + config, String::from(¤t_list.id), ) { Ok(i) => Ok(i), @@ -66,7 +66,7 @@ pub async fn download(config: Cfg, liststack: Vec, clean: bool, delete_old // println!("Deleting version {} for mod {}", ver.1, ver.0); delete_version(current_list.clone(), ver.1)?; } else { - disable_version(config.clone(), current_list.clone(), ver.1, ver.0)?; + disable_version(config, current_list.clone(), ver.1, ver.0)?; }; } } diff --git a/src/commands/io.rs b/src/commands/io.rs index 2a26f1d..43e642a 100644 --- a/src/commands/io.rs +++ b/src/commands/io.rs @@ -21,9 +21,9 @@ struct ExportVersion { } impl ExportVersion { - fn from(config: Cfg, list_id: &str, mod_id: &str) -> MLE { + fn from(config: &Cfg, list_id: &str, mod_id: &str) -> MLE { Ok(Self { - version: userlist_get_current_version(config.clone(), list_id, mod_id)?, + version: userlist_get_current_version(config, list_id, mod_id)?, set: userlist_get_set_version(config, list_id, mod_id)? }) } @@ -39,18 +39,18 @@ 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))?; + pub fn from(config: &Cfg, list_id: String, download: bool) -> MLE { + let list = lists_get(config, String::from(&list_id))?; let mut dl_folder = None; if download { dl_folder = Some(list.download_folder) }; - let mods = userlist_get_all_ids(config.clone(), &list_id)?; + let mods = userlist_get_all_ids(config, &list_id)?; let mut versions = vec![]; for m in mods { - versions.push(ExportVersion::from(config.clone(), &list_id, &m)?) + versions.push(ExportVersion::from(config, &list_id, &m)?) } Ok(Self { @@ -63,16 +63,16 @@ impl ExportList { } } -pub fn export(config: Cfg, list: Option) -> MLE<()> { +pub fn export(config: &Cfg, list: Option) -> MLE<()> { let mut list_ids: Vec = vec![]; if list.is_none() { - list_ids = lists_get_all_ids(config.clone())?; + list_ids = lists_get_all_ids(config)?; } else { - list_ids.push(lists_get(config.clone(), list.unwrap())?.id); + list_ids.push(lists_get(config, list.unwrap())?.id); } let mut lists: Vec = vec![]; for list_id in list_ids { - lists.push(ExportList::from(config.clone(), list_id, true)?); + lists.push(ExportList::from(config, list_id, true)?); } let toml = toml::to_string(&Export { lists })?; @@ -85,7 +85,7 @@ pub fn export(config: Cfg, list: Option) -> MLE<()> { Ok(()) } -pub async fn import(config: Cfg, file_str: String, direct_download: bool) -> MLE<()> { +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)?; @@ -99,18 +99,18 @@ pub async fn import(config: Cfg, file_str: String, direct_download: bool) -> MLE 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), + config, + &list.id, + &list.mc_version, + &list.modloader, + &list.download_folder, )?; let mut ver_ids = vec![]; for id in exportlist.versions { ver_ids.push(AddMod { id: IDSelector::VersionID(id.version), set_version: id.set} ); } - mod_add(config.clone(), ver_ids, list, direct_download).await?; + mod_add(config, ver_ids, list, direct_download).await?; } Ok(()) } diff --git a/src/commands/list.rs b/src/commands/list.rs index c07823b..95f9927 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -16,30 +16,31 @@ pub struct List { pub download_folder: String, } -pub fn get_current_list(config: Cfg) -> MLE { - let id = config_get_current_list(config.clone())?; +pub fn get_current_list(config: &Cfg) -> MLE { + let id = config_get_current_list(config)?; lists_get(config, id) } pub fn list_add( - config: Cfg, - id: String, - mc_version: String, - modloader: Modloader, - directory: String, + config: &Cfg, + id: &str, + mc_version: &str, + modloader: &Modloader, + directory: &str, ) -> MLE<()> { lists_insert(config, id, mc_version, modloader, directory) } -pub fn list_change(config: Cfg, id: String) -> MLE<()> { - if !lists_get_all_ids(config.clone())?.into_iter().any(|l| l == id) { +pub fn list_change(config: &Cfg, id: String) -> MLE<()> { + 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) } -pub fn list_remove(config: Cfg, id: String) -> MLE<()> { +pub fn list_remove(config: &Cfg, id: String) -> MLE<()> { + //TODO add logging lists_remove(config, id) } @@ -50,7 +51,7 @@ pub fn list_remove(config: Cfg, id: String) -> MLE<()> { /// * `config` - The current config /// * `args` - All args, to extract the new version pub async fn list_version( - config: Cfg, + config: &Cfg, id: String, mc_version: String, download: bool, @@ -61,20 +62,20 @@ pub async fn list_version( id, mc_version ); - lists_version(config.clone(), &id, &mc_version)?; + lists_version(config, &id, &mc_version)?; println!( "\nCheck for updates for new minecraft version in list {}", id ); - let list = lists_get(config.clone(), id)?; + let list = lists_get(config, id)?; update(config, vec![list], true, download, delete).await } -pub fn list_list(config: Cfg) -> MLE<()> { - let lists = lists_get_all_ids(config.clone())?; +pub fn list_list(config: &Cfg) -> MLE<()> { + let lists = lists_get_all_ids(config)?; for list in lists { - let l = lists_get(config.clone(), list)?; + let l = lists_get(config, list)?; println!("{}: | {} | {}", l.id, l.mc_version, l.modloader) } Ok(()) diff --git a/src/commands/modification.rs b/src/commands/modification.rs index 730583d..31931f8 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -11,11 +11,9 @@ use crate::{ error::{ErrorType, MLError, MLE}, files::{delete_version, download_versions}, modrinth::{extract_current_version, get_raw_versions, project, projects, versions, Version}, - List, + List, PROGRESS_CHARS, }; -const PROGRESS_CHARS: &str = "#>-"; - #[derive(Debug, Clone)] pub struct AddMod { pub id: IDSelector, @@ -40,7 +38,7 @@ pub struct ProjectInfo { } pub async fn mod_add( - config: Cfg, + config: &Cfg, mods: Vec, list: List, direct_download: bool, @@ -74,11 +72,11 @@ pub async fn mod_add( info_p.set_style(bar_style.clone()); let mut projectinfo: Vec = Vec::new(); if !mod_ids.is_empty() { - projectinfo.append(&mut get_mod_infos(config.clone(), mod_ids, list.clone()).await?); + projectinfo.append(&mut get_mod_infos(config, mod_ids, list.clone()).await?); info_p.inc(1); }; if !ver_ids.is_empty() { - projectinfo.append(&mut get_ver_info(config.clone(), ver_ids).await?); + projectinfo.append(&mut get_ver_info(config, ver_ids).await?); info_p.inc(1); }; @@ -105,7 +103,7 @@ pub async fn mod_add( }; match userlist_insert( - config.clone(), + config, &list.id, &project.mod_id, ¤t_version_id, @@ -128,7 +126,7 @@ pub async fn mod_add( }?; match mods_insert( - config.clone(), + config, &project.mod_id, &project.slug, &project.title, @@ -161,7 +159,7 @@ 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(); @@ -255,7 +253,7 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> Ok(projectinfo) } -async fn get_ver_info(config: Cfg, ver_ids: Vec<(String, bool)>) -> MLE> { +async fn get_ver_info(config: &Cfg, ver_ids: Vec<(String, bool)>) -> MLE> { let mut setmap: HashMap = HashMap::new(); @@ -306,16 +304,16 @@ 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 mod_id = mods_get_id(&config.data, id)?; - println!("Remove mod {} from {}", mods_get_info(&config, &mod_id)?.title, list.id); - let version = userlist_get_current_version(config.clone(), &list.id, &mod_id)?; + println!("Remove mod {} from {}", mods_get_info(config, &mod_id)?.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.clone(), &list.id, &mod_id)?; + userlist_remove(config, &list.id, &mod_id)?; println!(" ✓"); print!(" └Delete file"); @@ -334,12 +332,12 @@ pub fn mod_remove(config: Cfg, id: &str, list: List) -> MLE<()> { print!(" └Clean main db table"); //Force flush of stdout, else print! doesn't print instantly std::io::stdout().flush()?; - let list_ids = lists_get_all_ids(config.clone())?; + let list_ids = lists_get_all_ids(config)?; // Remove mod from main list if not used elsewhere let mut mod_used = false; for id in list_ids { - let mods = match userlist_get_all_ids(config.clone(), &id) { + let mods = match userlist_get_all_ids(config, &id) { Ok(m) => m, Err(err) => { if err.to_string() == "Database: NO_MODS_USERLIST" { diff --git a/src/commands/update.rs b/src/commands/update.rs index 2de13f3..7482e43 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -9,13 +9,11 @@ use crate::{ error::{ErrorType, MLError, MLE}, files::{clean_list_dir, delete_version, disable_version, download_versions}, modrinth::{extract_current_version, versions, Version}, - List, + List, PROGRESS_CHARS, }; -const PROGRESS_CHARS: &str = "#>-"; - pub async fn update( - config: Cfg, + config: &Cfg, liststack: Vec, clean: bool, direct_download: bool, @@ -33,7 +31,7 @@ pub async fn update( for current_list in liststack { // println!("Update mods in {}", current_list.id); - let mods = userlist_get_all_ids(config.clone(), ¤t_list.id)?; + let mods = userlist_get_all_ids(config, ¤t_list.id)?; let list_p = mp.insert_before(&update_p, ProgressBar::new(mods.len().try_into().unwrap())); list_p.set_style(bar_style.clone()); @@ -47,11 +45,11 @@ pub async fn update( let mod_p = mp.insert_before(&list_p, ProgressBar::new(1)); mod_p.set_style(spinner_style.clone()); - let info = mods_get_info(&config, &id)?; + let info = mods_get_info(config, &id)?; mod_p.set_message(format!("Update {}", info.title)); // println!(" ├{}", info.title); - if userlist_get_set_version(config.clone(), ¤t_list.id, &id)? { + if userlist_get_set_version(config, ¤t_list.id, &id)? { // println!(" │ └Set version, skipping update"); list_p.inc(1); continue; @@ -59,16 +57,16 @@ pub async fn update( //Getting current installed version for disable or delete let disable_version = - userlist_get_current_version(config.clone(), ¤t_list.id, &id)?; + userlist_get_current_version(config, ¤t_list.id, &id)?; mod_p.inc(1); updatestack.push( match specific_update( - config.clone(), + config, clean, current_list.clone(), - String::from(&id), + &id, &mod_p ) .await @@ -112,7 +110,7 @@ pub async fn update( delete_version(current_list.clone(), ver.0)?; } else if ver.0 != "NONE" { println!(" └Disable version {}", ver.0); - disable_version(config.clone(), current_list.clone(), ver.0, ver.1)?; + disable_version(config, current_list.clone(), ver.0, ver.1)?; }; } } @@ -126,9 +124,9 @@ pub async fn update( Ok(()) } -async fn specific_update(config: Cfg, clean: bool, list: List, id: String, progress: &ProgressBar) -> MLE { +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; + versions(&config.apis.modrinth, String::from(id), list.clone()).await; let mut versions: Vec = vec![]; @@ -144,9 +142,9 @@ async fn specific_update(config: Cfg, clean: bool, list: List, id: String, progr if clean || (versions.join("|") != userlist_get_applicable_versions( - config.clone(), + config, String::from(&list.id), - String::from(&id), + String::from(id), )?) { let current_str = extract_current_version(applicable_versions.clone())?; @@ -154,7 +152,7 @@ async fn specific_update(config: Cfg, clean: bool, list: List, id: String, progr if clean { // println!("\t └Add version to downloadstack"); } else { - progress.println(format!("Found new version for {}", mods_get_info(&config, &id).unwrap().title)); + progress.println(format!("Found new version for {}", mods_get_info(config, id).unwrap().title)); // println!("\t └Get versions for specified minecraft versions"); // println!("\t └New current version: {}", current_str); }; @@ -178,7 +176,7 @@ async fn specific_update(config: Cfg, clean: bool, list: List, id: String, progr } .url; - userlist_change_versions(config, list.id, current_str, versions.join("|"), link, id)?; + 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 0cb1891..a952d40 100644 --- a/src/config.rs +++ b/src/config.rs @@ -73,6 +73,7 @@ impl Cfg { check_game_versions(&versionfile, true).await?; }, } + Ok(config) } } diff --git a/src/db.rs b/src/db.rs index dde00ab..3409298 100644 --- a/src/db.rs +++ b/src/db.rs @@ -9,7 +9,7 @@ use crate::{ }; //MODS -pub fn mods_insert(config: Cfg, id: &str, slug: &str, name: &str) -> MLE<()> { +pub fn mods_insert(config: &Cfg, id: &str, slug: &str, name: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -21,7 +21,7 @@ pub fn mods_insert(config: Cfg, id: &str, slug: &str, name: &str) -> MLE<()> { Ok(()) } -pub fn mods_get_all_ids(config: Cfg) -> Result, Box> { +pub fn mods_get_all_ids(config: &Cfg) -> Result, Box> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -120,7 +120,7 @@ pub fn mods_get_info(config: &Cfg, id: &str) -> MLE { } } -pub fn mods_remove(config: Cfg, id: String) -> MLE<()> { +pub fn mods_remove(config: &Cfg, id: String) -> MLE<()> { println!("Removing mod {} from database", id); let data = format!("{}/data.db", config.data); @@ -137,7 +137,7 @@ pub struct DBModlistVersions { pub versions: String, } -pub fn mods_get_versions(config: Cfg, mods: Vec) -> MLE> { +pub fn mods_get_versions(config: &Cfg, mods: Vec) -> MLE> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -186,7 +186,7 @@ pub fn mods_get_versions(config: Cfg, mods: Vec) -> MLE MLE> { +pub fn userlist_get_all_ids(config: &Cfg, list_id: &str) -> MLE> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -239,7 +239,7 @@ pub fn userlist_get_all_ids(config: Cfg, list_id: &str) -> MLE> { } } -pub fn userlist_remove(config: Cfg, list_id: &str, mod_id: &str) -> MLE<()> { +pub fn userlist_remove(config: &Cfg, list_id: &str, mod_id: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -251,7 +251,7 @@ pub fn userlist_remove(config: Cfg, list_id: &str, mod_id: &str) -> MLE<()> { } pub fn userlist_get_applicable_versions( - config: Cfg, + config: &Cfg, list_id: String, mod_id: String, ) -> MLE { @@ -279,7 +279,7 @@ pub fn userlist_get_applicable_versions( } pub fn userlist_get_all_applicable_versions_with_mods( - config: Cfg, + config: &Cfg, list_id: String, ) -> MLE> { let data = format!("{}/data.db", config.data); @@ -307,7 +307,7 @@ pub fn userlist_get_all_applicable_versions_with_mods( Ok(versions) } -pub fn userlist_get_current_version(config: Cfg, list_id: &str, mod_id: &str) -> MLE { +pub fn userlist_get_current_version(config: &Cfg, list_id: &str, mod_id: &str) -> MLE { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -327,7 +327,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, + config: &Cfg, list_id: String, ) -> MLE> { let data = format!("{}/data.db", config.data); @@ -353,7 +353,7 @@ pub fn userlist_get_all_current_version_ids( } pub fn userlist_get_all_current_versions_with_mods( - config: Cfg, + config: &Cfg, list_id: String, ) -> Result, Box> { let data = format!("{}/data.db", config.data); @@ -384,7 +384,7 @@ pub fn userlist_get_all_current_versions_with_mods( 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 = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -401,7 +401,7 @@ pub fn userlist_get_set_version(config: Cfg, list_id: &str, mod_id: &str) -> MLE } pub fn userlist_change_versions( - config: Cfg, + config: &Cfg, list_id: String, current_version: String, versions: String, @@ -416,7 +416,7 @@ pub fn userlist_change_versions( } pub fn userlist_add_disabled_versions( - config: Cfg, + config: &Cfg, list_id: String, disabled_version: String, mod_id: String, @@ -442,7 +442,7 @@ 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(); @@ -462,7 +462,7 @@ pub fn userlist_get_disabled_versions(config: Cfg, list_id: String, mod_id: Stri } pub fn userlist_get_all_downloads( - config: Cfg, + config: &Cfg, list_id: String, ) -> Result, Box> { let data = format!("{}/data.db", config.data); @@ -492,11 +492,11 @@ pub fn userlist_get_all_downloads( //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, + config: &Cfg, + id: &str, + mc_version: &str, + mod_loader: &Modloader, + download_folder: &str, ) -> MLE<()> { println!("Creating list {}", id); @@ -506,9 +506,9 @@ pub fn lists_insert( connection.execute( "INSERT INTO lists VALUES (?1, ?2, ?3, ?4)", [ - id.clone(), + id, mc_version, - mod_loader.to_string(), + &mod_loader.to_string(), download_folder, ], )?; @@ -517,7 +517,7 @@ pub fn lists_insert( Ok(()) } -pub fn lists_remove(config: Cfg, id: String) -> MLE<()> { +pub fn lists_remove(config: &Cfg, id: String) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -526,7 +526,7 @@ pub fn lists_remove(config: Cfg, id: String) -> MLE<()> { Ok(()) } -pub fn lists_get(config: Cfg, list_id: String) -> MLE { +pub fn lists_get(config: &Cfg, list_id: String) -> MLE { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -564,7 +564,7 @@ pub fn lists_get(config: Cfg, list_id: String) -> MLE { Ok(list) } -pub fn lists_version(config: Cfg, list_id: &str, version: &str) -> MLE<()> { +pub fn lists_version(config: &Cfg, list_id: &str, version: &str) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -575,7 +575,7 @@ pub fn lists_version(config: Cfg, list_id: &str, version: &str) -> MLE<()> { Ok(()) } -pub fn lists_get_all_ids(config: Cfg) -> MLE> { +pub fn lists_get_all_ids(config: &Cfg) -> MLE> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -594,7 +594,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: String) -> MLE<()> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -605,7 +605,7 @@ pub fn config_change_current_list(config: Cfg, id: String) -> MLE<()> { Ok(()) } -pub fn config_get_current_list(config: Cfg) -> MLE { +pub fn config_get_current_list(config: &Cfg) -> MLE { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -626,7 +626,7 @@ pub fn config_get_current_list(config: Cfg) -> MLE { //SETUP(UPDATES) pub fn s_userlist_update_download( - config: Cfg, + config: &Cfg, list_id: String, mod_id: String, link: String, @@ -645,7 +645,7 @@ pub fn s_userlist_update_download( Ok(()) } -pub fn s_config_create_version(config: Cfg) -> Result<(), Box> { +pub fn s_config_create_version(config: &Cfg) -> Result<(), Box> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -656,7 +656,7 @@ 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)?; @@ -667,7 +667,7 @@ pub fn s_config_update_version(config: Cfg, ver: String) -> Result<(), Box Result> { +pub fn s_config_get_version(config: &Cfg) -> Result> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -689,7 +689,7 @@ pub fn s_config_get_version(config: Cfg) -> Result) -> MLE<()> { let cached = get_cached_versions(&config.cache); @@ -89,7 +87,7 @@ async fn download_version(config: Cfg, list: List, version: Version, mut cached: progress.set_message(format!("Copy {} to cache", version.id)); let dl_path_file = format!("{}/{}", list.download_folder, filename); - let cache_path = format!("{}/{}", &config.clone().cache, filename); + let cache_path = format!("{}/{}", &config.cache, filename); copy(dl_path_file, cache_path)?; } @@ -135,7 +133,7 @@ async fn download_file(url: &str, path: &str, name: &str, progress: &ProgressBar } pub fn disable_version( - config: Cfg, + config: &Cfg, current_list: List, versionid: String, mod_id: String, diff --git a/src/lib.rs b/src/lib.rs index f59ba89..69cc650 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,7 @@ pub use commands::*; use error::{ErrorType, MLError, MLE}; use serde::{Deserialize, Serialize}; -pub static TICK_CHARS: &str = "#>-"; +pub static PROGRESS_CHARS: &str = "#>-"; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub enum Modloader { diff --git a/src/main.rs b/src/main.rs index 31a320b..0e040b6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -162,7 +162,6 @@ async fn main() { match cli.command { Commands::Mod { command } => { match command { - #[allow(unused_variables)] ModCommands::Add { id, version, @@ -171,10 +170,10 @@ async fn main() { lock, } => { let listf = match list { - Some(list) => lists_get(config.clone(), list).unwrap(), + Some(list) => lists_get(&config, list).unwrap(), None => lists_get( - config.clone(), - config_get_current_list(config.clone()).unwrap(), + &config, + config_get_current_list(&config).unwrap(), ) .unwrap(), }; @@ -186,18 +185,18 @@ async fn main() { let add_id = AddMod { id: marked_id, set_version: lock }; - mod_add(config, vec![add_id], listf, download).await + mod_add(&config, vec![add_id], listf, download).await } ModCommands::Remove { id, list } => { let listf = match list { - Some(list) => lists_get(config.clone(), list).unwrap(), + Some(list) => lists_get(&config, list).unwrap(), None => lists_get( - config.clone(), - config_get_current_list(config.clone()).unwrap(), + &config, + config_get_current_list(&config).unwrap(), ) .unwrap(), }; - mod_remove(config, &id, listf) + mod_remove(&config, &id, listf) } } } @@ -211,28 +210,28 @@ async fn main() { } => { let ml = match modloader { Some(ml) => Modloader::from(&ml).unwrap(), - None => config.clone().defaults.modloader, + None => config.defaults.modloader.clone(), }; let versions_path = &config.versions; let ver = match version { Some(ver) => VersionLevel::from(&ver).get(versions_path, cli.force_gameupdate).await.unwrap(), - None => config.clone().defaults.version.get(versions_path, cli.force_gameupdate).await.unwrap(), + None => config.defaults.version.clone().get(versions_path, cli.force_gameupdate).await.unwrap(), }; - list_add(config, id, ver, ml, directory) + list_add(&config, &id, &ver, &ml, &directory) } - ListCommands::Remove { id } => list_remove(config, id), + ListCommands::Remove { id } => list_remove(&config, id), ListCommands::List => { - list_list(config) + list_list(&config) } - ListCommands::Change { id } => list_change(config, id), + ListCommands::Change { id } => list_change(&config, id), ListCommands::Version { id, version, download, remove, - } => list_version(config, id, version, download, remove).await, + } => list_version(&config, id, version, download, remove).await, } } Commands::Update { @@ -244,34 +243,35 @@ async fn main() { } => { let mut liststack: Vec = vec![]; if all { - let list_ids = lists_get_all_ids(config.clone()).unwrap(); + let list_ids = lists_get_all_ids(&config).unwrap(); for id in list_ids { - liststack.push(lists_get(config.clone(), id).unwrap()); + liststack.push(lists_get(&config, id).unwrap()); } } else { let current = match list { - Some(l) => lists_get(config.clone(), l).unwrap(), - None => get_current_list(config.clone()).unwrap(), + Some(l) => lists_get(&config, l).unwrap(), + None => get_current_list(&config).unwrap(), }; liststack.push(current) } - update(config, liststack, clean, download, remove).await + update(&config, liststack, clean, download, remove).await } Commands::Download { all, clean, remove, list } => { let mut liststack: Vec = vec![]; if all { - let list_ids = lists_get_all_ids(config.clone()).unwrap(); + let list_ids = lists_get_all_ids(&config).unwrap(); for id in list_ids { - liststack.push(lists_get(config.clone(), id).unwrap()); + liststack.push(lists_get(&config, id).unwrap()); } } else { let current = match list { - Some(l) => lists_get(config.clone(), l).unwrap(), - None => get_current_list(config.clone()).unwrap(), + 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 { @@ -284,9 +284,9 @@ async fn main() { .unwrap(), }; - import(config, filestr, download).await + import(&config, filestr, download).await } - Commands::Export { list } => export(config, list), + Commands::Export { list } => export(&config, list), Commands::Test => Ok(()), } .unwrap(); -- cgit v1.2.3 From 7f1a262999d7a8b7f12a97daf4b6722638dc62a1 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Thu, 25 May 2023 21:06:40 +0200 Subject: more progress instead of print, more references --- src/commands/download.rs | 8 ++- src/commands/modification.rs | 18 +++---- src/commands/update.rs | 123 +++++++++++++------------------------------ src/config.rs | 35 ++++++------ src/db.rs | 17 +++--- src/files.rs | 22 ++++---- src/lib.rs | 13 ++++- src/main.rs | 15 +++--- 8 files changed, 109 insertions(+), 142 deletions(-) (limited to 'src') diff --git a/src/commands/download.rs b/src/commands/download.rs index fea3f34..e9a96b5 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -1,4 +1,6 @@ +use indicatif::MultiProgress; + use crate::{config::Cfg, List}; use crate::{ db::userlist_get_all_current_versions_with_mods, @@ -10,10 +12,12 @@ use crate::{ }; pub async fn download(config: &Cfg, liststack: Vec, clean: bool, delete_old: bool) -> MLE<()> { + + let mp = MultiProgress::new(); + for current_list in liststack { println!("Downloading current versions of mods in {}", current_list.id); 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, String::from(¤t_list.id), @@ -54,6 +58,8 @@ pub async fn download(config: &Cfg, liststack: Vec, clean: bool, delete_ol current_list.clone(), config.clone(), get_raw_versions(&config.apis.modrinth, to_download).await, + &mp, + None ) .await?; } else { diff --git a/src/commands/modification.rs b/src/commands/modification.rs index 31931f8..d369c4b 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -1,6 +1,6 @@ use std::{io::Write, collections::HashMap}; -use indicatif::{ProgressBar, ProgressStyle}; +use indicatif::{ProgressBar, ProgressStyle, MultiProgress}; use crate::{ config::Cfg, @@ -11,16 +11,16 @@ use crate::{ error::{ErrorType, MLError, MLE}, files::{delete_version, download_versions}, modrinth::{extract_current_version, get_raw_versions, project, projects, versions, Version}, - List, PROGRESS_CHARS, + List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_SPINNER, }; -#[derive(Debug, Clone)] +#[derive(Debug)] pub struct AddMod { pub id: IDSelector, pub set_version: bool } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] pub enum IDSelector { ModificationID(String), VersionID(String), @@ -43,12 +43,11 @@ pub async fn mod_add( list: List, direct_download: bool, ) -> MLE<()> { - let spinner_style = ProgressStyle::with_template("{spinner:.green}{msg}").unwrap(); - let bar_style = ProgressStyle::with_template("{spinner:.green}{wide_msg}{pos}/{len} [{bar:.green/lime}]").unwrap().progress_chars(PROGRESS_CHARS); - // println!("Add mods to {}", list.id); - // println!(" └Add mods:"); + //TODO MultiProgress + let spinner_style = ProgressStyle::with_template(STYLE_SPINNER).unwrap(); + let bar_style = ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS); let mut mod_ids: Vec<(String, bool)> = Vec::new(); let mut ver_ids: Vec<(String, bool)> = Vec::new(); @@ -153,7 +152,8 @@ pub async fn mod_add( //Download all the added mods if direct_download { - download_versions(list.clone(), config.clone(), downloadstack).await?; + let mp = MultiProgress::new(); + download_versions(list.clone(), config.clone(), downloadstack, &mp, None).await?; }; Ok(()) diff --git a/src/commands/update.rs b/src/commands/update.rs index 7482e43..bde6896 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -9,7 +9,7 @@ use crate::{ error::{ErrorType, MLError, MLE}, files::{clean_list_dir, delete_version, disable_version, download_versions}, modrinth::{extract_current_version, versions, Version}, - List, PROGRESS_CHARS, + List, PROGRESS_CHARS, STYLE_BAR_POS, }; pub async fn update( @@ -23,35 +23,32 @@ pub async fn update( let mp = MultiProgress::new(); let update_p = mp.add(ProgressBar::new(liststack.len().try_into().unwrap())); - let bar_style = ProgressStyle::with_template("{spinner:.green}{wide_msg}{pos}/{len} [{bar:.green/lime}]").unwrap().progress_chars(PROGRESS_CHARS); - let spinner_style = ProgressStyle::with_template("{spinner:.green}{msg}").unwrap(); + let bar_style = ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS); update_p.set_style(bar_style.clone()); update_p.set_message("Update"); for current_list in liststack { + let list_p = mp.insert_before(&update_p, ProgressBar::new(2)); + list_p.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); + list_p.set_message(format!("Update {}", current_list.id)); - // println!("Update mods in {}", current_list.id); let mods = userlist_get_all_ids(config, ¤t_list.id)?; - let list_p = mp.insert_before(&update_p, ProgressBar::new(mods.len().try_into().unwrap())); - list_p.set_style(bar_style.clone()); - list_p.set_message(format!("Update {}", current_list.id)); + let list_u_p = mp.insert_before(&list_p, ProgressBar::new(mods.len().try_into().unwrap())); + list_u_p.set_style(bar_style.clone()); + list_u_p.set_message(format!("Update {}", current_list.id)); let mut current_versions: Vec<(String, String)> = vec![]; let mut updatestack: Vec = vec![]; for id in mods { - let mod_p = mp.insert_before(&list_p, ProgressBar::new(1)); - mod_p.set_style(spinner_style.clone()); - let info = mods_get_info(config, &id)?; - mod_p.set_message(format!("Update {}", info.title)); - // println!(" ├{}", info.title); - + 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)? { - // println!(" │ └Set version, skipping update"); - list_p.inc(1); + list_u_p.inc(1); continue; } @@ -59,15 +56,13 @@ pub async fn update( let disable_version = userlist_get_current_version(config, ¤t_list.id, &id)?; - mod_p.inc(1); - updatestack.push( match specific_update( config, clean, current_list.clone(), &id, - &mod_p + &list_u_p ) .await { @@ -77,44 +72,55 @@ pub async fn update( } Err(e) => { if e.to_string() == "Mod: NO_UPDATE_AVAILABLE" { - // println!( - // " │ └No new version found for the specified minecraft version" - // ); } else { return Err(e); }; - list_p.inc(1); + list_u_p.inc(1); continue; } }, ); - list_p.inc(1); + list_u_p.inc(1); } - list_p.finish_with_message(format!("Updated {}", current_list.id)); + list_u_p.finish_with_message(format!("Updated mods in {}", current_list.id)); + list_p.inc(1); if clean { - update_p.set_message("Cleaning"); - update_p.inc(1); + list_p.set_message("Cleaning"); clean_list_dir(¤t_list)?; }; if direct_download && !updatestack.is_empty() { - download_versions(current_list.clone(), config.clone(), updatestack).await?; + download_versions(current_list.clone(), config.clone(), updatestack, &mp, Some(&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(bar_style.clone()); for ver in current_versions { if delete_old { - println!(" └Delete version {}", ver.0); + d_p.set_message(format!("Delete version {}", ver.0)); + d_p.inc(1); delete_version(current_list.clone(), ver.0)?; } else if ver.0 != "NONE" { - println!(" └Disable version {}", ver.0); + d_p.set_message(format!("Disable version {}", ver.0)); + d_p.inc(1); disable_version(config, current_list.clone(), ver.0, ver.1)?; }; } + + let del_msg = if delete_old { + "Deleted all old versions" + } else { + "Disabled all old versions" + }; + + d_p.finish_with_message(del_msg); } }; + list_p.inc(1); + list_p.finish_with_message(format!("Updated {}", current_list.id)); update_p.inc(1); } @@ -149,13 +155,7 @@ async fn specific_update(config: &Cfg, clean: bool, list: List, id: &str, progre { let current_str = extract_current_version(applicable_versions.clone())?; - if clean { - // println!("\t └Add version to downloadstack"); - } else { - progress.println(format!("Found new version for {}", mods_get_info(config, id).unwrap().title)); - // println!("\t └Get versions for specified minecraft versions"); - // println!("\t └New current version: {}", current_str); - }; + 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 @@ -183,56 +183,5 @@ async fn specific_update(config: &Cfg, clean: bool, list: List, id: &str, progre 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, -// }; -// -// let config = Cfg::init().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 { -// id: "dEqtGnT9".to_string(), -// project_id: "kYuIpRLv".to_string(), -// author_id: "Qnt13hO8".to_string(), -// featured: true, -// name: "1.2.2-1.19 - Fabric".to_string(), -// version_number: "1.2.2-1.19".to_string(), -// changelog: None, -// date_published: "2022-11-02T17:41:43.072267Z".to_string(), -// downloads: 58, -// version_type: VersionType::release, -// files: vec![VersionFile { -// hashes: Hash { -// sha1: "fdc6dc39427fc92cc1d7ad8b275b5b83325e712b".to_string(), -// sha512: "5b372f00d6e5d6a5ef225c3897826b9f6a2be5506905f7f71b9e939779765b41be6f2a9b029cfc752ad0751d0d2d5f8bb4544408df1363eebdde15641e99a849".to_string() -// }, -// url: "https://cdn.modrinth.com/data/kYuIpRLv/versions/dEqtGnT9/waveycapes-fabric-1.2.2-mc1.19.2.jar".to_string(), -// filename: "waveycapes-fabric-1.2.2-mc1.19.2.jar".to_string(), -// primary: true, -// size: 323176 -// }], -// game_versions: vec![ -// "1.19".to_string(), -// "1.19.1".to_string(), -// "1.19.2".to_string() -// ], -// loaders: vec![ -// "fabric".to_string() -// ] -// }]; -// assert!(download_versions(current_list, config, versions) -// .await -// .is_ok()) -// } diff --git a/src/config.rs b/src/config.rs index a952d40..54cf768 100644 --- a/src/config.rs +++ b/src/config.rs @@ -4,6 +4,7 @@ use std::{ path::Path, }; +use indicatif::{ProgressBar, ProgressStyle}; use serde::{Deserialize, Serialize}; use crate::{db::db_setup, error::MLE, Modloader, VersionLevel, check_game_versions}; @@ -79,9 +80,10 @@ impl Cfg { } fn create_config(path: &str) -> MLE<()> { - print!("No config file found, create default"); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush()?; + let p = ProgressBar::new(1); + p.set_style(ProgressStyle::with_template("{wide_msg}").unwrap()); + p.set_message("Create default config"); + let cache_dir = dirs::cache_dir() .unwrap() .join("modlist") @@ -102,37 +104,36 @@ fn create_config(path: &str) -> MLE<()> { create_dir_all(path.split("config.toml").collect::>()[0])?; let mut file = File::create(path)?; file.write_all(toml::to_string(&default_cfg)?.as_bytes())?; - println!(" ✓"); + p.finish_with_message(format!("Created default config ({})", path)); Ok(()) } fn create_database(path: &str) -> MLE<()> { - print!("No database found, create base"); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush()?; + let p = ProgressBar::new(1); + p.set_style(ProgressStyle::with_template("{wide_msg}").unwrap()); + p.set_message("Create database"); File::create(path)?; db_setup(path)?; - println!(" ✓"); + p.finish_with_message(format!("Created database ({})", path)); Ok(()) } fn create_cache(path: &str) -> MLE<()> { - print!("No cache direcory found, create one"); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush()?; + let p = ProgressBar::new(1); + p.set_style(ProgressStyle::with_template("{wide_msg}").unwrap()); + p.set_message("Create cache"); create_dir_all(path)?; - println!(" ✓"); + p.finish_with_message(format!("Created cache ({})", path)); Ok(()) } async fn create_versions_dummy(path: &str) -> MLE<()> { - print!("No version file found, create dummy"); - //Force flush of stdout, else print! doesn't print instantly - std::io::stdout().flush()?; - + let p = ProgressBar::new(1); + p.set_style(ProgressStyle::with_template("{wide_msg}").unwrap()); + p.set_message("Create version file"); File::create(path)?; - println!(" ✓"); + p.finish_with_message(format!("Created version file ({})", path)); Ok(()) } diff --git a/src/db.rs b/src/db.rs index 3409298..22085a5 100644 --- a/src/db.rs +++ b/src/db.rs @@ -121,7 +121,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); + // println!("Removing mod {} from database", id); let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -167,10 +167,10 @@ pub fn mods_get_versions(config: &Cfg, mods: Vec) -> MLE MLE> { 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_USERLIST")), + true => Err(MLError::new(ErrorType::DBError, &format!("NO_MODS_USERLIST{}", list_id))), false => Ok(mod_ids), } } @@ -475,7 +474,7 @@ pub fn userlist_get_all_downloads( for link in link_iter { let l = link?; - println!("Found link {}", String::from(&l)); + // println!("Found link {}", String::from(&l)); links.push(l) } @@ -498,7 +497,7 @@ pub fn lists_insert( mod_loader: &Modloader, download_folder: &str, ) -> MLE<()> { - println!("Creating list {}", id); + // println!("Creating list {}", id); let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; diff --git a/src/files.rs b/src/files.rs index 565d2b6..2830a5f 100644 --- a/src/files.rs +++ b/src/files.rs @@ -14,24 +14,27 @@ use crate::{ db::{mods_get_info, userlist_add_disabled_versions}, error::{ErrorType, MLError, MLE}, modrinth::Version, - List, PROGRESS_CHARS, + List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_SPINNER, STYLE_BAR_BYTE, }; -pub async fn download_versions(list: List, config: Cfg, versions: Vec) -> MLE<()> { +pub async fn download_versions(list: List, config: Cfg, versions: Vec, progress: &MultiProgress, progress_before: Option<&ProgressBar>) -> MLE<()> { let cached = get_cached_versions(&config.cache); - let mp = MultiProgress::new(); - let mut js = JoinSet::new(); - let style_spinner = ProgressStyle::with_template("{spinner:.green}{wide_msg}").unwrap(); + let style_spinner = ProgressStyle::with_template(STYLE_SPINNER).unwrap(); + + let all = match progress_before { + Some(p) => progress.insert_before(p, ProgressBar::new(versions.len().try_into().unwrap())), + None => progress.add(ProgressBar::new(versions.len().try_into().unwrap())), - let all = mp.add(ProgressBar::new(versions.len().try_into().unwrap())); - all.set_style(ProgressStyle::with_template("{wide_msg}{pos}/{len} [{bar:.green/lime}]").unwrap().progress_chars(PROGRESS_CHARS)); + + }; + all.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); all.set_message("Downloading"); for ver in versions { - let p = mp.insert_before(&all, ProgressBar::new(1)); + 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)); // std::thread::sleep(std::time::Duration::from_millis(200)); @@ -103,7 +106,7 @@ async fn download_file(url: &str, path: &str, name: &str, progress: &ProgressBar let size = res.content_length().expect("Couldn't get content length"); - let style_bar_byte = ProgressStyle::with_template("{spinner:.green}{wide_msg}{bytes}/{total_bytes} [{bar:.green/lime}]") + let style_bar_byte = ProgressStyle::with_template(STYLE_BAR_BYTE) .unwrap() .progress_chars(PROGRESS_CHARS); @@ -203,7 +206,6 @@ pub fn get_downloaded_versions(list: List) -> MLE> { pub fn clean_list_dir(list: &List) -> MLE<()> { let dl_path = &list.download_folder; - println!(" └Clean directory for: {}", list.id); for entry in std::fs::read_dir(dl_path)? { let entry = entry?; std::fs::remove_file(entry.path())?; diff --git a/src/lib.rs b/src/lib.rs index 69cc650..a7a34ac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,8 +12,13 @@ pub use apis::*; use apis::modrinth::{get_game_versions, GameVersion, GameVersionType}; pub use commands::*; use error::{ErrorType, MLError, MLE}; +use indicatif::{ProgressStyle, ProgressBar}; use serde::{Deserialize, Serialize}; +pub static STYLE_BAR_POS: &str = "{spinner:.green}{wide_msg}{pos}/{len} [{bar:.green/lime}]"; +pub static STYLE_BAR_BYTE: &str = "{spinner:.green}{wide_msg}{bytes}/{total_bytes} [{bar:.green/lime}]"; +pub static STYLE_SPINNER: &str = "{spinner:.green}{wide_msg}"; +pub static STYLE_MESSAGE: &str = "{wide_msg}"; pub static PROGRESS_CHARS: &str = "#>-"; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] @@ -59,15 +64,19 @@ pub enum VersionLevel { /// Checks if update needed (time) /// if yes: get versions, update pub async fn check_game_versions(path: &str, force: bool) -> MLE<()> { + let p = ProgressBar::new(1); + p.set_style(ProgressStyle::with_template(STYLE_MESSAGE).unwrap()); + p.set_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(()); } - print!("Update minecraft versions"); std::io::stdout().flush()?; let versions = get_game_versions().await; remove_file(path)?; let mut file = File::create(path)?; file.write_all(serde_json::to_string_pretty(&versions)?.as_bytes())?; - println!(" ✓"); + + p.finish_with_message("Updated minecraft versions"); Ok(()) } diff --git a/src/main.rs b/src/main.rs index 0e040b6..7e00368 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,10 +15,6 @@ struct Cli { /// config file path #[arg(short, long)] config: Option, - - /// Force GameVersion update - #[arg(long)] - force_gameupdate: bool, } #[derive(Subcommand)] @@ -30,6 +26,10 @@ enum Commands { List { #[command(subcommand)] command: ListCommands, + + /// Force GameVersion update + #[arg(long)] + force_gameupdate: bool, }, Download { /// download all lists @@ -200,7 +200,7 @@ async fn main() { } } } - Commands::List { command } => { + Commands::List { command, force_gameupdate } => { match command { ListCommands::Add { id, @@ -215,8 +215,8 @@ async fn main() { let versions_path = &config.versions; let ver = match version { - Some(ver) => VersionLevel::from(&ver).get(versions_path, cli.force_gameupdate).await.unwrap(), - None => config.defaults.version.clone().get(versions_path, cli.force_gameupdate).await.unwrap(), + 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) @@ -254,6 +254,7 @@ async fn main() { }; liststack.push(current) } + update(&config, liststack, clean, download, remove).await } Commands::Download { all, clean, remove, list } => { -- cgit v1.2.3 From d8554e30029bf43dccce72e982784cd01857b0c4 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Thu, 25 May 2023 22:48:54 +0200 Subject: added mod add progress --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/commands/download.rs | 31 ++++++++++++++++++---- src/commands/io.rs | 14 +++++----- src/commands/list.rs | 8 +++--- src/commands/modification.rs | 62 +++++++++++++++++++++----------------------- src/commands/update.rs | 23 +++++++--------- src/db.rs | 4 +-- src/files.rs | 22 ++++++---------- src/lib.rs | 5 ++-- src/main.rs | 20 +++++++------- 11 files changed, 100 insertions(+), 93 deletions(-) (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index 394a3e6..39a163c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -829,7 +829,7 @@ dependencies = [ [[package]] name = "modlist" -version = "0.14.2" +version = "0.15.0" dependencies = [ "chrono", "clap", diff --git a/Cargo.toml b/Cargo.toml index a4b51bc..c0fca21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "modlist" -version = "0.14.2" +version = "0.15.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/commands/download.rs b/src/commands/download.rs index e9a96b5..7aa0156 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -1,6 +1,7 @@ -use indicatif::MultiProgress; +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, @@ -14,9 +15,12 @@ use crate::{ 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)); for current_list in liststack { - println!("Downloading current versions of mods in {}", current_list.id); + download_p.set_message(format!("Download in {}", current_list.id)); + let downloaded_versions = get_downloaded_versions(current_list.clone())?; let current_version_ids = match userlist_get_all_current_versions_with_mods( config, @@ -59,24 +63,41 @@ pub async fn download(config: &Cfg, liststack: Vec, clean: bool, delete_ol config.clone(), get_raw_versions(&config.apis.modrinth, to_download).await, &mp, - None + &download_p, ) .await?; } else { - println!("There are no new versions to download"); + 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)); for ver in to_disable { if delete_old { - // println!("Deleting version {} for mod {}", ver.1, ver.0); + d_p.set_message(format!("Delete version {}", ver.1)); + d_p.inc(1); delete_version(current_list.clone(), ver.1)?; } else { + d_p.set_message(format!("Disable version {}", ver.1)); + d_p.inc(1); disable_version(config, current_list.clone(), ver.1, ver.0)?; }; } + + let del_msg = if delete_old { + "Deleted all old versions" + } else { + "Disabled all old versions" + }; + + d_p.finish_with_message(del_msg); } + + download_p.inc(1); } + download_p.finish_with_message("Downloaded all lists"); + Ok(()) } diff --git a/src/commands/io.rs b/src/commands/io.rs index 43e642a..45e363e 100644 --- a/src/commands/io.rs +++ b/src/commands/io.rs @@ -39,18 +39,18 @@ struct ExportList { } impl ExportList { - pub fn from(config: &Cfg, list_id: String, download: bool) -> MLE { - let list = lists_get(config, String::from(&list_id))?; + pub fn from(config: &Cfg, list_id: &str, download: bool) -> MLE { + let list = lists_get(config, list_id)?; let mut dl_folder = None; if download { dl_folder = Some(list.download_folder) }; - let mods = userlist_get_all_ids(config, &list_id)?; + let mods = userlist_get_all_ids(config, list_id)?; let mut versions = vec![]; for m in mods { - versions.push(ExportVersion::from(config, &list_id, &m)?) + versions.push(ExportVersion::from(config, list_id, &m)?) } Ok(Self { @@ -68,11 +68,11 @@ pub fn export(config: &Cfg, list: Option) -> MLE<()> { if list.is_none() { list_ids = lists_get_all_ids(config)?; } else { - list_ids.push(lists_get(config, list.unwrap())?.id); + list_ids.push(lists_get(config, &list.unwrap())?.id); } let mut lists: Vec = vec![]; for list_id in list_ids { - lists.push(ExportList::from(config, list_id, true)?); + lists.push(ExportList::from(config, &list_id, true)?); } let toml = toml::to_string(&Export { lists })?; @@ -85,7 +85,7 @@ pub fn export(config: &Cfg, list: Option) -> MLE<()> { Ok(()) } -pub async fn import(config: &Cfg, file_str: String, direct_download: bool) -> MLE<()> { +pub async fn import(config: &Cfg, file_str: &str, direct_download: bool) -> MLE<()> { let mut file = File::open(file_str)?; let mut content = String::new(); file.read_to_string(&mut content)?; diff --git a/src/commands/list.rs b/src/commands/list.rs index 95f9927..52f14f2 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -18,7 +18,7 @@ pub struct List { pub fn get_current_list(config: &Cfg) -> MLE { let id = config_get_current_list(config)?; - lists_get(config, id) + lists_get(config, &id) } pub fn list_add( @@ -52,7 +52,7 @@ pub fn list_remove(config: &Cfg, id: String) -> MLE<()> { /// * `args` - All args, to extract the new version pub async fn list_version( config: &Cfg, - id: String, + id: &str, mc_version: String, download: bool, delete: bool, @@ -62,7 +62,7 @@ pub async fn list_version( id, mc_version ); - lists_version(config, &id, &mc_version)?; + lists_version(config, id, &mc_version)?; println!( "\nCheck for updates for new minecraft version in list {}", @@ -75,7 +75,7 @@ pub async fn list_version( pub fn list_list(config: &Cfg) -> MLE<()> { let lists = lists_get_all_ids(config)?; for list in lists { - let l = lists_get(config, list)?; + let l = lists_get(config, &list)?; println!("{}: | {} | {}", l.id, l.mc_version, l.modloader) } Ok(()) diff --git a/src/commands/modification.rs b/src/commands/modification.rs index d369c4b..8abf913 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -11,7 +11,7 @@ use crate::{ 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, STYLE_SPINNER, + List, PROGRESS_CHARS, STYLE_BAR_POS, }; #[derive(Debug)] @@ -43,57 +43,49 @@ pub async fn mod_add( list: List, direct_download: bool, ) -> MLE<()> { + let mp = MultiProgress::new(); - //TODO MultiProgress - - let spinner_style = ProgressStyle::with_template(STYLE_SPINNER).unwrap(); - let bar_style = ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS); let mut mod_ids: Vec<(String, bool)> = Vec::new(); let mut ver_ids: Vec<(String, bool)> = Vec::new(); - - let p = ProgressBar::new(mods.len().try_into().unwrap()); - p.set_style(spinner_style.clone()); - p.set_message("Sort ids"); + + 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_message("Sort ids"); //"Sort" project ids from version ids to be able to handle them differently but in a batch for m in mods { - p.inc(1); + add_p.inc(1); match m.id { IDSelector::ModificationID(pid) => mod_ids.push((pid, m.set_version)), IDSelector::VersionID(vid) => ver_ids.push((vid, m.set_version)), } } + + add_p.set_message("Get infos"); - p.finish_with_message("Sort ids done"); - - let info_p = ProgressBar::new(2); - info_p.set_message("Get infos"); - info_p.set_style(bar_style.clone()); let mut projectinfo: Vec = Vec::new(); if !mod_ids.is_empty() { projectinfo.append(&mut get_mod_infos(config, mod_ids, list.clone()).await?); - info_p.inc(1); }; if !ver_ids.is_empty() { projectinfo.append(&mut get_ver_info(config, ver_ids).await?); - info_p.inc(1); }; - info_p.finish_with_message("Get infos done"); - if projectinfo.is_empty() { return Err(MLError::new(ErrorType::ArgumentError, "NO_IDS?")); }; + add_p.set_message("Add mods to database"); + let mut downloadstack: Vec = Vec::new(); //Adding each mod to the lists and downloadstack - let add_p = ProgressBar::new(projectinfo.len().try_into().unwrap()); - add_p.set_style(bar_style); + 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 { - add_p.set_message(format!("Add {}", project.title)); + project_p.set_message(format!("Add {}", project.title)); let current_version_id = if project.current_version.is_none() { String::from("NONE") @@ -144,18 +136,19 @@ pub async fn mod_add( downloadstack.push(project.current_version.unwrap()) }; - // add_p.println(format!("Added {}", project.title)); - add_p.inc(1); + project_p.inc(1); } - add_p.finish_with_message("Added all mods"); + project_p.finish_with_message("Added all mods to the database"); //Download all the added mods if direct_download { - let mp = MultiProgress::new(); - download_versions(list.clone(), config.clone(), downloadstack, &mp, None).await?; + add_p.set_message("Download mods"); + download_versions(list.clone(), config.clone(), downloadstack, &mp, &add_p).await?; }; + add_p.finish_with_message("Added all mods"); + Ok(()) } @@ -277,14 +270,17 @@ async fn get_ver_info(config: &Cfg, ver_ids: Vec<(String, bool)>) -> MLE f, + None => { files[0].clone() } + } .url; + projectinfo.push(ProjectInfo { mod_id: String::from(&project.id), slug: project.slug, diff --git a/src/commands/update.rs b/src/commands/update.rs index bde6896..194bbe5 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -9,7 +9,7 @@ use crate::{ error::{ErrorType, MLError, MLE}, files::{clean_list_dir, delete_version, disable_version, download_versions}, modrinth::{extract_current_version, versions, Version}, - List, PROGRESS_CHARS, STYLE_BAR_POS, + List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION, }; pub async fn update( @@ -23,23 +23,21 @@ pub async fn update( let mp = MultiProgress::new(); let update_p = mp.add(ProgressBar::new(liststack.len().try_into().unwrap())); - let bar_style = ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS); - update_p.set_style(bar_style.clone()); - update_p.set_message("Update"); + 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)); + let list_p = mp.insert_before(&update_p, ProgressBar::new(2)); - list_p.set_style(ProgressStyle::with_template(STYLE_BAR_POS).unwrap().progress_chars(PROGRESS_CHARS)); - list_p.set_message(format!("Update {}", current_list.id)); + list_p.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + list_p.set_message("Update mods"); 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(bar_style.clone()); - list_u_p.set_message(format!("Update {}", current_list.id)); + 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![]; for id in mods { @@ -84,7 +82,6 @@ pub async fn update( } list_u_p.finish_with_message(format!("Updated mods in {}", current_list.id)); - list_p.inc(1); if clean { list_p.set_message("Cleaning"); @@ -92,12 +89,12 @@ pub async fn update( }; if direct_download && !updatestack.is_empty() { - download_versions(current_list.clone(), config.clone(), updatestack, &mp, Some(&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(bar_style.clone()); + 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)); @@ -119,14 +116,12 @@ pub async fn update( d_p.finish_with_message(del_msg); } }; - list_p.inc(1); list_p.finish_with_message(format!("Updated {}", current_list.id)); update_p.inc(1); } update_p.finish_with_message("Updated all lists"); - Ok(()) } diff --git a/src/db.rs b/src/db.rs index 22085a5..1f3ad4c 100644 --- a/src/db.rs +++ b/src/db.rs @@ -525,7 +525,7 @@ pub fn lists_remove(config: &Cfg, id: String) -> MLE<()> { Ok(()) } -pub fn lists_get(config: &Cfg, list_id: String) -> MLE { +pub fn lists_get(config: &Cfg, list_id: &str) -> MLE { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -549,7 +549,7 @@ pub fn lists_get(config: &Cfg, list_id: String) -> MLE { for l in list_iter { let li = l?; list = List { - id: String::from(&list_id), + id: list_id.to_string(), mc_version: String::from(&li[0]), modloader: Modloader::from(&li[1])?, download_folder: String::from(&li[2]), diff --git a/src/files.rs b/src/files.rs index 2830a5f..814f06d 100644 --- a/src/files.rs +++ b/src/files.rs @@ -14,37 +14,29 @@ use crate::{ db::{mods_get_info, userlist_add_disabled_versions}, error::{ErrorType, MLError, MLE}, modrinth::Version, - List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_SPINNER, STYLE_BAR_BYTE, + List, PROGRESS_CHARS, STYLE_SPINNER, STYLE_BAR_BYTE, STYLE_BAR_POS, }; -pub async fn download_versions(list: List, config: Cfg, versions: Vec, progress: &MultiProgress, progress_before: Option<&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 = match progress_before { - Some(p) => progress.insert_before(p, ProgressBar::new(versions.len().try_into().unwrap())), - None => progress.add(ProgressBar::new(versions.len().try_into().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)); - all.set_message("Downloading"); + 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)); - // std::thread::sleep(std::time::Duration::from_millis(200)); } while js.join_next().await.is_some() { all.inc(1) } - all.finish(); - - // mp.clear().unwrap(); + all.finish_with_message(format!("✓Downloading {}", list.id)); Ok(()) } @@ -56,10 +48,12 @@ async fn download_version(config: Cfg, list: List, version: Version, mut cached: progress.set_message(format!("{} - {}", project_info.title, version.id)); + let mut cache_msg = ""; //Check cache if already downloaded let c = cached.remove(&version.id); if c.is_some() { progress.set_message(format!("Get {} from cache", version.id)); + cache_msg = " (cached)"; copy_cached_version(&c.unwrap(), &dl_path); } else { let files = version.files; @@ -95,7 +89,7 @@ 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)); + progress.finish_with_message(format!("✓{} - {}{}", project_info.title, version.id, cache_msg)); Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index a7a34ac..7287660 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,9 +15,10 @@ use error::{ErrorType, MLError, MLE}; use indicatif::{ProgressStyle, ProgressBar}; use serde::{Deserialize, Serialize}; -pub static STYLE_BAR_POS: &str = "{spinner:.green}{wide_msg}{pos}/{len} [{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 PROGRESS_CHARS: &str = "#>-"; @@ -70,7 +71,7 @@ pub async fn check_game_versions(path: &str, force: bool) -> MLE<()> { let creation_time = fs::metadata(path)?.created()?; if !force && creation_time.elapsed().unwrap() < Duration::from_secs(60 * 60 * 24) { return Ok(()); } - std::io::stdout().flush()?; + let versions = get_game_versions().await; remove_file(path)?; let mut file = File::create(path)?; diff --git a/src/main.rs b/src/main.rs index 7e00368..d03f88a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -170,10 +170,10 @@ async fn main() { lock, } => { let listf = match list { - Some(list) => lists_get(&config, list).unwrap(), + Some(list) => lists_get(&config, &list).unwrap(), None => lists_get( &config, - config_get_current_list(&config).unwrap(), + &config_get_current_list(&config).unwrap(), ) .unwrap(), }; @@ -189,10 +189,10 @@ async fn main() { } ModCommands::Remove { id, list } => { let listf = match list { - Some(list) => lists_get(&config, list).unwrap(), + Some(list) => lists_get(&config, &list).unwrap(), None => lists_get( &config, - config_get_current_list(&config).unwrap(), + &config_get_current_list(&config).unwrap(), ) .unwrap(), }; @@ -231,7 +231,7 @@ async fn main() { version, download, remove, - } => list_version(&config, id, version, download, remove).await, + } => list_version(&config, &id, version, download, remove).await, } } Commands::Update { @@ -245,11 +245,11 @@ async fn main() { if all { let list_ids = lists_get_all_ids(&config).unwrap(); for id in list_ids { - liststack.push(lists_get(&config, id).unwrap()); + liststack.push(lists_get(&config, &id).unwrap()); } } else { let current = match list { - Some(l) => lists_get(&config, l).unwrap(), + Some(l) => lists_get(&config, &l).unwrap(), None => get_current_list(&config).unwrap(), }; liststack.push(current) @@ -262,11 +262,11 @@ async fn main() { if all { let list_ids = lists_get_all_ids(&config).unwrap(); for id in list_ids { - liststack.push(lists_get(&config, id).unwrap()); + liststack.push(lists_get(&config, &id).unwrap()); } } else { let current = match list { - Some(l) => lists_get(&config, l).unwrap(), + Some(l) => lists_get(&config, &l).unwrap(), None => get_current_list(&config).unwrap(), }; liststack.push(current) @@ -285,7 +285,7 @@ async fn main() { .unwrap(), }; - import(&config, filestr, download).await + import(&config, &filestr, download).await } Commands::Export { list } => export(&config, list), Commands::Test => Ok(()), -- cgit v1.2.3 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 --- Cargo.lock | 325 ++++++++++++++++--------------------------- 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 +++++++++++----------- 13 files changed, 526 insertions(+), 482 deletions(-) (limited to 'src') diff --git a/Cargo.lock b/Cargo.lock index 39a163c..c72ac69 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,11 +19,11 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "ahash" -version = "0.7.6" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" +checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" dependencies = [ - "getrandom", + "cfg-if", "once_cell", "version_check", ] @@ -39,9 +39,9 @@ dependencies = [ [[package]] name = "anstream" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6342bd4f5a1205d7f41e94a41a901f5647c938cdfa96036338e8533c9d6c2450" +checksum = "0ca84f3628370c59db74ee214b3263d58f9aadd9b4fe7e711fd87dc452b7f163" dependencies = [ "anstyle", "anstyle-parse", @@ -109,9 +109,9 @@ dependencies = [ [[package]] name = "base64" -version = "0.21.0" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a" +checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" [[package]] name = "bitflags" @@ -121,15 +121,15 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.2.1" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24a6904aef64d73cf10ab17ebace7befb918b82164785cb89907993be7f83813" +checksum = "6776fc96284a0bb647b615056fc496d1fe1644a7ab01829818a6d91cae888b84" [[package]] name = "bumpalo" -version = "3.12.1" +version = "3.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b1ce199063694f33ffb7dd4e0ee620741495c32833cde5aa08f02a0bf96f0c8" +checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" [[package]] name = "bytes" @@ -166,9 +166,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.2.4" +version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "956ac1f6381d8d82ab4684768f89c0ea3afe66925ceadb4eeb3fc452ffc55d62" +checksum = "93aae7a4192245f70fe75dd9157fc7b4a5bf53e88d30bd4396f7d8f9284d5acc" dependencies = [ "clap_builder", "clap_derive", @@ -177,9 +177,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.2.4" +version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84080e799e54cff944f4b4a4b0e71630b0e0443b25b985175c7dddc1a859b749" +checksum = "4f423e341edefb78c9caba2d9c7f7687d0e72e89df3ce3394554754393ac3990" dependencies = [ "anstream", "anstyle", @@ -190,40 +190,30 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.2.1" +version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a19591b2ab0e3c04b588a0e04ddde7b9eaa423646d1b4a8092879216bf47473" +checksum = "a04ddfaacc3bc9e6ea67d024575fafc2a813027cf374b8f24f7bc233c6b6be12" dependencies = [ "clap", ] [[package]] name = "clap_derive" -version = "4.2.0" +version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9644cd56d6b87dbe899ef8b053e331c0637664e9e21a33dfcdc36093f5c5c4" +checksum = "191d9573962933b4027f932c600cd252ce27a8ad5979418fe78e43c07996f27b" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.15", + "syn", ] [[package]] name = "clap_lex" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a2dd5a6fe8c6e3502f568a6353e5273bbb15193ad9a89e457b9970798efbea1" - -[[package]] -name = "codespan-reporting" -version = "0.11.1" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" -dependencies = [ - "termcolor", - "unicode-width", -] +checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" [[package]] name = "colorchoice" @@ -233,9 +223,9 @@ checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" [[package]] name = "console" -version = "0.15.6" +version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0525278dce688103060006713371cedbad27186c7d913f33d866b498da0f595" +checksum = "c926e00cc70edefdc64d3a5ff31cc65bb97a3460097762bd23afb4d8145fccf8" dependencies = [ "encode_unicode", "lazy_static", @@ -260,68 +250,25 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" -[[package]] -name = "cxx" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f61f1b6389c3fe1c316bf8a4dccc90a38208354b330925bce1f74a6c4756eb93" -dependencies = [ - "cc", - "cxxbridge-flags", - "cxxbridge-macro", - "link-cplusplus", -] - -[[package]] -name = "cxx-build" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cee708e8962df2aeb38f594aae5d827c022b6460ac71a7a3e2c3c2aae5a07b" -dependencies = [ - "cc", - "codespan-reporting", - "once_cell", - "proc-macro2", - "quote", - "scratch", - "syn 2.0.15", -] - -[[package]] -name = "cxxbridge-flags" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7944172ae7e4068c533afbb984114a56c46e9ccddda550499caa222902c7f7bb" - -[[package]] -name = "cxxbridge-macro" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2345488264226bf682893e25de0769f3360aac9957980ec49361b083ddaa5bc5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.15", -] - [[package]] name = "dirs" -version = "5.0.0" +version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dece029acd3353e3a58ac2e3eb3c8d6c35827a892edc6cc4138ef9c33df46ecd" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" dependencies = [ "dirs-sys", ] [[package]] name = "dirs-sys" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04414300db88f70d74c5ff54e50f9e1d1737d9a5b90f53fcf2e95ca2a9ab554b" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" dependencies = [ "libc", + "option-ext", "redox_users", - "windows-sys 0.45.0", + "windows-sys 0.48.0", ] [[package]] @@ -450,7 +397,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn", ] [[package]] @@ -501,9 +448,9 @@ checksum = "ad0a93d233ebf96623465aad4046a8d3aa4da22d4f4beba5388838c8a434bbb4" [[package]] name = "h2" -version = "0.3.18" +version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17f8a914c2987b688368b5138aa05321db91f4090cf26118185672ad588bce21" +checksum = "d357c7ae988e7d2182f7d7871d0b963962420b0678b0997ce7de72001aeab782" dependencies = [ "bytes", "fnv", @@ -523,17 +470,23 @@ name = "hashbrown" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" dependencies = [ "ahash", ] [[package]] name = "hashlink" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69fe1fcf8b4278d860ad0548329f892a3631fb63f82574df68275f34cdbe0ffa" +checksum = "0761a1b9491c4f2e3d66aa0f62d0fba0af9a0e2852e4d48ea506632a4b56e6aa" dependencies = [ - "hashbrown", + "hashbrown 0.13.2", ] [[package]] @@ -644,12 +597,11 @@ dependencies = [ [[package]] name = "iana-time-zone-haiku" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" dependencies = [ - "cxx", - "cxx-build", + "cc", ] [[package]] @@ -669,7 +621,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" dependencies = [ "autocfg", - "hashbrown", + "hashbrown 0.12.3", ] [[package]] @@ -695,9 +647,9 @@ dependencies = [ [[package]] name = "io-lifetimes" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c66c74d2ae7e79a5a8f7ac924adbe38ee42a859c6539ad869eb51f0b52dc220" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ "hermit-abi 0.3.1", "libc", @@ -730,9 +682,9 @@ checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" [[package]] name = "js-sys" -version = "0.3.61" +version = "0.3.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445dde2150c55e483f3d8416706b97ec8e8237c307e5b7b4b8dd15e6af2a0730" +checksum = "2f37a4a5928311ac501dee68b3c7613a1037d0edb30c8e5427bd832d55d1b790" dependencies = [ "wasm-bindgen", ] @@ -745,9 +697,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.142" +version = "0.2.144" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a987beff54b60ffa6d51982e1aa1146bc42f19bd26be28b0586f252fccf5317" +checksum = "2b00cc1c228a6782d0f076e7b232802e0c5689d41bb5df366f2a6b6621cfdfe1" [[package]] name = "libsqlite3-sys" @@ -760,20 +712,11 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "link-cplusplus" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" -dependencies = [ - "cc", -] - [[package]] name = "linux-raw-sys" -version = "0.3.4" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36eb31c1778188ae1e64398743890d0877fef36d11521ac60406b42016e8c2cf" +checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" [[package]] name = "lock_api" @@ -937,7 +880,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn", ] [[package]] @@ -958,6 +901,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "parking_lot" version = "0.12.1" @@ -1001,9 +950,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" -version = "0.3.26" +version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160" +checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" [[package]] name = "portable-atomic" @@ -1022,18 +971,18 @@ checksum = "dc59d1bcc64fc5d021d67521f818db868368028108d37f0e98d74e33f68297b5" [[package]] name = "proc-macro2" -version = "1.0.56" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" +checksum = "6aeca18b86b413c660b781aa319e4e2648a3e6f9eadc9b47e9038e6fe9f3451b" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.26" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" +checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" dependencies = [ "proc-macro2", ] @@ -1069,9 +1018,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.16" +version = "0.11.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b71749df584b7f4cac2c426c127a7c785a5106cc98f7a8feb044115f0fa254" +checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55" dependencies = [ "base64", "bytes", @@ -1112,7 +1061,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "549b9d036d571d42e6e85d1c1425e2ac83491075078ca9a15be021c56b1641f2" dependencies = [ - "bitflags 2.2.1", + "bitflags 2.3.1", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -1128,9 +1077,9 @@ checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" [[package]] name = "rustix" -version = "0.37.15" +version = "0.37.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0661814f891c57c930a610266415528da53c4933e6dea5fb350cbfe048a9ece" +checksum = "acf8729d8542766f1b2cf77eb034d52f40d375bb8b615d0b147089946e16613d" dependencies = [ "bitflags 1.3.2", "errno", @@ -1161,17 +1110,11 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" -[[package]] -name = "scratch" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1" - [[package]] name = "security-framework" -version = "2.8.2" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a332be01508d814fed64bf28f798a146d73792121129962fdf335bb3c49a4254" +checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8" dependencies = [ "bitflags 1.3.2", "core-foundation", @@ -1182,9 +1125,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.8.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c9bb296072e961fcbd8853511dd39c2d8be2deb1e17c6860b1d30732b323b4" +checksum = "f51d0c0d83bec45f16480d0ce0058397a69e48fcdc52d1dc8855fb68acbd31a7" dependencies = [ "core-foundation-sys", "libc", @@ -1192,22 +1135,22 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.160" +version = "1.0.163" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" +checksum = "2113ab51b87a539ae008b5c6c02dc020ffa39afd2d83cffcb3f4eb2722cebec2" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.160" +version = "1.0.163" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" +checksum = "8c805777e3930c8883389c602315a24224bcc738b63905ef87cd1420353ea93e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn", ] [[package]] @@ -1223,9 +1166,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4" +checksum = "93107647184f6027e3b7dcb2e11034cf95ffa1e3a682c67951963ac69c1c007d" dependencies = [ "serde", ] @@ -1284,20 +1227,9 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "syn" -version = "1.0.109" +version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a34fcf3e8b60f57e6a14301a2e916d323af98b0ea63c599441eec8558660c822" +checksum = "45b6ddbb36c5b969c182aec3c4a0bce7df3fbad4b77114706a49aacc80567388" dependencies = [ "proc-macro2", "quote", @@ -1317,15 +1249,6 @@ dependencies = [ "windows-sys 0.45.0", ] -[[package]] -name = "termcolor" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" -dependencies = [ - "winapi-util", -] - [[package]] name = "thiserror" version = "1.0.40" @@ -1343,7 +1266,7 @@ checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn", ] [[package]] @@ -1374,9 +1297,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.28.0" +version = "1.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3c786bf8134e5a3a166db9b29ab8f48134739014a3eca7bc6bfa95d673b136f" +checksum = "0aa32867d44e6f2ce3385e89dceb990188b8bb0fb25b0cf576647a6f98ac5105" dependencies = [ "autocfg", "bytes", @@ -1399,7 +1322,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn", ] [[package]] @@ -1428,9 +1351,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b403acf6f2bb0859c93c7f0d967cb4a75a7ac552100f9322faf64dc047669b21" +checksum = "d6135d499e69981f9ff0ef2167955a5333c35e36f6937d382974566b3d5b94ec" dependencies = [ "serde", "serde_spanned", @@ -1440,18 +1363,18 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622" +checksum = "5a76a9312f5ba4c2dec6b9161fdf25d87ad8a09256ccea5a556fef03c706a10f" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.19.8" +version = "0.19.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239410c8609e8125456927e6707163a3b1fdb40561e4b803bc041f466ccfdc13" +checksum = "2380d56e8670370eee6566b0bfd4265f65b3f432e8c6d85623f728d4fa31f739" dependencies = [ "indexmap", "serde", @@ -1468,19 +1391,20 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.38" +version = "0.1.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9cf6a813d3f40c88b0b6b6f29a5c95c6cdbf97c1f9cc53fb820200f5ad814d" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" dependencies = [ + "cfg-if", "pin-project-lite", "tracing-core", ] [[package]] name = "tracing-core" -version = "0.1.30" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" dependencies = [ "once_cell", ] @@ -1499,9 +1423,9 @@ checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" [[package]] name = "unicode-ident" -version = "1.0.8" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" +checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" [[package]] name = "unicode-normalization" @@ -1571,9 +1495,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.84" +version = "0.2.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31f8dcbc21f30d9b8f2ea926ecb58f6b91192c17e9d33594b3df58b2007ca53b" +checksum = "5bba0e8cb82ba49ff4e229459ff22a191bbe9a1cb3a341610c9c33efc27ddf73" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -1581,24 +1505,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.84" +version = "0.2.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95ce90fd5bcc06af55a641a86428ee4229e44e07033963a2290a8e241607ccb9" +checksum = "19b04bc93f9d6bdee709f6bd2118f57dd6679cf1176a1af464fca3ab0d66d8fb" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 1.0.109", + "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.34" +version = "0.4.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f219e0d211ba40266969f6dbdd90636da12f75bee4fc9d6c23d1260dadb51454" +checksum = "2d1985d03709c53167ce907ff394f5316aa22cb4e12761295c5dc57dacb6297e" dependencies = [ "cfg-if", "js-sys", @@ -1608,9 +1532,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.84" +version = "0.2.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c21f77c0bedc37fd5dc21f897894a5ca01e7bb159884559461862ae90c0b4c5" +checksum = "14d6b024f1a526bb0234f52840389927257beb670610081360e5a03c5df9c258" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -1618,22 +1542,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.84" +version = "0.2.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6" +checksum = "e128beba882dd1eb6200e1dc92ae6c5dbaa4311aa7bb211ca035779e5efc39f8" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.84" +version = "0.2.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d" +checksum = "ed9d5b4305409d1fc9482fee2d7f9bcbf24b3972bf59817ef757e23982242a93" [[package]] name = "wasm-streams" @@ -1650,9 +1574,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.61" +version = "0.3.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33b99f4b23ba3eec1a53ac264e35a755f00e966e0065077d6027c0f575b0b97" +checksum = "3bdd9ef4e984da1187bf8110c5cf5b845fbc87a23602cdf912386a76fcd3a7c2" dependencies = [ "js-sys", "wasm-bindgen", @@ -1674,15 +1598,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" @@ -1847,9 +1762,9 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" -version = "0.4.1" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8970b36c66498d8ff1d66685dc86b91b29db0c7739899012f63a63814b4b28" +checksum = "61de7bac303dc551fe038e2b3cef0f571087a47571ea6e79a87692ac99b99699" dependencies = [ "memchr", ] 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 From 7755c9acf6b8a1d81c03ef1138e80a162f36e743 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Fri, 26 May 2023 17:45:08 +0200 Subject: removed all println! --- src/commands/modification.rs | 9 --------- src/db.rs | 8 -------- src/files.rs | 1 - src/lib.rs | 2 -- 4 files changed, 20 deletions(-) (limited to 'src') diff --git a/src/commands/modification.rs b/src/commands/modification.rs index fdb70c7..577bbd1 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -166,8 +166,6 @@ async fn get_mod_infos( let mut ids = vec![]; - // println!("{:?}", mod_ids); - for id in mod_ids { setmap.insert(id.0.to_string(), id.1); ids.push(id.0); @@ -182,8 +180,6 @@ async fn get_mod_infos( _ => panic!("PANIC"), }; for project in m_projects { - // println!("\t└{}", project.title); - // println!("\t └Get versions"); let available_versions = versions( &config.apis.modrinth, String::from(&project.id), @@ -196,7 +192,6 @@ async fn get_mod_infos( let file: String; if !available_versions.is_empty() { let current_id = extract_current_version(available_versions.clone())?; - // println!("\t └Current version: {}", current_id); current_version = Some( available_versions @@ -219,8 +214,6 @@ async fn get_mod_infos( available_versions_vec.push(ver.id); } - // println!("{:?}", setmap); - projectinfo.push(ProjectInfo { mod_id: String::from(&project.id), slug: project.slug.clone(), @@ -231,7 +224,6 @@ async fn get_mod_infos( set_version: *setmap.get(&project.slug).unwrap(), }) } else { - // println!("\t └There's currently no mod version for your specified target"); current_version = None; file = String::from("NONE"); available_versions_vec.push(String::from("NONE")); @@ -335,7 +327,6 @@ pub fn mod_remove(config: &Cfg, id: &str, list: &List) -> MLE<()> { Ok(m) => m, Err(err) => { if err.to_string() == "Database: NO_MODS_USERLIST" { - println!(" ✓"); return Ok(()); }; return Err(err); diff --git a/src/db.rs b/src/db.rs index f627ef4..1958fc5 100644 --- a/src/db.rs +++ b/src/db.rs @@ -165,11 +165,6 @@ pub fn mods_get_versions(config: &Cfg, mods: Vec) -> MLE MLE<()> { - // println!("Creating list {}", id); - let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; diff --git a/src/files.rs b/src/files.rs index e874d9d..c81857b 100644 --- a/src/files.rs +++ b/src/files.rs @@ -160,7 +160,6 @@ pub fn disable_version( versionid: String, mod_id: String, ) -> MLE<()> { - //println!("Disabling version {} for mod {}", versionid, mod_id); let file = get_file_path(¤t_list, String::from(&versionid))?; let disabled = format!("{}.disabled", file); diff --git a/src/lib.rs b/src/lib.rs index 8196f1c..d76f8bf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -117,14 +117,12 @@ impl VersionLevel { 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(); - println!("{:?}", snapshot); Ok(snapshot.version) } VersionLevel::Version(v) => { -- cgit v1.2.3 From c7ecf3019a75dc0ab1a0aefeb9b880899fc8a231 Mon Sep 17 00:00:00 2001 From: fxqnlr Date: Mon, 29 May 2023 18:01:12 +0200 Subject: cargo fmt and add fmt file --- .rustfmt.toml | 1 + src/apis/modrinth.rs | 10 +++- src/cache.rs | 3 +- src/commands/download.rs | 39 +++++++++---- src/commands/io.rs | 6 +- src/commands/list.rs | 4 +- src/commands/modification.rs | 55 +++++++++++++++---- src/commands/update.rs | 56 +++++++++++++++---- src/config.rs | 7 ++- src/db.rs | 128 +++++++++++++++++++++++++++++-------------- src/error.rs | 8 ++- src/files.rs | 18 ++++-- src/lib.rs | 14 ++++- src/main.rs | 17 ++++-- 14 files changed, 269 insertions(+), 97 deletions(-) create mode 100644 .rustfmt.toml (limited to 'src') diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000..df99c69 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1 @@ +max_width = 80 diff --git a/src/apis/modrinth.rs b/src/apis/modrinth.rs index fb3952d..9a22633 100644 --- a/src/apis/modrinth.rs +++ b/src/apis/modrinth.rs @@ -130,7 +130,10 @@ pub enum GameVersionType { beta, } -async fn get(api: &str, path: &str) -> Result>, Box> { +async fn get( + api: &str, + path: &str, +) -> Result>, Box> { let url = format!(r#"{}{}"#, api, path); let client = Client::builder() @@ -182,7 +185,10 @@ pub async fn versions(api: &str, id: String, list: List) -> Vec { } ///Get version with the version ids -pub async fn get_raw_versions(api: &str, versions: Vec) -> Vec { +pub async fn get_raw_versions( + api: &str, + versions: Vec, +) -> Vec { let url = format!(r#"versions?ids=["{}"]"#, versions.join(r#"",""#)); let data = get(api, &url).await.unwrap().unwrap(); diff --git a/src/cache.rs b/src/cache.rs index 1e22091..8df4d2f 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -31,6 +31,7 @@ pub fn get_cached_versions(path: &str) -> HashMap { /// Panics if . pub fn copy_cached_version(version_path: &str, download_path: &str) { let versplit: Vec<&str> = version_path.split('/').collect(); - let download = format!("{}/{}", download_path, versplit[versplit.len() - 1]); + let download = + format!("{}/{}", download_path, versplit[versplit.len() - 1]); copy(version_path, download).unwrap(); } diff --git a/src/commands/download.rs b/src/commands/download.rs index dd00ffb..a7cf744 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -5,7 +5,8 @@ use crate::{ db::userlist_get_all_current_versions_with_mods, error::{ErrorType, MLError, MLE}, files::{ - clean_list_dir, delete_version, disable_version, download_versions, get_downloaded_versions, + clean_list_dir, delete_version, disable_version, download_versions, + get_downloaded_versions, }, modrinth::get_raw_versions, }; @@ -18,7 +19,8 @@ pub async fn download( delete_old: bool, ) -> MLE<()> { let mp = MultiProgress::new(); - let download_p = mp.add(ProgressBar::new(liststack.len().try_into().unwrap())); + let download_p = + mp.add(ProgressBar::new(liststack.len().try_into().unwrap())); download_p.set_style( ProgressStyle::with_template(STYLE_BAR_POS) .unwrap() @@ -28,14 +30,19 @@ pub async fn download( for current_list in liststack { download_p.set_message(format!("Download in {}", current_list.id)); - let downloaded_versions = get_downloaded_versions(current_list.clone())?; - let current_version_ids = match userlist_get_all_current_versions_with_mods( - config, - String::from(¤t_list.id), - ) { - Ok(i) => Ok(i), - Err(e) => Err(MLError::new(ErrorType::DBError, e.to_string().as_str())), - }?; + let downloaded_versions = + get_downloaded_versions(current_list.clone())?; + let current_version_ids = + match userlist_get_all_current_versions_with_mods( + config, + String::from(¤t_list.id), + ) { + Ok(i) => Ok(i), + Err(e) => Err(MLError::new( + ErrorType::DBError, + e.to_string().as_str(), + )), + }?; let mut to_download: Vec = vec![]; //(mod_id, version_id) @@ -54,7 +61,10 @@ pub async fn 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_disable.push(( + mod_id.clone(), + String::from(downloaded_version), + )); to_download.push(current_version); } } @@ -98,7 +108,12 @@ pub async fn download( } else { d_p.set_message(format!("Disable version {}", ver.1)); d_p.inc(1); - disable_version(config, current_list.clone(), ver.1, ver.0)?; + disable_version( + config, + current_list.clone(), + ver.1, + ver.0, + )?; }; } diff --git a/src/commands/io.rs b/src/commands/io.rs index 2501583..8e44b2b 100644 --- a/src/commands/io.rs +++ b/src/commands/io.rs @@ -102,7 +102,11 @@ pub fn export(config: &Cfg, list: Option) -> MLE<()> { Ok(()) } -pub async fn import(config: &Cfg, file_str: &str, direct_download: bool) -> MLE<()> { +pub async fn import( + config: &Cfg, + file_str: &str, + direct_download: bool, +) -> MLE<()> { let mut file = File::open(file_str)?; let mut content = String::new(); file.read_to_string(&mut content)?; diff --git a/src/commands/list.rs b/src/commands/list.rs index b0a082d..3665446 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -3,8 +3,8 @@ use indicatif::{ProgressBar, ProgressStyle}; use crate::{ config::Cfg, db::{ - config_change_current_list, config_get_current_list, lists_get, lists_get_all_ids, - lists_insert, lists_remove, lists_version, + config_change_current_list, config_get_current_list, lists_get, + lists_get_all_ids, lists_insert, lists_remove, lists_version, }, error::{ErrorType, MLError, MLE}, update, Modloader, STYLE_OPERATION, diff --git a/src/commands/modification.rs b/src/commands/modification.rs index 577bbd1..4488b70 100644 --- a/src/commands/modification.rs +++ b/src/commands/modification.rs @@ -5,12 +5,16 @@ use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use crate::{ config::Cfg, db::{ - lists_get_all_ids, mods_get_id, mods_get_info, mods_insert, mods_remove, - userlist_get_all_ids, userlist_get_current_version, userlist_insert, userlist_remove, + 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}, + modrinth::{ + extract_current_version, get_raw_versions, project, projects, versions, + Version, + }, List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION, }; @@ -60,7 +64,9 @@ pub async fn mod_add( for m in mods { add_p.inc(1); match m.id { - IDSelector::ModificationID(pid) => mod_ids.push((pid, m.set_version)), + IDSelector::ModificationID(pid) => { + mod_ids.push((pid, m.set_version)) + } IDSelector::VersionID(vid) => ver_ids.push((vid, m.set_version)), } } @@ -69,7 +75,8 @@ pub async fn mod_add( let mut projectinfo: Vec = Vec::new(); if !mod_ids.is_empty() { - projectinfo.append(&mut get_mod_infos(config, mod_ids, list.clone()).await?); + projectinfo + .append(&mut get_mod_infos(config, mod_ids, list.clone()).await?); }; if !ver_ids.is_empty() { projectinfo.append(&mut get_ver_info(config, ver_ids).await?); @@ -113,7 +120,10 @@ pub async fn mod_add( project.set_version, ) { Err(e) => { - let expected_err = format!("SQL: UNIQUE constraint failed: {}.mod_id", list.id); + let expected_err = format!( + "SQL: UNIQUE constraint failed: {}.mod_id", + list.id + ); if e.to_string() == expected_err { Err(MLError::new( ErrorType::ModError, @@ -126,7 +136,12 @@ 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(..) @@ -149,7 +164,14 @@ pub async fn mod_add( //Download all the added mods if direct_download { add_p.set_message("Download mods"); - download_versions(list.clone(), config.clone(), downloadstack, &mp, &add_p).await?; + download_versions( + list.clone(), + config.clone(), + downloadstack, + &mp, + &add_p, + ) + .await?; }; add_p.finish_with_message("Added all mods"); @@ -191,7 +213,8 @@ async fn get_mod_infos( let current_version: Option; let file: String; if !available_versions.is_empty() { - let current_id = extract_current_version(available_versions.clone())?; + let current_id = + extract_current_version(available_versions.clone())?; current_version = Some( available_versions @@ -242,7 +265,10 @@ async fn get_mod_infos( Ok(projectinfo) } -async fn get_ver_info(config: &Cfg, ver_ids: Vec<(String, bool)>) -> MLE> { +async fn get_ver_info( + config: &Cfg, + ver_ids: Vec<(String, bool)>, +) -> MLE> { let mut setmap: HashMap = HashMap::new(); let mut ids = vec![]; @@ -311,7 +337,9 @@ pub fn mod_remove(config: &Cfg, id: &str, list: &List) -> MLE<()> { 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); }; } @@ -343,7 +371,10 @@ pub fn mod_remove(config: &Cfg, id: &str, list: &List) -> MLE<()> { mods_remove(config, &mod_id)?; }; - progress.finish_with_message(format!("Removed {} from {}", info.title, list.id)); + 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 3aae002..c19c02c 100644 --- a/src/commands/update.rs +++ b/src/commands/update.rs @@ -4,10 +4,13 @@ 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, + 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}, + files::{ + clean_list_dir, delete_version, disable_version, download_versions, + }, modrinth::{extract_current_version, versions, Version}, List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION, }; @@ -21,7 +24,8 @@ pub async fn update( ) -> MLE<()> { let mp = MultiProgress::new(); - let update_p = mp.add(ProgressBar::new(liststack.len().try_into().unwrap())); + let update_p = + mp.add(ProgressBar::new(liststack.len().try_into().unwrap())); update_p.set_style( ProgressStyle::with_template(STYLE_BAR_POS) .unwrap() @@ -32,12 +36,16 @@ pub async fn update( update_p.set_message(format!("Update {}", current_list.id)); let list_p = mp.insert_before(&update_p, ProgressBar::new(2)); - list_p.set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); + list_p + .set_style(ProgressStyle::with_template(STYLE_OPERATION).unwrap()); list_p.set_message("Update mods"); 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())); + 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() @@ -58,10 +66,19 @@ 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 @@ -79,7 +96,10 @@ pub async fn update( list_u_p.inc(1); } - list_u_p.finish_with_message(format!("Updated mods in {}", current_list.id)); + list_u_p.finish_with_message(format!( + "Updated mods in {}", + current_list.id + )); if clean { list_p.set_message("Cleaning"); @@ -100,7 +120,9 @@ pub async fn update( if !clean { let d_p = mp.insert_before( &list_p, - ProgressBar::new(current_versions.len().try_into().unwrap()), + ProgressBar::new( + current_versions.len().try_into().unwrap(), + ), ); d_p.set_style( ProgressStyle::with_template(STYLE_BAR_POS) @@ -115,7 +137,12 @@ pub async fn update( } else if ver.0 != "NONE" { d_p.set_message(format!("Disable version {}", ver.0)); d_p.inc(1); - disable_version(config, current_list.clone(), ver.0, ver.1)?; + disable_version( + config, + current_list.clone(), + ver.0, + ver.1, + )?; }; } @@ -144,7 +171,8 @@ async fn specific_update( id: &str, progress: &ProgressBar, ) -> 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![]; @@ -159,7 +187,11 @@ async fn specific_update( 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())?; diff --git a/src/config.rs b/src/config.rs index 3858484..f0eb8f7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -7,7 +7,9 @@ use std::{ use indicatif::{ProgressBar, ProgressStyle}; use serde::{Deserialize, Serialize}; -use crate::{check_game_versions, db::db_setup, error::MLE, Modloader, VersionLevel}; +use crate::{ + check_game_versions, db::db_setup, error::MLE, Modloader, VersionLevel, +}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Cfg { @@ -44,7 +46,8 @@ impl Cfg { let mut file = match File::open(&configfile) { Ok(file) => file, Err(err) => { - if err.kind() == std::io::ErrorKind::NotFound && path.is_none() { + if err.kind() == std::io::ErrorKind::NotFound && path.is_none() + { create_config(&configfile)?; File::open(&configfile)? } else { diff --git a/src/db.rs b/src/db.rs index 1958fc5..49db2fd 100644 --- a/src/db.rs +++ b/src/db.rs @@ -21,7 +21,9 @@ pub fn mods_insert(config: &Cfg, id: &str, slug: &str, name: &str) -> MLE<()> { Ok(()) } -pub fn mods_get_all_ids(config: &Cfg) -> Result, Box> { +pub fn mods_get_all_ids( + config: &Cfg, +) -> Result, Box> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); @@ -64,8 +66,10 @@ pub fn mods_get_id(data: &str, slug: &str) -> MLE { } //get from id if no slug found if mod_id.is_empty() { - let mut stmt = connection.prepare("SELECT id FROM mods WHERE id = ?")?; - let id_iter = stmt.query_map([slug], |row| row.get::(0))?; + let mut stmt = + connection.prepare("SELECT id FROM mods WHERE id = ?")?; + let id_iter = + stmt.query_map([slug], |row| row.get::(0))?; for id in id_iter { mod_id = id?; @@ -73,8 +77,10 @@ pub fn mods_get_id(data: &str, slug: &str) -> MLE { } //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 mut stmt = + connection.prepare("SELECT id FROM mods WHERE title = ?")?; + let id_iter = + stmt.query_map([slug], |row| row.get::(0))?; for id in id_iter { mod_id = id?; @@ -98,7 +104,8 @@ pub fn mods_get_info(config: &Cfg, id: &str) -> MLE { let connection = Connection::open(data)?; let mut mod_info: Option = None; - let mut stmt = connection.prepare("SELECT title, slug FROM mods WHERE id = ?")?; + 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)?, @@ -135,7 +142,10 @@ pub struct DBModlistVersions { pub versions: String, } -pub fn mods_get_versions(config: &Cfg, mods: Vec) -> MLE> { +pub fn mods_get_versions( + config: &Cfg, + mods: Vec, +) -> MLE> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -153,8 +163,9 @@ 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)?, @@ -218,7 +229,8 @@ pub fn userlist_get_all_ids(config: &Cfg, list_id: &str) -> MLE> { let connection = Connection::open(data).unwrap(); let mut mod_ids: Vec = Vec::new(); - let mut stmt = connection.prepare(format!("SELECT mod_id FROM {}", list_id).as_str())?; + let mut stmt = connection + .prepare(format!("SELECT mod_id FROM {}", list_id).as_str())?; let id_iter = stmt.query_map([], |row| row.get::(0))?; for id in id_iter { @@ -261,7 +273,8 @@ pub fn userlist_get_applicable_versions( ) .as_str(), )?; - let ver_iter = stmt.query_map([mod_id], |row| row.get::(0))?; + let ver_iter = + stmt.query_map([mod_id], |row| row.get::(0))?; for ver in ver_iter { version = ver?; @@ -281,8 +294,9 @@ pub fn userlist_get_all_applicable_versions_with_mods( 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)?, @@ -302,14 +316,21 @@ pub fn userlist_get_all_applicable_versions_with_mods( Ok(versions) } -pub fn userlist_get_current_version(config: &Cfg, list_id: &str, mod_id: &str) -> MLE { +pub fn userlist_get_current_version( + config: &Cfg, + list_id: &str, + mod_id: &str, +) -> MLE { let data = format!("{}/data.db", config.data); let connection = Connection::open(data).unwrap(); let 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?; @@ -321,13 +342,16 @@ 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)?; let mut versions: Vec = Vec::new(); - let mut stmt = - connection.prepare(format!("SELECT current_version FROM {}", list_id).as_str())?; + 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 { @@ -349,8 +373,9 @@ pub fn userlist_get_all_current_versions_with_mods( 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)?, @@ -373,14 +398,21 @@ pub fn userlist_get_all_current_versions_with_mods( 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 = format!("{}/data.db", config.data); 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?; @@ -413,11 +445,16 @@ pub fn userlist_add_disabled_versions( let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; - let currently_disabled_versions = - userlist_get_disabled_versions(config, String::from(&list_id), String::from(&mod_id))?; + let 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), + false => { + format!("{}|{}", currently_disabled_versions, disabled_version) + } }; connection.execute( @@ -440,9 +477,12 @@ pub fn userlist_get_disabled_versions( 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?; @@ -462,8 +502,9 @@ pub fn userlist_get_all_downloads( 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 mut stmt = connection.prepare( + format!("SELECT current_download FROM {}", list_id).as_str(), + )?; let link_iter = stmt.query_map([], |row| row.get::(0))?; for link in link_iter { @@ -521,8 +562,9 @@ pub fn lists_get(config: &Cfg, list_id: &str) -> MLE { modloader: Modloader::Fabric, download_folder: String::new(), }; - let mut stmt = connection - .prepare("SELECT mc_version, modloader, download_folder FROM lists WHERE id = ?")?; + 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![ @@ -595,7 +637,8 @@ pub fn config_get_current_list(config: &Cfg) -> MLE { 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 mut stmt = connection + .prepare("SELECT value FROM user_config WHERE id = 'current_list'")?; let list_iter = stmt.query_map([], |row| row.get::(0))?; for list in list_iter { @@ -630,7 +673,9 @@ pub fn s_userlist_update_download( Ok(()) } -pub fn s_config_create_version(config: &Cfg) -> Result<(), Box> { +pub fn s_config_create_version( + config: &Cfg, +) -> Result<(), Box> { let data = format!("{}/data.db", config.data); let connection = Connection::open(data)?; @@ -655,12 +700,15 @@ pub fn s_config_update_version( Ok(()) } -pub fn s_config_get_version(config: &Cfg) -> Result> { +pub fn s_config_get_version( + config: &Cfg, +) -> Result> { let data = format!("{}/data.db", config.data); 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 mut stmt = connection + .prepare("SELECT value FROM user_config WHERE id = 'db_version'")?; let ver_iter = stmt.query_map([], |row| row.get::(0))?; for ver in ver_iter { diff --git a/src/error.rs b/src/error.rs index f981f14..a2b37a8 100644 --- a/src/error.rs +++ b/src/error.rs @@ -34,8 +34,12 @@ impl std::error::Error for MLError { impl fmt::Display for MLError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.etype { - ErrorType::ArgumentError => write!(f, "User input not accepted: {}", self.message), - ErrorType::ArgumentCountError => write!(f, "Too many/too few arguments"), + ErrorType::ArgumentError => { + write!(f, "User input not accepted: {}", self.message) + } + ErrorType::ArgumentCountError => { + write!(f, "Too many/too few arguments") + } ErrorType::ConfigError => write!(f, "CONFIG"), ErrorType::DBError => write!(f, "Database: {}", self.message), ErrorType::ModError => write!(f, "Mod: {}", self.message), diff --git a/src/files.rs b/src/files.rs index c81857b..3a16c62 100644 --- a/src/files.rs +++ b/src/files.rs @@ -92,7 +92,9 @@ async fn download_version( let mut splitname: Vec<&str> = file.filename.split('.').collect(); let extension = match splitname.pop().ok_or("") { Ok(e) => e, - Err(..) => return Err(MLError::new(ErrorType::Other, "NO_FILE_EXTENSION")), + Err(..) => { + return Err(MLError::new(ErrorType::Other, "NO_FILE_EXTENSION")) + } }; let filename = format!( "{}.mr.{}.{}.{}", @@ -102,7 +104,8 @@ async fn download_version( 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); @@ -119,7 +122,12 @@ async fn download_version( Ok(()) } -async fn download_file(url: &str, path: &str, name: &str, progress: &ProgressBar) -> MLE<()> { +async fn download_file( + url: &str, + path: &str, + name: &str, + progress: &ProgressBar, +) -> MLE<()> { let dl_path_file = format!("{}/{}", path, name); let res = Client::new().get(url).send().await?; @@ -185,7 +193,9 @@ 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]; diff --git a/src/lib.rs b/src/lib.rs index d76f8bf..f77befc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,7 +44,9 @@ impl Modloader { "forge" => Ok(Modloader::Forge), "fabric" => Ok(Modloader::Fabric), "quilt" => Ok(Modloader::Quilt), - _ => Err(MLError::new(ErrorType::ArgumentError, "UNKNOWN_MODLOADER")), + _ => { + Err(MLError::new(ErrorType::ArgumentError, "UNKNOWN_MODLOADER")) + } } } } @@ -76,7 +78,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) { + if !force + && creation_time.elapsed().unwrap() < Duration::from_secs(60 * 60 * 24) + { return Ok(()); } @@ -107,7 +111,11 @@ impl VersionLevel { } } - pub async fn get(self, versions_path: &str, force_update: bool) -> MLE { + pub async fn get( + self, + versions_path: &str, + force_update: bool, + ) -> MLE { let path = format!("{}/versions.json", versions_path); check_game_versions(&path, force_update).await?; let mut versions = load_game_versions(&path)?.into_iter(); diff --git a/src/main.rs b/src/main.rs index d9ad6af..5d60a17 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,9 @@ use clap::{Parser, Subcommand}; use modlist::{ config::Cfg, db::{config_get_current_list, lists_get, lists_get_all_ids}, - download, export, get_current_list, import, list_add, list_change, list_list, list_remove, - list_version, mod_add, mod_remove, update, AddMod, IDSelector, List, Modloader, VersionLevel, + 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)] @@ -170,7 +171,11 @@ async fn main() { } => { let listf = match list { Some(list) => lists_get(&config, &list).unwrap(), - None => lists_get(&config, &config_get_current_list(&config).unwrap()).unwrap(), + None => lists_get( + &config, + &config_get_current_list(&config).unwrap(), + ) + .unwrap(), }; let marked_id = match version { @@ -188,7 +193,11 @@ async fn main() { 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(), + None => lists_get( + &config, + &config_get_current_list(&config).unwrap(), + ) + .unwrap(), }; mod_remove(&config, &id, &listf) } -- cgit v1.2.3