summaryrefslogtreecommitdiff
path: root/src/commands
diff options
context:
space:
mode:
authorfx <[email protected]>2023-04-23 14:13:03 +0200
committerfx <[email protected]>2023-04-23 14:13:03 +0200
commit4300ad2eb05dddfa4274e04b204f2ad28c87da05 (patch)
treea2fd059e3aefff812d0d25e23fc85203dc9d122a /src/commands
parent2711f05669e353fbf452156d54855e9ba454f4a8 (diff)
parent64958cc9ff0858dbf068625e35b8d5dae249d4a4 (diff)
downloadmodlist-4300ad2eb05dddfa4274e04b204f2ad28c87da05.tar
modlist-4300ad2eb05dddfa4274e04b204f2ad28c87da05.tar.gz
modlist-4300ad2eb05dddfa4274e04b204f2ad28c87da05.zip
Merge pull request 'clap' (#1) from clap into master
Reviewed-on: http://raspberrypi.fritz.box:7920/fx/modlist/pulls/1
Diffstat (limited to 'src/commands')
-rw-r--r--src/commands/download.rs46
-rw-r--r--src/commands/io.rs78
-rw-r--r--src/commands/list.rs81
-rw-r--r--src/commands/mod.rs16
-rw-r--r--src/commands/modification.rs223
-rw-r--r--src/commands/setup.rs12
-rw-r--r--src/commands/update.rs132
7 files changed, 372 insertions, 216 deletions
diff --git a/src/commands/download.rs b/src/commands/download.rs
index 2714630..9434591 100644
--- a/src/commands/download.rs
+++ b/src/commands/download.rs
@@ -1,10 +1,16 @@
1use crate::{files::{get_downloaded_versions, download_versions, delete_version, disable_version, clean_list_dir}, db::{userlist_get_all_current_versions_with_mods, lists_get_all_ids, lists_get}, modrinth::get_raw_versions, error::{MLE, ErrorType, MLError}}; 1use crate::{config::Cfg, get_current_list, List};
2use crate::{List, get_current_list, config::Cfg, input::Input}; 2use crate::{
3 3 db::{lists_get, lists_get_all_ids, userlist_get_all_current_versions_with_mods},
4pub async fn download(config: Cfg, input: Input) -> MLE<()> { 4 error::{ErrorType, MLError, MLE},
5 files::{
6 clean_list_dir, delete_version, disable_version, download_versions, get_downloaded_versions,
7 },
8 modrinth::get_raw_versions,
9};
5 10
11pub async fn download(config: Cfg, all_lists: bool, clean: bool, delete_old: bool) -> MLE<()> {
6 let mut liststack: Vec<List> = vec![]; 12 let mut liststack: Vec<List> = vec![];
7 if input.all_lists { 13 if all_lists {
8 let list_ids = lists_get_all_ids(config.clone())?; 14 let list_ids = lists_get_all_ids(config.clone())?;
9 for id in list_ids { 15 for id in list_ids {
10 liststack.push(lists_get(config.clone(), id)?); 16 liststack.push(lists_get(config.clone(), id)?);
@@ -18,7 +24,10 @@ pub async fn download(config: Cfg, input: Input) -> MLE<()> {
18 for current_list in liststack { 24 for current_list in liststack {
19 let downloaded_versions = get_downloaded_versions(current_list.clone())?; 25 let downloaded_versions = get_downloaded_versions(current_list.clone())?;
20 println!("To download: {:#?}", downloaded_versions); 26 println!("To download: {:#?}", downloaded_versions);
21 let current_version_ids = match userlist_get_all_current_versions_with_mods(config.clone(), String::from(&current_list.id)) { 27 let current_version_ids = match userlist_get_all_current_versions_with_mods(
28 config.clone(),
29 String::from(&current_list.id),
30 ) {
22 Ok(i) => Ok(i), 31 Ok(i) => Ok(i),
23 Err(e) => Err(MLError::new(ErrorType::DBError, e.to_string().as_str())), 32 Err(e) => Err(MLError::new(ErrorType::DBError, e.to_string().as_str())),
24 }?; 33 }?;
@@ -33,31 +42,40 @@ pub async fn download(config: Cfg, input: Input) -> MLE<()> {
33 42
34 let current_download = downloaded_versions.get(&mod_id); 43 let current_download = downloaded_versions.get(&mod_id);
35 44
36 if current_download.is_none() || input.clean { 45 if current_download.is_none() || clean {
37 to_download.push(current_version); 46 to_download.push(current_version);
38 } else { 47 } else {
39 let downloaded_version = current_download.ok_or("SOMETHING_HAS_REALLY_GONE_WRONG").unwrap(); 48 let downloaded_version = current_download
49 .ok_or("SOMETHING_HAS_REALLY_GONE_WRONG")
50 .unwrap();
40 if &current_version != downloaded_version { 51 if &current_version != downloaded_version {
41 to_disable.push((mod_id.clone(), String::from(downloaded_version))); 52 to_disable.push((mod_id.clone(), String::from(downloaded_version)));
42 to_download.push(current_version); 53 to_download.push(current_version);
43 } 54 }
44 } 55 }
45 } 56 }
46 57
47 if input.clean { clean_list_dir(&current_list)? }; 58 if clean {
59 clean_list_dir(&current_list)?
60 };
48 61
49 if !to_download.is_empty() { 62 if !to_download.is_empty() {
50 download_versions(current_list.clone(), config.clone(), get_raw_versions(&config.apis.modrinth, to_download).await).await?; 63 download_versions(
64 current_list.clone(),
65 config.clone(),
66 get_raw_versions(&config.apis.modrinth, to_download).await,
67 )
68 .await?;
51 } else { 69 } else {
52 println!("There are no new versions to download"); 70 println!("There are no new versions to download");
53 } 71 }
54 72
55 if !to_disable.is_empty() { 73 if !to_disable.is_empty() {
56 for ver in to_disable { 74 for ver in to_disable {
57 if input.delete_old { 75 if delete_old {
58 println!("Deleting version {} for mod {}", ver.1, ver.0); 76 println!("Deleting version {} for mod {}", ver.1, ver.0);
59 delete_version(current_list.clone(), ver.1)?; 77 delete_version(current_list.clone(), ver.1)?;
60 } else { 78 } else {
61 disable_version(config.clone(), current_list.clone(), ver.1, ver.0)?; 79 disable_version(config.clone(), current_list.clone(), ver.1, ver.0)?;
62 }; 80 };
63 } 81 }
diff --git a/src/commands/io.rs b/src/commands/io.rs
index a3d056f..7f03eec 100644
--- a/src/commands/io.rs
+++ b/src/commands/io.rs
@@ -1,12 +1,18 @@
1use serde::{Deserialize, Serialize};
1use std::fs::File; 2use std::fs::File;
2use std::io::prelude::*; 3use std::io::prelude::*;
3use serde::{Serialize, Deserialize};
4 4
5use crate::{input::{Input, IoOptions}, db::{lists_get, userlist_get_all_ids, lists_get_all_ids, lists_insert}, config::Cfg, Modloader, List, devdir, error::MLE, mods_add, IDSelector}; 5use crate::{
6 config::Cfg,
7 db::{lists_get, lists_get_all_ids, lists_insert, userlist_get_all_ids},
8 devdir,
9 error::MLE,
10 mod_add, IDSelector, List, Modloader,
11};
6 12
7#[derive(Debug, Serialize, Deserialize)] 13#[derive(Debug, Serialize, Deserialize)]
8struct Export { 14struct Export {
9 lists: Vec<ExportList> 15 lists: Vec<ExportList>,
10} 16}
11 17
12#[derive(Debug, Serialize, Deserialize)] 18#[derive(Debug, Serialize, Deserialize)]
@@ -20,73 +26,77 @@ struct ExportList {
20 26
21impl ExportList { 27impl ExportList {
22 pub fn from(config: Cfg, list_id: String, download: bool) -> MLE<Self> { 28 pub fn from(config: Cfg, list_id: String, download: bool) -> MLE<Self> {
23
24 let list = lists_get(config.clone(), String::from(&list_id))?; 29 let list = lists_get(config.clone(), String::from(&list_id))?;
25 30
26 let mut dl_folder = None; 31 let mut dl_folder = None;
27 if download{ dl_folder = Some(list.download_folder) }; 32 if download {
33 dl_folder = Some(list.download_folder)
34 };
28 35
29 let mods = userlist_get_all_ids(config, list_id)?.join("|"); 36 let mods = userlist_get_all_ids(config, list_id)?.join("|");
30 37
31 Ok(Self { id: list.id, mods, launcher: list.modloader.to_string(), mc_version: list.mc_version, download_folder: dl_folder }) 38 Ok(Self {
39 id: list.id,
40 mods,
41 launcher: list.modloader.to_string(),
42 mc_version: list.mc_version,
43 download_folder: dl_folder,
44 })
32 } 45 }
33} 46}
34 47
35pub async fn io(config: Cfg, input: Input) -> MLE<()> { 48pub fn export(config: Cfg, list: Option<String>) -> MLE<()> {
36
37 match input.clone().io_options.unwrap() {
38 IoOptions::Export => { export(config, input)? },
39 IoOptions::Import => { import(config, input).await? },
40 }
41
42 Ok(())
43}
44
45fn export(config: Cfg, input: Input) -> MLE<()> {
46 let mut list_ids: Vec<String> = vec![]; 49 let mut list_ids: Vec<String> = vec![];
47 if input.all_lists { 50 if list.is_none() {
48 list_ids = lists_get_all_ids(config.clone())?; 51 list_ids = lists_get_all_ids(config.clone())?;
49 } else { 52 } else {
50 list_ids.push(lists_get(config.clone(), input.list.unwrap().id)?.id); 53 list_ids.push(lists_get(config.clone(), list.unwrap())?.id);
51 } 54 }
52 let mut lists: Vec<ExportList> = vec![]; 55 let mut lists: Vec<ExportList> = vec![];
53 for list_id in list_ids { 56 for list_id in list_ids {
54 lists.push(ExportList::from(config.clone(), list_id, true)?); 57 lists.push(ExportList::from(config.clone(), list_id, true)?);
55 } 58 }
56 59
57 let toml = toml::to_string( &Export { lists } )?; 60 let toml = toml::to_string(&Export { lists })?;
58 61
59 let filestr = dirs::home_dir().unwrap().join("mlexport.toml"); 62 let filestr = dirs::home_dir().unwrap().join("mlexport.toml");
60 63
61 let mut file = File::create(devdir(filestr.into_os_string().into_string().unwrap().as_str()))?; 64 let mut file = File::create(devdir(
65 filestr.into_os_string().into_string().unwrap().as_str(),
66 ))?;
62 file.write_all(toml.as_bytes())?; 67 file.write_all(toml.as_bytes())?;
63 68
64 Ok(()) 69 Ok(())
65} 70}
66 71
67async fn import(config: Cfg, input: Input) -> MLE<()> { 72pub async fn import(config: Cfg, file_str: String, direct_download: bool) -> MLE<()> {
68 73 let mut file = File::open(file_str)?;
69 let filestr: String = match input.file {
70 Some(args) => args,
71 None => devdir(dirs::home_dir().unwrap().join("mlexport.toml").into_os_string().into_string().unwrap().as_str()),
72 };
73
74 let mut file = File::open(filestr)?;
75 let mut content = String::new(); 74 let mut content = String::new();
76 file.read_to_string(&mut content)?; 75 file.read_to_string(&mut content)?;
77 let export: Export = toml::from_str(&content)?; 76 let export: Export = toml::from_str(&content)?;
78 77
79 for exportlist in export.lists { 78 for exportlist in export.lists {
80 let list = List { id: exportlist.id, mc_version: exportlist.mc_version, modloader: Modloader::from(&exportlist.launcher)?, download_folder: exportlist.download_folder.ok_or("NO_DL").unwrap() }; 79 let list = List {
81 lists_insert(config.clone(), list.id.clone(), list.mc_version.clone(), list.modloader.clone(), String::from(&list.download_folder))?; 80 id: exportlist.id,
81 mc_version: exportlist.mc_version,
82 modloader: Modloader::from(&exportlist.launcher)?,
83 download_folder: exportlist.download_folder.ok_or("NO_DL").unwrap(),
84 };
85 lists_insert(
86 config.clone(),
87 list.id.clone(),
88 list.mc_version.clone(),
89 list.modloader.clone(),
90 String::from(&list.download_folder),
91 )?;
82 let mods: Vec<&str> = exportlist.mods.split('|').collect(); 92 let mods: Vec<&str> = exportlist.mods.split('|').collect();
83 let mut mod_ids = vec![]; 93 let mut mod_ids = vec![];
84 for mod_id in mods { 94 for mod_id in mods {
85 mod_ids.push(IDSelector::ModificationID(String::from(mod_id))); 95 mod_ids.push(IDSelector::ModificationID(String::from(mod_id)));
86 }; 96 }
87 //TODO impl set_version and good direct download 97 //TODO impl set_version and good direct download
88 //TODO impl all at once, dafuck 98 //TODO impl all at once, dafuck
89 mods_add(config.clone(), mod_ids, list, input.direct_download, false).await?; 99 mod_add(config.clone(), mod_ids, list, direct_download, false).await?;
90 } 100 }
91 Ok(()) 101 Ok(())
92} 102}
diff --git a/src/commands/list.rs b/src/commands/list.rs
index 8e86973..13176f4 100644
--- a/src/commands/list.rs
+++ b/src/commands/list.rs
@@ -1,4 +1,12 @@
1use crate::{db::{lists_insert, lists_remove, config_change_current_list, config_get_current_list, lists_get, lists_version}, Modloader, config::Cfg, input::{Input, ListOptions}, cmd_update, error::MLE}; 1use crate::{
2 config::Cfg,
3 db::{
4 config_change_current_list, config_get_current_list, lists_get, lists_insert, lists_remove,
5 lists_version,
6 },
7 error::MLE,
8 update, Modloader,
9};
2 10
3#[derive(Debug, Clone, PartialEq, Eq)] 11#[derive(Debug, Clone, PartialEq, Eq)]
4pub struct List { 12pub struct List {
@@ -8,60 +16,55 @@ pub struct List {
8 pub download_folder: String, 16 pub download_folder: String,
9} 17}
10 18
11pub async fn list(config: Cfg, input: Input) -> MLE<()> {
12
13 match input.clone().list_options.unwrap() {
14 ListOptions::Add => {
15 add(config, input)
16 },
17 ListOptions::Change => {
18 change(config, input)
19 },
20 ListOptions::Remove => {
21 remove(config, input)
22 },
23 ListOptions::Version => {
24 version(config, input).await
25 }
26 }
27}
28
29pub fn get_current_list(config: Cfg) -> MLE<List> { 19pub fn get_current_list(config: Cfg) -> MLE<List> {
30 let id = config_get_current_list(config.clone())?; 20 let id = config_get_current_list(config.clone())?;
31 lists_get(config, id) 21 lists_get(config, id)
32} 22}
33 23
34fn add(config: Cfg, input: Input) -> MLE<()> { 24pub fn list_add(
35 let id = input.list_id.unwrap(); 25 config: Cfg,
36 let mc_version = input.list_mcversion.unwrap(); 26 id: String,
37 let mod_loader = input.modloader.unwrap(); 27 mc_version: String,
38 let download_folder = input.directory.unwrap(); 28 modloader: Modloader,
39 lists_insert(config, id, mc_version, mod_loader, download_folder) 29 directory: String,
30) -> MLE<()> {
31 lists_insert(config, id, mc_version, modloader, directory)
40} 32}
41 33
42fn change(config: Cfg, input: Input) -> MLE<()> { 34pub fn list_change(config: Cfg, id: String) -> MLE<()> {
43 println!("Change default list to: {}", input.clone().list.unwrap().id); 35 //TODO check if list exists
44 config_change_current_list(config, input.list.unwrap().id) 36 println!("Change default list to: {}", id);
37 config_change_current_list(config, id)
45} 38}
46 39
47fn remove(config: Cfg, input: Input) -> MLE<()> { 40pub fn list_remove(config: Cfg, id: String) -> MLE<()> {
48 lists_remove(config, input.list.unwrap().id) 41 lists_remove(config, id)
49} 42}
50 43
51///Changing the current lists version and updating it 44///Changing the current lists version and updating it
52/// 45///
53/// #Arguments 46/// #Arguments
54/// 47///
55/// * `config` - The current config 48/// * `config` - The current config
56/// * `args` - All args, to extract the new version 49/// * `args` - All args, to extract the new version
57async fn version(config: Cfg, input: Input) -> MLE<()> { 50pub async fn list_version(
58 println!("Change version for list {} to minecraft version: {}", input.clone().list.unwrap().id, input.clone().list_mcversion.unwrap()); 51 config: Cfg,
52 id: String,
53 mc_version: String,
54 download: bool,
55 delete: bool,
56) -> MLE<()> {
57 println!(
58 "Change version for list {} to minecraft version: {}",
59 id, mc_version
60 );
59 61
60 lists_version(config.clone(), input.clone().list.ok_or("").unwrap().id, input.clone().list_mcversion.ok_or("").unwrap())?; 62 lists_version(config.clone(), &id, &mc_version)?;
61
62 //Linebreak readability
63 println!("");
64 63
65 println!("Check for updates for new minecraft version in list {}", input.clone().list.unwrap().id); 64 println!(
66 cmd_update(config, vec![input.list.ok_or("").unwrap()], true, input.direct_download, input.delete_old).await 65 "\nCheck for updates for new minecraft version in list {}",
66 id
67 );
68 let list = lists_get(config.clone(), id)?;
69 update(config, vec![list], true, download, delete).await
67} 70}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 0d5bd00..1c7c012 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -1,13 +1,13 @@
1pub mod modification;
2pub mod list;
3pub mod update;
4pub mod setup;
5pub mod download; 1pub mod download;
6pub mod io; 2pub mod io;
3pub mod list;
4pub mod modification;
5pub mod setup;
6pub mod update;
7 7
8pub use modification::*;
9pub use list::*;
10pub use update::*;
11pub use setup::*;
12pub use download::*; 8pub use download::*;
13pub use io::*; 9pub use io::*;
10pub use list::*;
11pub use modification::*;
12pub use setup::*;
13pub use update::*;
diff --git a/src/commands/modification.rs b/src/commands/modification.rs
index 31e50af..ffc4e10 100644
--- a/src/commands/modification.rs
+++ b/src/commands/modification.rs
@@ -1,27 +1,19 @@
1use crate::{modrinth::{versions, extract_current_version, Version, projects, get_raw_versions, project}, config::Cfg, db::{mods_insert, userlist_remove, mods_get_id, userlist_insert, userlist_get_all_ids, userlist_get_current_version, lists_get_all_ids, mods_remove}, input::{Input, ModOptions}, files::{delete_version, download_versions}, List, error::{MLE, ErrorType, MLError}}; 1use crate::{
2 config::Cfg,
3 db::{
4 lists_get_all_ids, mods_get_id, mods_insert, mods_remove, userlist_get_all_ids,
5 userlist_get_current_version, userlist_insert, userlist_remove,
6 },
7 error::{ErrorType, MLError, MLE},
8 files::{delete_version, download_versions},
9 modrinth::{extract_current_version, get_raw_versions, project, projects, versions, Version},
10 List,
11};
2 12
3#[derive(Debug, Clone, PartialEq, Eq)] 13#[derive(Debug, Clone, PartialEq, Eq)]
4pub enum IDSelector { 14pub enum IDSelector {
5 ModificationID(String), 15 ModificationID(String),
6 VersionID(String) 16 VersionID(String),
7}
8
9pub async fn modification(config: Cfg, input: Input) -> MLE<()> {
10 match input.clone().mod_options.ok_or("").unwrap() {
11 ModOptions::Add => {
12 add(config, input).await
13 },
14 ModOptions::Remove => {
15 remove(config, input)
16 },
17 }
18}
19
20async fn add(config: Cfg, input: Input) -> MLE<()> {
21
22 mods_add(config, vec![input.mod_id.unwrap()], input.list.unwrap(), input.direct_download, input.set_version).await?;
23
24 Ok(())
25} 17}
26 18
27#[derive(Debug, Clone)] 19#[derive(Debug, Clone)]
@@ -34,10 +26,16 @@ pub struct ProjectInfo {
34 pub download_link: String, 26 pub download_link: String,
35} 27}
36 28
37pub async fn mods_add(config: Cfg, ids: Vec<IDSelector>, list: List, direct_download: bool, set_version: bool) -> MLE<()> { 29pub async fn mod_add(
30 config: Cfg,
31 ids: Vec<IDSelector>,
32 list: List,
33 direct_download: bool,
34 set_version: bool,
35) -> MLE<()> {
38 println!("Add mods to {}", list.id); 36 println!("Add mods to {}", list.id);
39 println!(" └Add mods:"); 37 println!(" └Add mods:");
40 38
41 let mut mod_ids: Vec<String> = Vec::new(); 39 let mut mod_ids: Vec<String> = Vec::new();
42 let mut ver_ids: Vec<String> = Vec::new(); 40 let mut ver_ids: Vec<String> = Vec::new();
43 41
@@ -50,11 +48,17 @@ pub async fn mods_add(config: Cfg, ids: Vec<IDSelector>, list: List, direct_down
50 } 48 }
51 49
52 let mut projectinfo: Vec<ProjectInfo> = Vec::new(); 50 let mut projectinfo: Vec<ProjectInfo> = Vec::new();
53 if !mod_ids.is_empty() { projectinfo.append(&mut get_mod_infos(config.clone(), mod_ids, list.clone()).await?) }; 51 if !mod_ids.is_empty() {
54 if !ver_ids.is_empty() { projectinfo.append(&mut get_ver_info(config.clone(), ver_ids).await?) }; 52 projectinfo.append(&mut get_mod_infos(config.clone(), mod_ids, list.clone()).await?)
53 };
54 if !ver_ids.is_empty() {
55 projectinfo.append(&mut get_ver_info(config.clone(), ver_ids).await?)
56 };
57
58 if projectinfo.is_empty() {
59 return Err(MLError::new(ErrorType::ArgumentError, "NO_IDS?"));
60 };
55 61
56 if projectinfo.is_empty() { return Err(MLError::new(ErrorType::ArgumentError, "NO_IDS?")) };
57
58 let mut downloadstack: Vec<Version> = Vec::new(); 62 let mut downloadstack: Vec<Version> = Vec::new();
59 63
60 //Adding each mod to the lists and downloadstack 64 //Adding each mod to the lists and downloadstack
@@ -63,29 +67,59 @@ pub async fn mods_add(config: Cfg, ids: Vec<IDSelector>, list: List, direct_down
63 } else { 67 } else {
64 println!(" └Insert mods in list {} and save infos", list.id); 68 println!(" └Insert mods in list {} and save infos", list.id);
65 } 69 }
66 70
67 for project in projectinfo { 71 for project in projectinfo {
68 let current_version_id = if project.current_version.is_none() { String::from("NONE") } else { project.current_version.clone().unwrap().id }; 72 let current_version_id = if project.current_version.is_none() {
69 match userlist_insert(config.clone(), &list.id, &project.mod_id, &current_version_id, project.clone().applicable_versions, &project.download_link, set_version) { 73 String::from("NONE")
74 } else {
75 project.current_version.clone().unwrap().id
76 };
77 match userlist_insert(
78 config.clone(),
79 &list.id,
80 &project.mod_id,
81 &current_version_id,
82 project.clone().applicable_versions,
83 &project.download_link,
84 set_version,
85 ) {
70 Err(e) => { 86 Err(e) => {
71 let expected_err = format!("SQL: UNIQUE constraint failed: {}.mod_id", list.id); 87 let expected_err = format!("SQL: UNIQUE constraint failed: {}.mod_id", list.id);
72 if e.to_string() == expected_err { Err(MLError::new(ErrorType::ModError, "MOD_ALREADY_ON_SELECTED_LIST")) } else { Err(e) } 88 if e.to_string() == expected_err {
73 }, 89 Err(MLError::new(
74 Ok(..) => { Ok(..) }, 90 ErrorType::ModError,
91 "MOD_ALREADY_ON_SELECTED_LIST",
92 ))
93 } else {
94 Err(e)
95 }
96 }
97 Ok(..) => Ok(..),
75 }?; 98 }?;
76 99
77 match mods_insert(config.clone(), &project.mod_id, &project.slug, &project.title) { 100 match mods_insert(
101 config.clone(),
102 &project.mod_id,
103 &project.slug,
104 &project.title,
105 ) {
78 Err(e) => { 106 Err(e) => {
79 if e.to_string() == "SQL: UNIQUE constraint failed: mods.id" { Ok(..) } else { Err(e) } 107 if e.to_string() == "SQL: UNIQUE constraint failed: mods.id" {
80 }, 108 Ok(..)
109 } else {
110 Err(e)
111 }
112 }
81 Ok(..) => Ok(..), 113 Ok(..) => Ok(..),
82 }?; 114 }?;
83 115
84 if project.current_version.is_some() { downloadstack.push(project.current_version.unwrap()) }; 116 if project.current_version.is_some() {
117 downloadstack.push(project.current_version.unwrap())
118 };
85 } 119 }
86 120
87 //Download all the added mods 121 //Download all the added mods
88 if direct_download { 122 if direct_download {
89 download_versions(list.clone(), config.clone(), downloadstack).await?; 123 download_versions(list.clone(), config.clone(), downloadstack).await?;
90 }; 124 };
91 125
@@ -104,7 +138,12 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<String>, list: List) -> MLE<Vec
104 for project in m_projects { 138 for project in m_projects {
105 println!("\t└{}", project.title); 139 println!("\t└{}", project.title);
106 println!("\t └Get versions"); 140 println!("\t └Get versions");
107 let available_versions = versions(&config.apis.modrinth, String::from(&project.id), list.clone()).await; 141 let available_versions = versions(
142 &config.apis.modrinth,
143 String::from(&project.id),
144 list.clone(),
145 )
146 .await;
108 147
109 let mut available_versions_vec: Vec<String> = Vec::new(); 148 let mut available_versions_vec: Vec<String> = Vec::new();
110 let current_version: Option<Version>; 149 let current_version: Option<Version>;
@@ -113,36 +152,63 @@ async fn get_mod_infos(config: Cfg, mod_ids: Vec<String>, list: List) -> MLE<Vec
113 let current_id = extract_current_version(available_versions.clone())?; 152 let current_id = extract_current_version(available_versions.clone())?;
114 println!("\t └Current version: {}", current_id); 153 println!("\t └Current version: {}", current_id);
115 154
116 current_version = Some(available_versions.clone().into_iter().find(|v| v.id == current_id).unwrap()); 155 current_version = Some(
156 available_versions
157 .clone()
158 .into_iter()
159 .find(|v| v.id == current_id)
160 .unwrap(),
161 );
117 162
118 file = current_version.clone().ok_or("").unwrap().files.into_iter().find(|f| f.primary).unwrap().url; 163 file = current_version
164 .clone()
165 .ok_or("")
166 .unwrap()
167 .files
168 .into_iter()
169 .find(|f| f.primary)
170 .unwrap()
171 .url;
119 for ver in available_versions { 172 for ver in available_versions {
120 available_versions_vec.push(ver.id); 173 available_versions_vec.push(ver.id);
121 }; 174 }
122
123 projectinfo.push(ProjectInfo { mod_id: project.id, slug: project.slug, title: project.title, current_version, applicable_versions: available_versions_vec, download_link: file })
124 175
176 projectinfo.push(ProjectInfo {
177 mod_id: project.id,
178 slug: project.slug,
179 title: project.title,
180 current_version,
181 applicable_versions: available_versions_vec,
182 download_link: file,
183 })
125 } else { 184 } else {
126 println!("\t └There's currently no mod version for your specified target"); 185 println!("\t └There's currently no mod version for your specified target");
127 current_version = None; 186 current_version = None;
128 file = String::from("NONE"); 187 file = String::from("NONE");
129 available_versions_vec.push(String::from("NONE")); 188 available_versions_vec.push(String::from("NONE"));
130 projectinfo.push(ProjectInfo { mod_id: project.id, slug: project.slug, title: project.title, current_version, applicable_versions: available_versions_vec, download_link: file }) 189 projectinfo.push(ProjectInfo {
190 mod_id: project.id,
191 slug: project.slug,
192 title: project.title,
193 current_version,
194 applicable_versions: available_versions_vec,
195 download_link: file,
196 })
131 } 197 }
132 }; 198 }
133 199
134 Ok(projectinfo) 200 Ok(projectinfo)
135} 201}
136 202
137async fn get_ver_info(config: Cfg, ver_ids: Vec<String>) -> MLE<Vec<ProjectInfo>> { 203async fn get_ver_info(config: Cfg, ver_ids: Vec<String>) -> MLE<Vec<ProjectInfo>> {
138 let mut projectinfo: Vec<ProjectInfo> = Vec::new(); 204 let mut projectinfo: Vec<ProjectInfo> = Vec::new();
139 205
140 //Get required information from ver_ids 206 //Get required information from ver_ids
141 let mut v_versions = get_raw_versions(&config.apis.modrinth, ver_ids).await; 207 let mut v_versions = get_raw_versions(&config.apis.modrinth, ver_ids).await;
142 let mut v_mod_ids: Vec<String> = Vec::new(); 208 let mut v_mod_ids: Vec<String> = Vec::new();
143 for ver in v_versions.clone() { 209 for ver in v_versions.clone() {
144 v_mod_ids.push(ver.project_id); 210 v_mod_ids.push(ver.project_id);
145 }; 211 }
146 let mut v_projects = projects(&config.apis.modrinth, v_mod_ids).await; 212 let mut v_projects = projects(&config.apis.modrinth, v_mod_ids).await;
147 v_versions.sort_by(|a, b| a.project_id.cmp(&b.project_id)); 213 v_versions.sort_by(|a, b| a.project_id.cmp(&b.project_id));
148 v_projects.sort_by(|a, b| a.id.cmp(&b.id)); 214 v_projects.sort_by(|a, b| a.id.cmp(&b.id));
@@ -150,35 +216,54 @@ async fn get_ver_info(config: Cfg, ver_ids: Vec<String>) -> MLE<Vec<ProjectInfo>
150 for (i, project) in v_projects.into_iter().enumerate() { 216 for (i, project) in v_projects.into_iter().enumerate() {
151 let version = &v_versions[i]; 217 let version = &v_versions[i];
152 println!("\t└{}({})", project.title, version.id); 218 println!("\t└{}({})", project.title, version.id);
153 let file = version.clone().files.into_iter().find(|f| f.primary).unwrap().url; 219 let file = version
154 projectinfo.push(ProjectInfo { mod_id: project.id, slug: project.slug, title: project.title, current_version: Some(version.clone()), applicable_versions: vec![String::from(&version.id)], download_link: file }) 220 .clone()
155 }; 221 .files
222 .into_iter()
223 .find(|f| f.primary)
224 .unwrap()
225 .url;
226 projectinfo.push(ProjectInfo {
227 mod_id: project.id,
228 slug: project.slug,
229 title: project.title,
230 current_version: Some(version.clone()),
231 applicable_versions: vec![String::from(&version.id)],
232 download_link: file,
233 })
234 }
156 Ok(projectinfo) 235 Ok(projectinfo)
157} 236}
158 237
159fn remove(config: Cfg, input: Input) -> MLE<()> { 238/// Remove mod from a list
160 239/// # Arguments
161 let id = match input.clone().mod_id.unwrap() { 240///
162 IDSelector::ModificationID(id) => id, 241/// * `config` - config struct
163 IDSelector::VersionID(..) => return Err(MLError::new(ErrorType::ArgumentError, "NO_MOD_ID")), 242/// * `id` - name, slug or id of the mod
164 }; 243/// * `list` - List struct
165 244pub fn mod_remove(config: Cfg, id: &str, list: List) -> MLE<()> {
166 let mod_id = mods_get_id(&config.data, &id)?; 245 let mod_id = mods_get_id(&config.data, id)?;
167 246
168 let version = userlist_get_current_version(config.clone(), input.clone().list.unwrap().id, String::from(&mod_id))?; 247 let version = userlist_get_current_version(config.clone(), &list.id, &mod_id)?;
169 248
170 userlist_remove(config.clone(), input.clone().list.unwrap().id, String::from(&mod_id))?; 249 userlist_remove(config.clone(), &list.id, &mod_id)?;
171 delete_version(input.list.unwrap(), version)?; 250 delete_version(list, version)?;
172 251
173 let list_ids = lists_get_all_ids(config.clone())?; 252 let list_ids = lists_get_all_ids(config.clone())?;
174 253
254 // Remove mod from main list if not used elsewhere
175 let mut mod_used = false; 255 let mut mod_used = false;
176 for id in list_ids { 256 for id in list_ids {
177 let mods = userlist_get_all_ids(config.clone(), id)?; 257 let mods = userlist_get_all_ids(config.clone(), id)?;
178 if mods.contains(&mod_id) { mod_used = true; break; }; 258 if mods.contains(&mod_id) {
179 }; 259 mod_used = true;
260 break;
261 };
262 }
180 263
181 if !mod_used { mods_remove(config, mod_id)?; }; 264 if !mod_used {
265 mods_remove(config, mod_id)?;
266 };
182 267
183 Ok(()) 268 Ok(())
184} 269}
diff --git a/src/commands/setup.rs b/src/commands/setup.rs
index 0161bd7..40e8c0a 100644
--- a/src/commands/setup.rs
+++ b/src/commands/setup.rs
@@ -1,14 +1,14 @@
1use std::{fs::File, path::Path}; 1use std::{fs::File, path::Path};
2 2
3use crate::{config::Cfg, db::db_setup, error::MLE, devdir}; 3use crate::{config::Cfg, db::db_setup, devdir, error::MLE};
4 4
5pub async fn setup(config: Cfg) -> MLE<()> { 5pub async fn setup(config: Cfg) -> MLE<()> {
6 let db_file = devdir(format!("{}/data.db", config.data).as_str()); 6 let db_file = devdir(format!("{}/data.db", config.data).as_str());
7 7
8 if !Path::new(&db_file).exists() { 8 if !Path::new(&db_file).exists() {
9 create(config, db_file)?; 9 create(config, db_file)?;
10 } 10 }
11 11
12 /* 12 /*
13 match s_config_get_version(config.clone()) { 13 match s_config_get_version(config.clone()) {
14 Ok(ver) => { 14 Ok(ver) => {
@@ -21,12 +21,11 @@ pub async fn setup(config: Cfg) -> MLE<()> {
21 Err(..) => to_02(config).await? 21 Err(..) => to_02(config).await?
22 }; 22 };
23 */ 23 */
24 24
25 Ok(()) 25 Ok(())
26} 26}
27 27
28fn create(config: Cfg, db_file: String) -> MLE<()> { 28fn create(config: Cfg, db_file: String) -> MLE<()> {
29
30 println!("Create database"); 29 println!("Create database");
31 30
32 File::create(db_file)?; 31 File::create(db_file)?;
@@ -44,7 +43,7 @@ fn create(config: Cfg, db_file: String) -> MLE<()> {
44// let full_list = lists_get(config.clone(), String::from(&list))?; 43// let full_list = lists_get(config.clone(), String::from(&list))?;
45// 44//
46// let versions = userlist_get_all_current_version_ids(config.clone(), full_list.clone().id)?; 45// let versions = userlist_get_all_current_version_ids(config.clone(), full_list.clone().id)?;
47// 46//
48// let raw_versions = get_raw_versions(String::from(&config.apis.modrinth), versions).await; 47// let raw_versions = get_raw_versions(String::from(&config.apis.modrinth), versions).await;
49// 48//
50// for ver in raw_versions { 49// for ver in raw_versions {
@@ -69,4 +68,3 @@ fn create(config: Cfg, db_file: String) -> MLE<()> {
69// } 68// }
70// s_config_update_version(config, String::from("0.4")) 69// s_config_update_version(config, String::from("0.4"))
71//} 70//}
72
diff --git a/src/commands/update.rs b/src/commands/update.rs
index 75bee39..3d9578b 100644
--- a/src/commands/update.rs
+++ b/src/commands/update.rs
@@ -1,29 +1,30 @@
1use crate::{config::Cfg, modrinth::{versions, extract_current_version, Version}, get_current_list, db::{userlist_get_all_ids, userlist_get_applicable_versions, userlist_change_versions, lists_get_all_ids, lists_get, userlist_get_current_version, userlist_get_set_version, mods_get_info}, List, input::Input, files::{delete_version, download_versions, disable_version, clean_list_dir}, error::{MLE, MLError, ErrorType}}; 1use crate::{
2 2 config::Cfg,
3pub async fn update(config: Cfg, input: Input) -> MLE<()> { 3 db::{
4 let mut liststack: Vec<List> = vec![]; 4 mods_get_info, userlist_change_versions, userlist_get_all_ids,
5 if input.all_lists { 5 userlist_get_applicable_versions, userlist_get_current_version, userlist_get_set_version,
6 let list_ids = lists_get_all_ids(config.clone())?; 6 },
7 for id in list_ids { 7 error::{ErrorType, MLError, MLE},
8 liststack.push(lists_get(config.clone(), id)?); 8 files::{clean_list_dir, delete_version, disable_version, download_versions},
9 } 9 modrinth::{extract_current_version, versions, Version},
10 } else { 10 List,
11 let current = get_current_list(config.clone())?; 11};
12 println!("Update list {}:", current.id); 12
13 liststack.push(current) 13pub async fn update(
14 } 14 config: Cfg,
15 cmd_update(config, liststack, input.clean, input.direct_download, input.delete_old).await 15 liststack: Vec<List>,
16} 16 clean: bool,
17 17 direct_download: bool,
18pub async fn cmd_update(config: Cfg, liststack: Vec<List>, clean: bool, direct_download: bool, delete_old: bool) -> MLE<()> { 18 delete_old: bool,
19) -> MLE<()> {
19 for current_list in liststack { 20 for current_list in liststack {
20 let mods = userlist_get_all_ids(config.clone(), current_list.clone().id)?; 21 let mods = userlist_get_all_ids(config.clone(), current_list.clone().id)?;
21 22
22 let mut current_versions: Vec<(String, String)> = vec![]; 23 let mut current_versions: Vec<(String, String)> = vec![];
23 24
24 println!(" └Update mods:"); 25 println!(" └Update mods:");
25 let mut updatestack: Vec<Version> = vec![]; 26 let mut updatestack: Vec<Version> = vec![];
26 27
27 for id in mods { 28 for id in mods {
28 let info = mods_get_info(config.clone(), &id)?; 29 let info = mods_get_info(config.clone(), &id)?;
29 println!("\t└{}", info.title); 30 println!("\t└{}", info.title);
@@ -34,27 +35,39 @@ pub async fn cmd_update(config: Cfg, liststack: Vec<List>, clean: bool, direct_d
34 } 35 }
35 36
36 //Getting current installed version for disable or delete 37 //Getting current installed version for disable or delete
37 let disable_version = userlist_get_current_version(config.clone(), String::from(&current_list.id), String::from(&id))?; 38 let disable_version =
39 userlist_get_current_version(config.clone(), &current_list.id, &id)?;
38 40
39 updatestack.push( 41 updatestack.push(
40 match specific_update(config.clone(), clean, current_list.clone(), String::from(&id)).await { 42 match specific_update(
43 config.clone(),
44 clean,
45 current_list.clone(),
46 String::from(&id),
47 )
48 .await
49 {
41 Ok(ver) => { 50 Ok(ver) => {
42 current_versions.push((disable_version, id)); 51 current_versions.push((disable_version, id));
43 ver 52 ver
44 }, 53 }
45 Err(e) => { 54 Err(e) => {
46 if e.to_string() == "Mod: NO_UPDATE_AVAILABLE" { 55 if e.to_string() == "Mod: NO_UPDATE_AVAILABLE" {
47 println!("\t └No new version found for the specified minecraft version"); 56 println!(
57 "\t └No new version found for the specified minecraft version"
58 );
48 } else { 59 } else {
49 return Err(e); 60 return Err(e);
50 }; 61 };
51 continue; 62 continue;
52 } 63 }
53 } 64 },
54 ) 65 )
55 }; 66 }
56 67
57 if clean { clean_list_dir(&current_list)?; }; 68 if clean {
69 clean_list_dir(&current_list)?;
70 };
58 71
59 if direct_download && !updatestack.is_empty() { 72 if direct_download && !updatestack.is_empty() {
60 download_versions(current_list.clone(), config.clone(), updatestack).await?; 73 download_versions(current_list.clone(), config.clone(), updatestack).await?;
@@ -65,7 +78,7 @@ pub async fn cmd_update(config: Cfg, liststack: Vec<List>, clean: bool, direct_d
65 if delete_old { 78 if delete_old {
66 println!("\t └Delete version {}", ver.0); 79 println!("\t └Delete version {}", ver.0);
67 delete_version(current_list.clone(), ver.0)?; 80 delete_version(current_list.clone(), ver.0)?;
68 } else if ver.0 != "NONE" { 81 } else if ver.0 != "NONE" {
69 println!("\t └Disable version {}", ver.0); 82 println!("\t └Disable version {}", ver.0);
70 disable_version(config.clone(), current_list.clone(), ver.0, ver.1)?; 83 disable_version(config.clone(), current_list.clone(), ver.0, ver.1)?;
71 }; 84 };
@@ -78,10 +91,11 @@ pub async fn cmd_update(config: Cfg, liststack: Vec<List>, clean: bool, direct_d
78} 91}
79 92
80async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> MLE<Version> { 93async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> MLE<Version> {
81 let applicable_versions = versions(&config.apis.modrinth, String::from(&id), list.clone()).await; 94 let applicable_versions =
82 95 versions(&config.apis.modrinth, String::from(&id), list.clone()).await;
96
83 let mut versions: Vec<String> = vec![]; 97 let mut versions: Vec<String> = vec![];
84 98
85 if !applicable_versions.is_empty() { 99 if !applicable_versions.is_empty() {
86 for ver in &applicable_versions { 100 for ver in &applicable_versions {
87 versions.push(String::from(&ver.id)); 101 versions.push(String::from(&ver.id));
@@ -92,8 +106,14 @@ async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> ML
92 106
93 let mut current: Vec<Version> = vec![]; 107 let mut current: Vec<Version> = vec![];
94 //TODO Split clean and no match 108 //TODO Split clean and no match
95 if clean || (versions.join("|") != userlist_get_applicable_versions(config.clone(), String::from(&list.id), String::from(&id))?) { 109 if clean
96 110 || (versions.join("|")
111 != userlist_get_applicable_versions(
112 config.clone(),
113 String::from(&list.id),
114 String::from(&id),
115 )?)
116 {
97 let current_str = extract_current_version(applicable_versions.clone())?; 117 let current_str = extract_current_version(applicable_versions.clone())?;
98 118
99 if clean { 119 if clean {
@@ -104,34 +124,54 @@ async fn specific_update(config: Cfg, clean: bool, list: List, id: String) -> ML
104 }; 124 };
105 125
106 //get new versions 126 //get new versions
107 let current_ver = match applicable_versions.into_iter().find(|ver| ver.id == current_str).ok_or("!no current version in applicable_versions") { 127 let current_ver = match applicable_versions
128 .into_iter()
129 .find(|ver| ver.id == current_str)
130 .ok_or("!no current version in applicable_versions")
131 {
108 Ok(v) => Ok(v), 132 Ok(v) => Ok(v),
109 Err(e) => Err(MLError::new(ErrorType::Other, e)), 133 Err(e) => Err(MLError::new(ErrorType::Other, e)),
110 }?; 134 }?;
111 current.push(current_ver.clone()); 135 current.push(current_ver.clone());
112 136
113 let link = match current_ver.files.into_iter().find(|f| f.primary).ok_or("!no primary in links") { 137 //TODO implement version selection if no primary
138 let link = match current_ver
139 .files
140 .into_iter()
141 .find(|f| f.primary)
142 .ok_or("!no primary in links")
143 {
114 Ok(p) => Ok(p), 144 Ok(p) => Ok(p),
115 Err(e) => Err(MLError::new(ErrorType::Other, e)), 145 Err(e) => Err(MLError::new(ErrorType::Other, e)),
116 }?.url; 146 }?
147 .url;
117 userlist_change_versions(config, list.id, current_str, versions.join("|"), link, id)?; 148 userlist_change_versions(config, list.id, current_str, versions.join("|"), link, id)?;
118 } 149 }
119 150
120 if current.is_empty() { return Err(MLError::new(ErrorType::ModError, "NO_UPDATE_AVAILABLE")) }; 151 if current.is_empty() {
121 152 return Err(MLError::new(ErrorType::ModError, "NO_UPDATE_AVAILABLE"));
153 };
154
122 //println!(" └✔️"); 155 //println!(" └✔️");
123 Ok(current[0].clone()) 156 Ok(current[0].clone())
124} 157}
125 158
126#[tokio::test] 159#[tokio::test]
127async fn download_updates_test() { 160async fn download_updates_test() {
161 use crate::{
162 modrinth::{Hash, Version, VersionFile, VersionType},
163 List, Modloader,
164 };
128 165
129 use crate::{modrinth::{Version, VersionFile, Hash, VersionType}, Modloader, List};
130
131 let config = Cfg::init("modlist.toml").unwrap(); 166 let config = Cfg::init("modlist.toml").unwrap();
132 let current_list = List { id: String::from("..."), mc_version: String::from("..."), modloader: Modloader::Fabric, download_folder: String::from("./dev/tests/dl") }; 167 let current_list = List {
133 168 id: String::from("..."),
134 let versions = vec![Version { 169 mc_version: String::from("..."),
170 modloader: Modloader::Fabric,
171 download_folder: String::from("./dev/tests/dl"),
172 };
173
174 let versions = vec![Version {
135 id: "dEqtGnT9".to_string(), 175 id: "dEqtGnT9".to_string(),
136 project_id: "kYuIpRLv".to_string(), 176 project_id: "kYuIpRLv".to_string(),
137 author_id: "Qnt13hO8".to_string(), 177 author_id: "Qnt13hO8".to_string(),
@@ -161,5 +201,7 @@ async fn download_updates_test() {
161 "fabric".to_string() 201 "fabric".to_string()
162 ] 202 ]
163 }]; 203 }];
164 assert!(download_versions(current_list, config, versions).await.is_ok()) 204 assert!(download_versions(current_list, config, versions)
205 .await
206 .is_ok())
165} 207}