summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorFxQnLr <[email protected]>2023-01-29 14:14:43 +0100
committerGitHub <[email protected]>2023-01-29 14:14:43 +0100
commit35d9e091b9b6f68e51a79c1a10e0a95cd2ae974e (patch)
tree68a63f39a5bf6241e4ca9499d03ea148ec9737c4 /src
parent8f3c77986b36d7653fd44e16ef986f0ad284e0c4 (diff)
parentd7d0c904bff665ab5c8355f2381a0628ebbf7a30 (diff)
downloadmodlist-35d9e091b9b6f68e51a79c1a10e0a95cd2ae974e.tar
modlist-35d9e091b9b6f68e51a79c1a10e0a95cd2ae974e.tar.gz
modlist-35d9e091b9b6f68e51a79c1a10e0a95cd2ae974e.zip
Merge pull request #3 from FxQnLr/new_input
New input, fuck it
Diffstat (limited to 'src')
-rw-r--r--src/apis/modrinth.rs16
-rw-r--r--src/commands/download.rs22
-rw-r--r--src/commands/io.rs30
-rw-r--r--src/commands/list.rs93
-rw-r--r--src/commands/mod.rs4
-rw-r--r--src/commands/modification.rs49
-rw-r--r--src/commands/setup.rs2
-rw-r--r--src/commands/update.rs87
-rw-r--r--src/config.rs1
-rw-r--r--src/db.rs37
-rw-r--r--src/error.rs14
-rw-r--r--src/files.rs35
-rw-r--r--src/input.rs435
-rw-r--r--src/main.rs52
14 files changed, 540 insertions, 337 deletions
diff --git a/src/apis/modrinth.rs b/src/apis/modrinth.rs
index 78073e6..36ab5df 100644
--- a/src/apis/modrinth.rs
+++ b/src/apis/modrinth.rs
@@ -1,9 +1,8 @@
1use std::io::{Error, ErrorKind};
2use chrono::{DateTime, FixedOffset}; 1use chrono::{DateTime, FixedOffset};
3use reqwest::Client; 2use reqwest::Client;
4use serde::Deserialize; 3use serde::Deserialize;
5 4
6use crate::{Modloader, List}; 5use crate::{Modloader, List, error::{MLE, MLError, ErrorType}};
7 6
8#[derive(Debug, Deserialize, Clone)] 7#[derive(Debug, Deserialize, Clone)]
9pub struct Project { 8pub struct Project {
@@ -142,7 +141,7 @@ pub async fn project(api: String, name: &str) -> Project {
142} 141}
143 142
144pub async fn projects(api: String, ids: Vec<String>) -> Vec<Project> { 143pub async fn projects(api: String, ids: Vec<String>) -> Vec<Project> {
145 println!("Getting versions for all mods from modrinth"); 144 println!("\tGet versions from modrinth\n");
146 let all = ids.join(r#"",""#); 145 let all = ids.join(r#"",""#);
147 let url = format!(r#"projects?ids=["{}"]"#, all); 146 let url = format!(r#"projects?ids=["{}"]"#, all);
148 147
@@ -177,9 +176,9 @@ pub async fn get_raw_versions(api: String, versions: Vec<String>) -> Vec<Version
177 serde_json::from_slice(&data).unwrap() 176 serde_json::from_slice(&data).unwrap()
178} 177}
179 178
180pub fn extract_current_version(versions: Vec<Version>) -> Result<String, Box<dyn std::error::Error>> { 179pub fn extract_current_version(versions: Vec<Version>) -> MLE<String> {
181 match versions.len() { 180 match versions.len() {
182 0 => Err(Box::new(Error::new(ErrorKind::NotFound, "NO_VERSIONS_AVAILABLE"))), 181 0 => Err(MLError::new(ErrorType::ModError, "NO_VERSIONS_AVAILABLE")),
183 1.. => { 182 1.. => {
184 let mut times: Vec<(String, DateTime<FixedOffset>)> = vec![]; 183 let mut times: Vec<(String, DateTime<FixedOffset>)> = vec![];
185 for ver in versions { 184 for ver in versions {
@@ -188,7 +187,7 @@ pub fn extract_current_version(versions: Vec<Version>) -> Result<String, Box<dyn
188 } 187 }
189 times.sort_by_key(|t| t.1); 188 times.sort_by_key(|t| t.1);
190 times.reverse(); 189 times.reverse();
191 println!("Current Version: {}", times[0].0); 190 println!("\t └New current version: {}", times[0].0);
192 Ok(times[0].0.to_string()) 191 Ok(times[0].0.to_string())
193 }, 192 },
194 _ => panic!("available_versions should never be negative"), 193 _ => panic!("available_versions should never be negative"),
@@ -198,6 +197,7 @@ pub fn extract_current_version(versions: Vec<Version>) -> Result<String, Box<dyn
198pub enum MCVersionType { 197pub enum MCVersionType {
199 Release, 198 Release,
200 Latest, 199 Latest,
200 Specific,
201} 201}
202 202
203#[derive(Debug, Deserialize)] 203#[derive(Debug, Deserialize)]
@@ -220,6 +220,10 @@ pub async fn get_minecraft_version(api: String, version: MCVersionType) -> Strin
220 &mc_versions[i] 220 &mc_versions[i]
221 }, 221 },
222 MCVersionType::Latest => &mc_versions[0], 222 MCVersionType::Latest => &mc_versions[0],
223 MCVersionType::Specific => {
224 println!("Not inplemented");
225 &mc_versions[0]
226 }
223 }; 227 };
224 String::from(&ver.version) 228 String::from(&ver.version)
225} 229}
diff --git a/src/commands/download.rs b/src/commands/download.rs
index b958bf3..7748d15 100644
--- a/src/commands/download.rs
+++ b/src/commands/download.rs
@@ -1,7 +1,7 @@
1use crate::{files::{get_downloaded_versions, download_versions, delete_version, disable_version}, db::{userlist_get_all_current_versions_with_mods, lists_get_all_ids, lists_get}, modrinth::get_raw_versions}; 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}};
2use crate::{List, get_current_list, config::Cfg, input::Input}; 2use crate::{List, get_current_list, config::Cfg, input::Input};
3 3
4pub async fn download(config: Cfg, input: Input) -> Result<(), Box<dyn std::error::Error>> { 4pub async fn download(config: Cfg, input: Input) -> MLE<()> {
5 5
6 let mut liststack: Vec<List> = vec![]; 6 let mut liststack: Vec<List> = vec![];
7 if input.all_lists { 7 if input.all_lists {
@@ -18,7 +18,10 @@ pub async fn download(config: Cfg, input: Input) -> Result<(), Box<dyn std::erro
18 for current_list in liststack { 18 for current_list in liststack {
19 let downloaded_versions = get_downloaded_versions(current_list.clone())?; 19 let downloaded_versions = get_downloaded_versions(current_list.clone())?;
20 println!("To download: {:#?}", downloaded_versions); 20 println!("To download: {:#?}", downloaded_versions);
21 let current_version_ids = userlist_get_all_current_versions_with_mods(config.clone(), String::from(&current_list.id))?; 21 let current_version_ids = match userlist_get_all_current_versions_with_mods(config.clone(), String::from(&current_list.id)) {
22 Ok(i) => Ok(i),
23 Err(e) => Err(MLError::new(ErrorType::DBError, e.to_string().as_str())),
24 }?;
22 25
23 let mut to_download: Vec<String> = vec![]; 26 let mut to_download: Vec<String> = vec![];
24 //(mod_id, version_id) 27 //(mod_id, version_id)
@@ -33,7 +36,7 @@ pub async fn download(config: Cfg, input: Input) -> Result<(), Box<dyn std::erro
33 if current_download.is_none() || input.clean { 36 if current_download.is_none() || input.clean {
34 to_download.push(current_version); 37 to_download.push(current_version);
35 } else { 38 } else {
36 let downloaded_version = current_download.ok_or("SOMETHING_HAS_REALLY_GONE_WRONG")?; 39 let downloaded_version = current_download.ok_or("SOMETHING_HAS_REALLY_GONE_WRONG").unwrap();
37 if &current_version != downloaded_version { 40 if &current_version != downloaded_version {
38 to_disable.push((mod_id.clone(), String::from(downloaded_version))); 41 to_disable.push((mod_id.clone(), String::from(downloaded_version)));
39 to_download.push(current_version); 42 to_download.push(current_version);
@@ -41,17 +44,10 @@ pub async fn download(config: Cfg, input: Input) -> Result<(), Box<dyn std::erro
41 } 44 }
42 } 45 }
43 46
44 if input.clean { 47 if input.clean { clean_list_dir(&current_list)? };
45 let dl_path = &current_list.download_folder;
46 println!("Cleaning {}", dl_path);
47 for entry in std::fs::read_dir(dl_path)? {
48 let entry = entry?;
49 std::fs::remove_file(entry.path())?;
50 }
51 }
52 48
53 if !to_download.is_empty() { 49 if !to_download.is_empty() {
54 download_versions(current_list.clone(), get_raw_versions(String::from(&config.apis.modrinth), to_download).await).await?; 50 download_versions(current_list.clone(), config.clone(), get_raw_versions(String::from(&config.apis.modrinth), to_download).await).await?;
55 } else { 51 } else {
56 println!("There are no new versions to download"); 52 println!("There are no new versions to download");
57 } 53 }
diff --git a/src/commands/io.rs b/src/commands/io.rs
index 6c4a4d3..4835e3d 100644
--- a/src/commands/io.rs
+++ b/src/commands/io.rs
@@ -2,7 +2,7 @@ use std::fs::File;
2use std::io::prelude::*; 2use std::io::prelude::*;
3use serde::{Serialize, Deserialize}; 3use serde::{Serialize, Deserialize};
4 4
5use crate::{input::{Input, Subcmd}, db::{lists_get, userlist_get_all_ids, lists_get_all_ids, lists_insert}, config::Cfg, Modloader, mod_add, List, devdir}; 5use crate::{input::{Input, IoOptions}, db::{lists_get, userlist_get_all_ids, lists_get_all_ids, lists_insert}, config::Cfg, Modloader, /*mod_add,*/ List, devdir, error::MLE};
6 6
7#[derive(Debug, Serialize, Deserialize)] 7#[derive(Debug, Serialize, Deserialize)]
8struct Export { 8struct Export {
@@ -19,7 +19,7 @@ struct ExportList {
19} 19}
20 20
21impl ExportList { 21impl ExportList {
22 pub fn from(config: Cfg, list_id: String, download: bool) -> Result<Self, Box<dyn std::error::Error>> { 22 pub fn from(config: Cfg, list_id: String, download: bool) -> MLE<Self> {
23 23
24 let list = lists_get(config.clone(), String::from(&list_id))?; 24 let list = lists_get(config.clone(), String::from(&list_id))?;
25 25
@@ -32,26 +32,22 @@ impl ExportList {
32 } 32 }
33} 33}
34 34
35pub async fn io(config: Cfg, input: Input) -> Result<(), Box<dyn std::error::Error>> { 35pub async fn io(config: Cfg, input: Input) -> MLE<()> {
36 36
37 match input.subcommand.clone().ok_or("INVALID_INPUT")? { 37 match input.clone().io_options.unwrap() {
38 Subcmd::Export => { export(config, input)? }, 38 IoOptions::Export => { export(config, input)? },
39 Subcmd::Import => { import(config, input.args).await? }, 39 IoOptions::Import => { import(config, input).await? },
40 _ => { },
41 } 40 }
42 41
43 Ok(()) 42 Ok(())
44} 43}
45 44
46fn export(config: Cfg, input: Input) -> Result<(), Box<dyn std::error::Error>> { 45fn export(config: Cfg, input: Input) -> MLE<()> {
47 let mut list_ids: Vec<String> = vec![]; 46 let mut list_ids: Vec<String> = vec![];
48 if input.all_lists { 47 if input.all_lists {
49 list_ids = lists_get_all_ids(config.clone())?; 48 list_ids = lists_get_all_ids(config.clone())?;
50 } else { 49 } else {
51 let args = input.args.ok_or("NO_ARGS")?; 50 list_ids.push(lists_get(config.clone(), input.list.unwrap().id)?.id);
52 for arg in args {
53 list_ids.push(lists_get(config.clone(), arg)?.id);
54 }
55 } 51 }
56 let mut lists: Vec<ExportList> = vec![]; 52 let mut lists: Vec<ExportList> = vec![];
57 for list_id in list_ids { 53 for list_id in list_ids {
@@ -68,10 +64,10 @@ fn export(config: Cfg, input: Input) -> Result<(), Box<dyn std::error::Error>> {
68 Ok(()) 64 Ok(())
69} 65}
70 66
71async fn import(config: Cfg, args: Option<Vec<String>>) -> Result<(), Box<dyn std::error::Error>> { 67async fn import(config: Cfg, input: Input) -> MLE<()> {
72 68
73 let filestr: String = match args { 69 let filestr: String = match input.file {
74 Some(args) => String::from(&args[0]), 70 Some(args) => String::from(args),
75 None => String::from(devdir(dirs::home_dir().unwrap().join("mlexport.toml").into_os_string().into_string().unwrap().as_str())), 71 None => String::from(devdir(dirs::home_dir().unwrap().join("mlexport.toml").into_os_string().into_string().unwrap().as_str())),
76 }; 72 };
77 73
@@ -83,14 +79,14 @@ async fn import(config: Cfg, args: Option<Vec<String>>) -> Result<(), Box<dyn st
83 println!("{:#?}", export); 79 println!("{:#?}", export);
84 80
85 for exportlist in export.lists { 81 for exportlist in export.lists {
86 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")? }; 82 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() };
87 lists_insert(config.clone(), list.id.clone(), list.mc_version.clone(), list.modloader.clone(), String::from(&list.download_folder))?; 83 lists_insert(config.clone(), list.id.clone(), list.mc_version.clone(), list.modloader.clone(), String::from(&list.download_folder))?;
88 let mods: Vec<&str> = exportlist.mods.split("|").collect(); 84 let mods: Vec<&str> = exportlist.mods.split("|").collect();
89 let mut mod_ids = vec![]; 85 let mut mod_ids = vec![];
90 for mod_id in mods { 86 for mod_id in mods {
91 mod_ids.push(String::from(mod_id)); 87 mod_ids.push(String::from(mod_id));
92 }; 88 };
93 mod_add(config.clone(), mod_ids, list.clone(), false).await?; 89 //mod_add(config.clone(), mod_ids, list.clone(), false).await?;
94 } 90 }
95 Ok(()) 91 Ok(())
96} 92}
diff --git a/src/commands/list.rs b/src/commands/list.rs
index 3998cce..eaf6fa1 100644
--- a/src/commands/list.rs
+++ b/src/commands/list.rs
@@ -1,6 +1,4 @@
1use std::io::{Error, ErrorKind}; 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};
2
3use crate::{db::{lists_insert, lists_remove, config_change_current_list, lists_get_all_ids, config_get_current_list, lists_get, lists_version}, Modloader, config::Cfg, input::{Input, Subcmd}, cmd_update, error::{MLE, ErrorType, MLError}, modrinth::MCVersionType};
4 2
5#[derive(Debug, Clone, PartialEq, Eq)] 3#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct List { 4pub struct List {
@@ -10,32 +8,20 @@ pub struct List {
10 pub download_folder: String, 8 pub download_folder: String,
11} 9}
12 10
13pub async fn list(config: Cfg, input: Input) -> Result<(), Box<dyn std::error::Error>> { 11pub async fn list(config: Cfg, input: Input) -> MLE<()> {
14 12
15 match input.subcommand.ok_or("")? { 13 match input.clone().list_options.unwrap() {
16 Subcmd::Add => { 14 ListOptions::Add => {
17 match add(config, input.args.ok_or("")?) { 15 add(config, input)
18 Ok(..) => Ok(()),
19 Err(e) => Err(Box::new(e))
20 }
21 }, 16 },
22 Subcmd::Change => { 17 ListOptions::Change => {
23 change(config, input.args) 18 change(config, input)
24 }, 19 },
25 Subcmd::Remove => { 20 ListOptions::Remove => {
26 match remove(config, input.args.ok_or("")?) { 21 remove(config, input)
27 Ok(..) => Ok(()),
28 Err(e) => Err(Box::new(e))
29 }
30 }, 22 },
31 Subcmd::Version => { 23 ListOptions::Version => {
32 match version(config, Some(input.args.ok_or("NO_VERSION")?), Some(MCVersionType::Release)).await { 24 version(config, input).await
33 Ok(..) => Ok(()),
34 Err(e) => Err(Box::new(e))
35 }
36 }
37 _ => {
38 Err(Box::new(Error::new(ErrorKind::InvalidInput, "WRONG_SUBCOMMAND")))
39 } 25 }
40 } 26 }
41} 27}
@@ -45,42 +31,21 @@ pub fn get_current_list(config: Cfg) -> MLE<List> {
45 lists_get(config, id) 31 lists_get(config, id)
46} 32}
47 33
48fn add(config: Cfg, args: Vec<String>) -> MLE<()> { 34fn add(config: Cfg, input: Input) -> MLE<()> {
49 match args.len() { 35 let id = input.list_id.unwrap();
50 1 | 2 | 3 => Err(MLError::new(ErrorType::ArgumentCountError, "TOO_FEW_ARGUMENTS")), 36 let mc_version = input.list_mcversion.unwrap();
51 4 => { 37 let mod_loader = input.modloader.unwrap();
52 let id = String::from(&args[0]); 38 let download_folder = input.directory.unwrap();
53 let mc_version = String::from(&args[1]); 39 lists_insert(config, id, mc_version, mod_loader, download_folder)
54 let mod_loader = Modloader::from(&args[2])?;
55 let download_folder = String::from(&args[3]);
56 lists_insert(config, id, mc_version, mod_loader, download_folder)
57 },
58 5.. => Err(MLError::new(ErrorType::ArgumentCountError, "TOO_MANY_ARGUMENTS")),
59 _ => panic!("list arguments should never be zero or lower"),
60 }
61} 40}
62 41
63fn change(config: Cfg, args: Option<Vec<String>>) -> Result<(), Box<dyn std::error::Error>> { 42fn change(config: Cfg, input: Input) -> MLE<()> {
64 let lists = lists_get_all_ids(config.clone())?; 43 println!("Change default list to: {}", input.clone().list.unwrap().id);
65 if args.is_none() { println!("Currently selected list: {}", get_current_list(config)?.id); return Ok(()) }; 44 config_change_current_list(config, input.list.unwrap().id)
66 let argsvec = args.ok_or("BAH")?;
67 match argsvec.len() {
68 1 => {
69 let list = String::from(&argsvec[0]);
70 if !lists.contains(&list) { return Err(Box::new(Error::new(ErrorKind::NotFound, "LIST_DOESNT_EXIST"))); };
71 config_change_current_list(config, list)
72 },
73 2.. => Err(Box::new(Error::new(ErrorKind::InvalidInput, "TOO_MANY_ARGUMENTS"))),
74 _ => panic!("list arguments should never lower than zero"),
75 }
76} 45}
77 46
78fn remove(config: Cfg, args: Vec<String>) -> MLE<()> { 47fn remove(config: Cfg, input: Input) -> MLE<()> {
79 match args.len() { 48 lists_remove(config, input.list.unwrap().id)
80 1 => lists_remove(config, String::from(&args[0])),
81 2.. => Err(MLError::new(ErrorType::ArgumentCountError, "TOO_MANY_ARGUMENTS")),
82 _ => panic!("list arguments should never be zero or lower"),
83 }
84} 49}
85 50
86///Changing the current lists version and updating it 51///Changing the current lists version and updating it
@@ -88,10 +53,14 @@ fn remove(config: Cfg, args: Vec<String>) -> MLE<()> {
88/// 53///
89/// * `config` - The current config 54/// * `config` - The current config
90/// * `args` - All args, to extract the new version 55/// * `args` - All args, to extract the new version
91async fn version(config: Cfg, args: Option<Vec<String>>, version_type: Option<MCVersionType>) -> MLE<()> { 56async fn version(config: Cfg, input: Input) -> MLE<()> {
92 let current_list = lists_get(config.clone(), config_get_current_list(config.clone())?)?; 57 println!("Change version for list {} to minecraft version: {}", input.clone().list.unwrap().id, input.clone().list_mcversion.unwrap());
58
59 lists_version(config.clone(), input.clone().list.ok_or("").unwrap().id, input.clone().list_mcversion.ok_or("").unwrap())?;
60
61 //Linebreak readability
62 println!("");
93 63
94 lists_version(config.clone(), String::from(&current_list.id), String::from(&args.unwrap()[0]))?; 64 println!("Check for updates for new minecraft version in list {}", input.clone().list.unwrap().id);
95 //update the list & with -- args 65 cmd_update(config, vec![input.list.ok_or("").unwrap()], true, input.direct_download, input.delete_old).await
96 cmd_update(config, vec![current_list], true, true, false).await
97} 66}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 0d5bd00..38139f9 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -1,13 +1,13 @@
1pub mod modification; 1pub mod modification;
2pub mod list; 2pub mod list;
3pub mod update; 3pub mod update;
4pub mod setup; 4//pub mod setup;
5pub mod download; 5pub mod download;
6pub mod io; 6pub mod io;
7 7
8pub use modification::*; 8pub use modification::*;
9pub use list::*; 9pub use list::*;
10pub use update::*; 10pub use update::*;
11pub use setup::*; 11//pub use setup::*;
12pub use download::*; 12pub use download::*;
13pub use io::*; 13pub use io::*;
diff --git a/src/commands/modification.rs b/src/commands/modification.rs
index 7d4be8d..c82d6b5 100644
--- a/src/commands/modification.rs
+++ b/src/commands/modification.rs
@@ -1,34 +1,26 @@
1use std::io::{Error, ErrorKind}; 1use crate::{modrinth::{project, versions, extract_current_version, Version, projects}, config::Cfg, db::{mods_insert, userlist_remove, mods_get_id, userlist_insert, mods_get_all_ids, 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}};
2 2
3use crate::{modrinth::{project, versions, extract_current_version, Version, projects}, config::Cfg, db::{mods_insert, userlist_remove, mods_get_id, userlist_insert, mods_get_all_ids, userlist_get_all_ids, userlist_get_current_version, lists_get_all_ids, mods_remove}, input::{Input, Subcmd}, get_current_list, files::{delete_version, download_versions}, List}; 3pub async fn modification(config: Cfg, input: Input) -> MLE<()> {
4 4 match input.clone().mod_options.ok_or("").unwrap() {
5pub async fn modification(config: Cfg, input: Input) -> Result<(), Box<dyn std::error::Error>> { 5 ModOptions::Add => {
6 match input.subcommand.as_ref().ok_or("")? {
7 Subcmd::Add => {
8 add(config, input).await 6 add(config, input).await
9 }, 7 },
10 Subcmd::Remove => { 8 ModOptions::Remove => {
11 remove(config, input.args.ok_or("")?) 9 remove(config, input)
12 }, 10 },
13 _ => Err(Box::new(Error::new(ErrorKind::InvalidInput, "SUBCOMMAND_NOT_AVAILABLE")))
14 } 11 }
15} 12}
16 13
17async fn add(config: Cfg, input: Input) -> Result<(), Box<dyn std::error::Error>> { 14async fn add(config: Cfg, input: Input) -> MLE<()> {
18
19 let args = input.args.ok_or("")?;
20 15
21 if args.is_empty() { return Err(Box::new(Error::new(ErrorKind::InvalidInput, "TOO_FEW_ARGUMENTS"))); }; 16 mod_add(config, vec![String::from(input.mod_id.unwrap())], input.list.unwrap(), input.direct_download).await?;
22
23 let current_list = get_current_list(config.clone())?;
24
25 mod_add(config, vec![String::from(&args[0])], current_list, input.disable_download).await?;
26 17
27 Ok(()) 18 Ok(())
28} 19}
29 20
30pub async fn mod_add(config: Cfg, mod_id: Vec<String>, list: List, disable_download: bool) -> Result<(), Box<dyn std::error::Error>> { 21pub async fn mod_add(config: Cfg, mod_id: Vec<String>, list: List, direct_download: bool) -> MLE<()> {
31 22
23 //Fix printing (its horrible)
32 println!("Adding mod(s) {:?}", mod_id); 24 println!("Adding mod(s) {:?}", mod_id);
33 let projects = if mod_id.len() == 1 { 25 let projects = if mod_id.len() == 1 {
34 vec![project(String::from(&config.apis.modrinth), &mod_id[0]).await] 26 vec![project(String::from(&config.apis.modrinth), &mod_id[0]).await]
@@ -50,7 +42,7 @@ pub async fn mod_add(config: Cfg, mod_id: Vec<String>, list: List, disable_downl
50 42
51 current_version_id = current_version.clone().unwrap().id; 43 current_version_id = current_version.clone().unwrap().id;
52 44
53 file = current_version.clone().ok_or("VERSION_CORRUPTED")?.files.into_iter().find(|f| f.primary).unwrap().url; 45 file = current_version.clone().ok_or("").unwrap().files.into_iter().find(|f| f.primary).unwrap().url;
54 46
55 for ver in available_versions { 47 for ver in available_versions {
56 available_versions_vec.push(ver.id); 48 available_versions_vec.push(ver.id);
@@ -67,7 +59,7 @@ pub async fn mod_add(config: Cfg, mod_id: Vec<String>, list: List, disable_downl
67 match userlist_get_all_ids(config.clone(), list.clone().id) { 59 match userlist_get_all_ids(config.clone(), list.clone().id) {
68 Ok(mods) => { 60 Ok(mods) => {
69 if mods.contains(&project.id) { 61 if mods.contains(&project.id) {
70 return Err(Box::new(Error::new(ErrorKind::Other, "MOD_ALREADY_ON_LIST"))); } 62 return Err(MLError::new(ErrorType::ModError, "MOD_ALREADY_ON_LIST")); }
71 else { 63 else {
72 userlist_insert(config.clone(), String::from(&list.id), String::from(&project.id), String::from(&current_version_id), available_versions_vec, file)?; 64 userlist_insert(config.clone(), String::from(&list.id), String::from(&project.id), String::from(&current_version_id), available_versions_vec, file)?;
73 } 65 }
@@ -88,24 +80,23 @@ pub async fn mod_add(config: Cfg, mod_id: Vec<String>, list: List, disable_downl
88 }, 80 },
89 }; 81 };
90 82
91 if !disable_download && current_version.is_some() { download_versions(list.clone(), vec![current_version.unwrap()]).await?; }; 83 if direct_download && current_version.is_some() { download_versions(list.clone(), config.clone(), vec![current_version.unwrap()]).await?; };
92 84
93 } 85 }
94 86
95 Ok(()) 87 Ok(())
96} 88}
97 89
98fn remove(config: Cfg, args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> { 90fn remove(config: Cfg, input: Input) -> MLE<()> {
99 if args.is_empty() { return Err(Box::new(Error::new(ErrorKind::InvalidInput, "TOO_FEW_ARGUMENTS"))); }; 91
100 92 //TODO inplement deletion by slug or title
101 let current_list = get_current_list(config.clone())?; 93 let mod_id = mods_get_id(config.clone(), input.clone().mod_id.unwrap())?;
102 let mod_id = mods_get_id(config.clone(), String::from(&args[0]))?;
103 94
104 let version = userlist_get_current_version(config.clone(), String::from(&current_list.id), String::from(&mod_id))?; 95 let version = userlist_get_current_version(config.clone(), input.clone().list.unwrap().id, String::from(&mod_id))?;
105 96
106 //TODO implement remove from modlist if not in any other lists && config clean is true 97 //TODO implement remove from modlist if not in any other lists && config clean is true
107 userlist_remove(config.clone(), String::from(&current_list.id), String::from(&mod_id))?; 98 userlist_remove(config.clone(), input.clone().list.unwrap().id, String::from(&mod_id))?;
108 delete_version(current_list, version)?; 99 delete_version(input.list.unwrap(), version)?;
109 100
110 let list_ids = lists_get_all_ids(config.clone())?; 101 let list_ids = lists_get_all_ids(config.clone())?;
111 102
diff --git a/src/commands/setup.rs b/src/commands/setup.rs
index e4fa801..cc7472c 100644
--- a/src/commands/setup.rs
+++ b/src/commands/setup.rs
@@ -63,4 +63,4 @@ fn to_04(config: Cfg) -> Result<(), Box<dyn std::error::Error>> {
63 s_insert_column(config.clone(), list_id, String::from("disabled_versions"), String::from("TEXT"), Some(String::from("NONE")))?; 63 s_insert_column(config.clone(), list_id, String::from("disabled_versions"), String::from("TEXT"), Some(String::from("NONE")))?;
64 } 64 }
65 s_config_update_version(config, String::from("0.4")) 65 s_config_update_version(config, String::from("0.4"))
66} 66} \ No newline at end of file
diff --git a/src/commands/update.rs b/src/commands/update.rs
index ca28130..d400a24 100644
--- a/src/commands/update.rs
+++ b/src/commands/update.rs
@@ -1,9 +1,6 @@
1use std::io::{Error, ErrorKind}; 1use crate::{config::Cfg, modrinth::{projects, Project, versions, extract_current_version, Version}, get_current_list, db::{userlist_get_all_ids, mods_get_versions, userlist_get_applicable_versions, userlist_change_versions, lists_get_all_ids, lists_get, userlist_get_current_version, mods_change_versions}, List, input::Input, files::{delete_version, download_versions, disable_version, clean_list_dir}, error::{MLE, MLError, ErrorType}};
2
3use crate::{config::Cfg, modrinth::{projects, Project, versions, extract_current_version, Version}, get_current_list, db::{userlist_get_all_ids, mods_get_versions, userlist_get_applicable_versions, userlist_change_versions, lists_get_all_ids, lists_get, userlist_get_current_version, mods_change_versions}, List, input::Input, files::{delete_version, download_versions, disable_version}, error::{MLE, MLError, ErrorType}};
4 2
5pub async fn update(config: Cfg, input: Input) -> MLE<()> { 3pub async fn update(config: Cfg, input: Input) -> MLE<()> {
6
7 let mut liststack: Vec<List> = vec![]; 4 let mut liststack: Vec<List> = vec![];
8 if input.all_lists { 5 if input.all_lists {
9 let list_ids = lists_get_all_ids(config.clone())?; 6 let list_ids = lists_get_all_ids(config.clone())?;
@@ -12,10 +9,9 @@ pub async fn update(config: Cfg, input: Input) -> MLE<()> {
12 } 9 }
13 } else { 10 } else {
14 let current = get_current_list(config.clone())?; 11 let current = get_current_list(config.clone())?;
15 println!("Checking for updates of mods in {}", current.id); 12 println!("Check for updates of mods in list {}", current.id);
16 liststack.push(current) 13 liststack.push(current)
17 } 14 }
18
19 cmd_update(config, liststack, input.clean, input.direct_download, input.delete_old).await 15 cmd_update(config, liststack, input.clean, input.direct_download, input.delete_old).await
20} 16}
21 17
@@ -31,6 +27,7 @@ pub async fn cmd_update(config: Cfg, liststack: Vec<List>, clean: bool, direct_d
31 let mut projects = projects(String::from(&config.apis.modrinth), mods).await; 27 let mut projects = projects(String::from(&config.apis.modrinth), mods).await;
32 projects.sort_by_key(|pro| pro.id.clone()); 28 projects.sort_by_key(|pro| pro.id.clone());
33 29
30 println!("Comparing mod versions:");
34 let mut updatestack: Vec<Version> = vec![]; 31 let mut updatestack: Vec<Version> = vec![];
35 for (index, project) in projects.into_iter().enumerate() { 32 for (index, project) in projects.into_iter().enumerate() {
36 //Get versions for project and check if they match up 33 //Get versions for project and check if they match up
@@ -39,6 +36,8 @@ pub async fn cmd_update(config: Cfg, liststack: Vec<List>, clean: bool, direct_d
39 let v_id = &current_version.mod_id; 36 let v_id = &current_version.mod_id;
40 if &p_id != v_id { return Err(MLError::new(ErrorType::Other, "SORTING_ERROR")) }; 37 if &p_id != v_id { return Err(MLError::new(ErrorType::Other, "SORTING_ERROR")) };
41 38
39 println!("\t({}) Check for update", project.title);
40
42 //Getting current installed version for disable or delete 41 //Getting current installed version for disable or delete
43 let disable_version = userlist_get_current_version(config.clone(), String::from(&current_list.id), String::from(&project.id))?; 42 let disable_version = userlist_get_current_version(config.clone(), String::from(&current_list.id), String::from(&project.id))?;
44 43
@@ -51,51 +50,52 @@ pub async fn cmd_update(config: Cfg, liststack: Vec<List>, clean: bool, direct_d
51 current_versions.push((disable_version, p_id)); 50 current_versions.push((disable_version, p_id));
52 ver 51 ver
53 }, 52 },
54 //TODO handle errors (only continue on "NO_UPDATE_AVAILABLE") 53 Err(e) => {
55 Err(..) => { 54 //Catch no update available
56 //Updating versions in modlist for no repeating version calls 55 if e.to_string() == "Mod: NO_UPDATE_AVAILABLE" {
57 mods_change_versions(config.clone(), version_db_string, project.id)?; 56 mods_change_versions(config.clone(), version_db_string, project.id)?;
58 println!("({}) No new version found for the specified", project.title); 57 println!("\t └No new version found for the specified minecraft version");
58 } else {
59 return Err(e);
60 };
59 continue; 61 continue;
60 }, 62 },
61 }); 63 });
62 } else { 64 } else {
63 println!("({}) No new version found", project.title); 65 println!("\t No new version found");
64 }; 66 };
65 }; 67 };
68
69 //Linebreak readability
70 println!("");
66 71
67 if clean { 72 if clean { clean_list_dir(&current_list)? };
68 let dl_path = &current_list.download_folder;
69 println!("Cleaning {}", dl_path);
70 for entry in std::fs::read_dir(dl_path)? {
71 let entry = entry?;
72 std::fs::remove_file(entry.path())?;
73 }
74 }
75 73
76 if direct_download { 74 //Linebreak readability
77 download_versions(current_list.clone(), updatestack).await?; 75 println!("");
76
77 if direct_download && !updatestack.is_empty() {
78 download_versions(current_list.clone(), config.clone(), updatestack).await?;
78 79
79 //Disable old versions 80 //Disable old versions
80 for ver in current_versions { 81 if !clean {
81 if delete_old { 82 for ver in current_versions {
82 println!("Deleting version {} for mod {}", ver.0, ver.1); 83 if delete_old {
83 delete_version(current_list.clone(), ver.0)?; 84 println!("Deleting version {} for mod {}", ver.0, ver.1);
84 } else if ver.0 != "NONE" { 85 delete_version(current_list.clone(), ver.0)?;
85 println!("Disabling version {} for mod {}", ver.0, ver.1); 86 } else if ver.0 != "NONE" {
86 disable_version(config.clone(), current_list.clone(), ver.0, ver.1)?; 87 println!("Disabling version {} for mod {}", ver.0, ver.1);
87 }; 88 disable_version(config.clone(), current_list.clone(), ver.0, ver.1)?;
89 };
90 }
88 } 91 }
89 }; 92 };
90
91 } 93 }
92 94
93 Ok(()) 95 Ok(())
94} 96}
95 97
96async fn specific_update(config: Cfg, clean: bool, list: List, project: Project) -> Result<Version, Box<dyn std::error::Error>> { 98async fn specific_update(config: Cfg, clean: bool, list: List, project: Project) -> MLE<Version> {
97 println!("Checking update for '{}' in {}", project.title, list.id);
98
99 let applicable_versions = versions(String::from(&config.apis.modrinth), String::from(&project.id), list.clone()).await; 99 let applicable_versions = versions(String::from(&config.apis.modrinth), String::from(&project.id), list.clone()).await;
100 100
101 let mut versions: Vec<String> = vec![]; 101 let mut versions: Vec<String> = vec![];
@@ -112,18 +112,24 @@ async fn specific_update(config: Cfg, clean: bool, list: List, project: Project)
112 let mut current: Vec<Version> = vec![]; 112 let mut current: Vec<Version> = vec![];
113 if clean || (versions.join("|") != userlist_get_applicable_versions(config.clone(), String::from(&list.id), String::from(&project.id))?) { 113 if clean || (versions.join("|") != userlist_get_applicable_versions(config.clone(), String::from(&list.id), String::from(&project.id))?) {
114 //get new versions 114 //get new versions
115 print!(" | getting new version"); 115 println!("\t └Get versions for specified minecraft versions");
116 let current_str = extract_current_version(applicable_versions.clone())?; 116 let current_str = extract_current_version(applicable_versions.clone())?;
117 let current_ver = applicable_versions.into_iter().find(|ver| ver.id == current_str).ok_or("")?; 117 let current_ver = match applicable_versions.into_iter().find(|ver| ver.id == current_str).ok_or("!no current version in applicable_versions") {
118 Ok(v) => Ok(v),
119 Err(e) => Err(MLError::new(ErrorType::Other, e)),
120 }?;
118 current.push(current_ver.clone()); 121 current.push(current_ver.clone());
119 122
120 let link = current_ver.files.into_iter().find(|f| f.primary).ok_or("")?.url; 123 let link = match current_ver.files.into_iter().find(|f| f.primary).ok_or("!no primary in links") {
124 Ok(p) => Ok(p),
125 Err(e) => Err(MLError::new(ErrorType::Other, e)),
126 }?.url;
121 userlist_change_versions(config, list.id, current_str, versions.join("|"), link, project.id)?; 127 userlist_change_versions(config, list.id, current_str, versions.join("|"), link, project.id)?;
122 } 128 }
123 129
124 if current.is_empty() { return Err(Box::new(Error::new(ErrorKind::NotFound, "NO_UPDATE_AVAILABLE"))) }; 130 if current.is_empty() { return Err(MLError::new(ErrorType::ModError, "NO_UPDATE_AVAILABLE")) };
125 131
126 println!(" | ✔️"); 132 //println!(" ������️");
127 Ok(current[0].clone()) 133 Ok(current[0].clone())
128} 134}
129 135
@@ -132,6 +138,7 @@ async fn download_updates_test() {
132 138
133 use crate::{modrinth::{Version, VersionFile, Hash, VersionType}, Modloader, List}; 139 use crate::{modrinth::{Version, VersionFile, Hash, VersionType}, Modloader, List};
134 140
141 let config = Cfg::init("modlist.toml").unwrap();
135 let current_list = List { id: String::from("..."), mc_version: String::from("..."), modloader: Modloader::Forge, download_folder: String::from("./dl") }; 142 let current_list = List { id: String::from("..."), mc_version: String::from("..."), modloader: Modloader::Forge, download_folder: String::from("./dl") };
136 143
137 let versions = vec![Version { 144 let versions = vec![Version {
@@ -164,5 +171,5 @@ async fn download_updates_test() {
164 "fabric".to_string() 171 "fabric".to_string()
165 ] 172 ]
166 }]; 173 }];
167 assert!(download_versions(current_list, versions).await.is_ok()) 174 assert!(download_versions(current_list, config, versions).await.is_ok())
168} 175}
diff --git a/src/config.rs b/src/config.rs
index 383e7ee..ded0062 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -25,7 +25,6 @@ impl Cfg {
25 if err.kind() == std::io::ErrorKind::NotFound { 25 if err.kind() == std::io::ErrorKind::NotFound {
26 println!("No config file found, creating one"); 26 println!("No config file found, creating one");
27 let default_cfg = Cfg { data: String::from("./"), apis: Apis { modrinth: String::from("https://api.modrinth.com/v2/") } }; 27 let default_cfg = Cfg { data: String::from("./"), apis: Apis { modrinth: String::from("https://api.modrinth.com/v2/") } };
28 //TODO Error
29 let mut file = File::create(devdir(configfile.to_str().unwrap()))?; 28 let mut file = File::create(devdir(configfile.to_str().unwrap()))?;
30 println!("Created config file"); 29 println!("Created config file");
31 file.write_all(&toml::to_string(&default_cfg)?.as_bytes())?; 30 file.write_all(&toml::to_string(&default_cfg)?.as_bytes())?;
diff --git a/src/db.rs b/src/db.rs
index 06c2459..f47bda6 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -5,7 +5,7 @@ use rusqlite::Connection;
5use crate::{Modloader, config::Cfg, List, devdir, error::{MLE, MLError, ErrorType}}; 5use crate::{Modloader, config::Cfg, List, devdir, error::{MLE, MLError, ErrorType}};
6 6
7//mods 7//mods
8pub fn mods_insert(config: Cfg, id: String, name: String, versions: Vec<String>) -> Result<(), Box<dyn std::error::Error>> { 8pub fn mods_insert(config: Cfg, id: String, name: String, versions: Vec<String>) -> MLE<()> {
9 9
10 println!("Inserting mod {}({}) into database", name, id); 10 println!("Inserting mod {}({}) into database", name, id);
11 11
@@ -41,7 +41,7 @@ pub fn mods_get_all_ids(config: Cfg) -> Result<Vec<String>, Box<dyn std::error::
41 } 41 }
42} 42}
43 43
44pub fn mods_get_id(config: Cfg, name: String) -> Result<String, Box<dyn std::error::Error>> { 44pub fn mods_get_id(config: Cfg, name: String) -> MLE<String> {
45 let data = devdir(format!("{}/data.db", config.data).as_str()); 45 let data = devdir(format!("{}/data.db", config.data).as_str());
46 let connection = Connection::open(data)?; 46 let connection = Connection::open(data)?;
47 47
@@ -56,12 +56,12 @@ pub fn mods_get_id(config: Cfg, name: String) -> Result<String, Box<dyn std::err
56 }; 56 };
57 57
58 match mod_id.is_empty() { 58 match mod_id.is_empty() {
59 true => Err(Box::new(Error::new(ErrorKind::NotFound, "MOD_NOT_FOUND"))), 59 true => Err(MLError::new(ErrorType::DBError, "GI_MOD_NOT_FOUND")),
60 false => Ok(mod_id), 60 false => Ok(mod_id),
61 } 61 }
62} 62}
63 63
64pub fn mods_get_name(config: Cfg, id: String) -> Result<String, Box<dyn std::error::Error>> { 64pub fn mods_get_name(config: Cfg, id: &str) -> MLE<String> {
65 let data = devdir(format!("{}/data.db", config.data).as_str()); 65 let data = devdir(format!("{}/data.db", config.data).as_str());
66 let connection = Connection::open(data)?; 66 let connection = Connection::open(data)?;
67 67
@@ -76,14 +76,14 @@ pub fn mods_get_name(config: Cfg, id: String) -> Result<String, Box<dyn std::err
76 }; 76 };
77 77
78 match mod_name.is_empty() { 78 match mod_name.is_empty() {
79 true => Err(Box::new(Error::new(ErrorKind::NotFound, "MOD_NOT_FOUND"))), 79 true => Err(MLError::new(ErrorType::DBError, "GN_MOD_NOT_FOUND")),
80 false => Ok(mod_name), 80 false => Ok(mod_name),
81 } 81 }
82} 82}
83 83
84pub fn mods_change_versions(config: Cfg, versions: String, mod_id: String) -> MLE<()> { 84pub fn mods_change_versions(config: Cfg, versions: String, mod_id: String) -> MLE<()> {
85 85
86 println!("Updating versions for {} with \n {}", mod_id, versions); 86 //println!("Updating versions for {} with \n {}", mod_id, versions);
87 87
88 let data = devdir(format!("{}/data.db", config.data).as_str()); 88 let data = devdir(format!("{}/data.db", config.data).as_str());
89 let connection = Connection::open(data)?; 89 let connection = Connection::open(data)?;
@@ -92,7 +92,7 @@ pub fn mods_change_versions(config: Cfg, versions: String, mod_id: String) -> ML
92 Ok(()) 92 Ok(())
93} 93}
94 94
95pub fn mods_remove(config: Cfg, id: String) -> Result<(), Box<dyn std::error::Error>> { 95pub fn mods_remove(config: Cfg, id: String) -> MLE<()> {
96 96
97 println!("Removing mod {} from database", id); 97 println!("Removing mod {} from database", id);
98 98
@@ -131,7 +131,7 @@ pub fn mods_get_versions(config: Cfg, mods: Vec<String>) -> MLE<Vec<DBModlistVer
131 131
132 for ver in id_iter { 132 for ver in id_iter {
133 let version = ver?; 133 let version = ver?;
134 println!("Getting versions for {} from the database", String::from(&version[2])); 134 println!("\t({}) Get versions from the database", String::from(&version[2]));
135 //println!("Found versions {} for mod {}", version[1], version[0]); 135 //println!("Found versions {} for mod {}", version[1], version[0]);
136 versionmaps.push(DBModlistVersions { mod_id: String::from(&version[0]), versions: String::from(&version[1]) }) 136 versionmaps.push(DBModlistVersions { mod_id: String::from(&version[0]), versions: String::from(&version[1]) })
137 }; 137 };
@@ -143,7 +143,7 @@ pub fn mods_get_versions(config: Cfg, mods: Vec<String>) -> MLE<Vec<DBModlistVer
143} 143}
144 144
145//userlist 145//userlist
146pub fn userlist_insert(config: Cfg, list_id: String, mod_id: String, current_version: String, applicable_versions: Vec<String>, current_link: String) -> Result<(), Box<dyn std::error::Error>> { 146pub fn userlist_insert(config: Cfg, list_id: String, mod_id: String, current_version: String, applicable_versions: Vec<String>, current_link: String) -> MLE<()> {
147 println!("Inserting {} into current list({})", mod_id, list_id); 147 println!("Inserting {} into current list({})", mod_id, list_id);
148 148
149 let data = devdir(format!("{}/data.db", config.data).as_str()); 149 let data = devdir(format!("{}/data.db", config.data).as_str());
@@ -177,7 +177,7 @@ pub fn userlist_get_all_ids(config: Cfg, list_id: String) -> MLE<Vec<String>> {
177} 177}
178 178
179 179
180pub fn userlist_remove(config: Cfg, list_id: String, mod_id: String) -> Result<(), Box<dyn std::error::Error>> { 180pub fn userlist_remove(config: Cfg, list_id: String, mod_id: String) -> MLE<()> {
181 let data = devdir(format!("{}/data.db", config.data).as_str()); 181 let data = devdir(format!("{}/data.db", config.data).as_str());
182 let connection = Connection::open(data)?; 182 let connection = Connection::open(data)?;
183 183
@@ -186,7 +186,7 @@ pub fn userlist_remove(config: Cfg, list_id: String, mod_id: String) -> Result<(
186} 186}
187 187
188 188
189pub fn userlist_get_applicable_versions(config: Cfg, list_id: String, mod_id: String) -> Result<String, Box<dyn std::error::Error>> { 189pub fn userlist_get_applicable_versions(config: Cfg, list_id: String, mod_id: String) -> MLE<String> {
190 let data = devdir(format!("{}/data.db", config.data).as_str()); 190 let data = devdir(format!("{}/data.db", config.data).as_str());
191 let connection = Connection::open(data).unwrap(); 191 let connection = Connection::open(data).unwrap();
192 192
@@ -201,12 +201,12 @@ pub fn userlist_get_applicable_versions(config: Cfg, list_id: String, mod_id: St
201 }; 201 };
202 202
203 match version.is_empty() { 203 match version.is_empty() {
204 true => Err(Box::new(Error::new(ErrorKind::NotFound, "MOD_NOT_FOUND"))), 204 true => Err(MLError::new(ErrorType::DBError, "GAV_MOD_NOT_FOUND")),
205 false => Ok(version), 205 false => Ok(version),
206 } 206 }
207} 207}
208 208
209pub fn userlist_get_all_applicable_versions_with_mods(config: Cfg, list_id: String) -> Result<Vec<(String, String)>, Box<dyn std::error::Error>> { 209pub fn userlist_get_all_applicable_versions_with_mods(config: Cfg, list_id: String) -> MLE<Vec<(String, String)>> {
210 let data = devdir(format!("{}/data.db", config.data).as_str()); 210 let data = devdir(format!("{}/data.db", config.data).as_str());
211 let connection = Connection::open(data)?; 211 let connection = Connection::open(data)?;
212 212
@@ -221,7 +221,7 @@ pub fn userlist_get_all_applicable_versions_with_mods(config: Cfg, list_id: Stri
221 versions.push((out[0].to_owned(), out[1].to_owned())); 221 versions.push((out[0].to_owned(), out[1].to_owned()));
222 }; 222 };
223 223
224 if versions.is_empty() { return Err(Box::new(std::io::Error::new(ErrorKind::Other, "NO_MODS_ON_LIST"))); }; 224 if versions.is_empty() { return Err(MLError::new(ErrorType::DBError, "NO_MODS_ON_LIST")); };
225 225
226 Ok(versions) 226 Ok(versions)
227} 227}
@@ -241,7 +241,7 @@ pub fn userlist_get_current_version(config: Cfg, list_id: String, mod_id: String
241 }; 241 };
242 242
243 match version.is_empty() { 243 match version.is_empty() {
244 true => Err(MLError::new(ErrorType::DBError, "MOD_NOT_FOUND")), 244 true => Err(MLError::new(ErrorType::DBError, "GCV_MOD_NOT_FOUND")),
245 false => Ok(version), 245 false => Ok(version),
246 } 246 }
247} 247}
@@ -285,7 +285,7 @@ pub fn userlist_get_all_current_versions_with_mods(config: Cfg, list_id: String)
285 Ok(versions) 285 Ok(versions)
286} 286}
287 287
288pub fn userlist_change_versions(config: Cfg, list_id: String, current_version: String, versions: String, link: String, mod_id: String) -> Result<(), Box<dyn std::error::Error>> { 288pub fn userlist_change_versions(config: Cfg, list_id: String, current_version: String, versions: String, link: String, mod_id: String) -> MLE<()> {
289 let data = devdir(format!("{}/data.db", config.data).as_str()); 289 let data = devdir(format!("{}/data.db", config.data).as_str());
290 let connection = Connection::open(data)?; 290 let connection = Connection::open(data)?;
291 291
@@ -322,7 +322,7 @@ pub fn userlist_get_disabled_versions(config:Cfg, list_id: String, mod_id: Strin
322 }; 322 };
323 323
324 match version.is_empty() { 324 match version.is_empty() {
325 true => Err(MLError::new(ErrorType::DBError, "MOD_NOT_FOUND")), 325 true => Err(MLError::new(ErrorType::DBError, "GDV_MOD_NOT_FOUND")),
326 false => Ok(version), 326 false => Ok(version),
327 } 327 }
328} 328}
@@ -349,6 +349,7 @@ pub fn userlist_get_all_downloads(config: Cfg, list_id: String) -> Result<Vec<St
349} 349}
350 350
351//lists 351//lists
352///Inserts into lists table and creates new table
352pub fn lists_insert(config: Cfg, id: String, mc_version: String, mod_loader: Modloader, download_folder: String) -> MLE<()> { 353pub fn lists_insert(config: Cfg, id: String, mc_version: String, mod_loader: Modloader, download_folder: String) -> MLE<()> {
353 println!("Creating list {}", id); 354 println!("Creating list {}", id);
354 355
@@ -420,7 +421,7 @@ pub fn lists_get_all_ids(config: Cfg) -> MLE<Vec<String>> {
420} 421}
421 422
422//config 423//config
423pub fn config_change_current_list(config: Cfg, id: String) -> Result<(), Box<dyn std::error::Error>> { 424pub fn config_change_current_list(config: Cfg, id: String) -> MLE<()> {
424 let data = devdir(format!("{}/data.db", config.data).as_str()); 425 let data = devdir(format!("{}/data.db", config.data).as_str());
425 let connection = Connection::open(data)?; 426 let connection = Connection::open(data)?;
426 427
diff --git a/src/error.rs b/src/error.rs
index dbe7224..612a2e2 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -15,9 +15,11 @@ pub enum ErrorType {
15 ArgumentCountError, 15 ArgumentCountError,
16 ConfigError, 16 ConfigError,
17 DBError, 17 DBError,
18 ModError,
18 LibToml, 19 LibToml,
19 LibSql, 20 LibSql,
20 LibReq, 21 LibReq,
22 LibChrono,
21 IoError, 23 IoError,
22 Other, 24 Other,
23} 25}
@@ -31,13 +33,15 @@ impl std::error::Error for MLError {
31impl fmt::Display for MLError { 33impl fmt::Display for MLError {
32 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 34 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33 match self.etype { 35 match self.etype {
34 ErrorType::ArgumentError => write!(f, "Wrong argument"), 36 ErrorType::ArgumentError => write!(f, "User input not accepted: {}", self.message),
35 ErrorType::ArgumentCountError => write!(f, "Too many/too few arguments"), 37 ErrorType::ArgumentCountError => write!(f, "Too many/too few arguments"),
36 ErrorType::ConfigError => write!(f, "CONFIG"), 38 ErrorType::ConfigError => write!(f, "CONFIG"),
37 ErrorType::DBError => write!(f, "DATABASE"), 39 ErrorType::DBError => write!(f, "Database: {}", self.message),
40 ErrorType::ModError => write!(f, "Mod: {}", self.message),
38 ErrorType::LibToml => write!(f, "TOML"), 41 ErrorType::LibToml => write!(f, "TOML"),
39 ErrorType::LibSql => write!(f, "SQL"), 42 ErrorType::LibSql => write!(f, "SQL"),
40 ErrorType::LibReq => write!(f, "REQWEST"), 43 ErrorType::LibReq => write!(f, "REQWEST"),
44 ErrorType::LibChrono => write!(f, "Chrono error: {}", self.message),
41 ErrorType::IoError => write!(f, "IO"), 45 ErrorType::IoError => write!(f, "IO"),
42 ErrorType::Other => write!(f, "OTHER") 46 ErrorType::Other => write!(f, "OTHER")
43 } 47 }
@@ -68,6 +72,12 @@ impl From<toml::ser::Error> for MLError {
68 } 72 }
69} 73}
70 74
75impl From<chrono::ParseError> for MLError {
76 fn from(error: chrono::ParseError) -> Self {
77 Self { etype: ErrorType::LibChrono, message: error.to_string() }
78 }
79}
80
71impl From<std::io::Error> for MLError { 81impl From<std::io::Error> for MLError {
72 fn from(error: std::io::Error) -> Self { 82 fn from(error: std::io::Error) -> Self {
73 Self { etype: ErrorType::IoError, message: error.to_string() } 83 Self { etype: ErrorType::IoError, message: error.to_string() }
diff --git a/src/files.rs b/src/files.rs
index 998ed32..8c822b2 100644
--- a/src/files.rs
+++ b/src/files.rs
@@ -2,13 +2,19 @@ use std::{fs::{File, read_dir, remove_file, rename}, io::Write, collections::Has
2use futures_util::StreamExt; 2use futures_util::StreamExt;
3use reqwest::Client; 3use reqwest::Client;
4 4
5use crate::{List, modrinth::Version, db::userlist_add_disabled_versions, config::Cfg, error::{MLE, MLError, ErrorType}}; 5use crate::{List, modrinth::Version, db::{userlist_add_disabled_versions, mods_get_name}, config::Cfg, error::{MLE, MLError, ErrorType}};
6 6
7pub async fn download_versions(current_list: List, versions: Vec<Version>) -> MLE<String> { 7pub async fn download_versions(list: List, config: Cfg, versions: Vec<Version>) -> MLE<String> {
8 8
9 let dl_path = String::from(&current_list.download_folder); 9 let dl_path = String::from(&list.download_folder);
10
11 println!("Download to directory from: {} ({})", list.id, dl_path);
10 12
11 for ver in versions { 13 for ver in versions {
14 let project_name = mods_get_name(config.clone(), &ver.project_id)?;
15 print!("\t({})Download version {}", project_name, ver.id);
16 //Force flush of stdout, else print! doesn't print instantly
17 std::io::stdout().flush().unwrap();
12 let primary_file = ver.files.into_iter().find(|file| file.primary).unwrap(); 18 let primary_file = ver.files.into_iter().find(|file| file.primary).unwrap();
13 let mut splitname: Vec<&str> = primary_file.filename.split('.').collect(); 19 let mut splitname: Vec<&str> = primary_file.filename.split('.').collect();
14 let extension = match splitname.pop().ok_or("") { 20 let extension = match splitname.pop().ok_or("") {
@@ -16,14 +22,15 @@ pub async fn download_versions(current_list: List, versions: Vec<Version>) -> ML
16 Err(..) => return Err(MLError::new(ErrorType::Other, "NO_FILE_EXTENSION")), 22 Err(..) => return Err(MLError::new(ErrorType::Other, "NO_FILE_EXTENSION")),
17 }; 23 };
18 let filename = format!("{}.mr.{}.{}.{}", splitname.join("."), ver.project_id, ver.id, extension); 24 let filename = format!("{}.mr.{}.{}.{}", splitname.join("."), ver.project_id, ver.id, extension);
19 download_file(primary_file.url, current_list.clone().download_folder, filename).await?; 25 download_file(primary_file.url, list.clone().download_folder, filename).await?;
26 //tokio::time::sleep(std::time::Duration::new(3, 0)).await;
27 println!(" ✓");
20 } 28 }
21 29
22 Ok(dl_path) 30 Ok(dl_path)
23} 31}
24 32
25async fn download_file(url: String, path: String, name: String) -> MLE<()> { 33async fn download_file(url: String, path: String, name: String) -> MLE<()> {
26 println!("Downloading {}", url);
27 let dl_path_file = format!("{}/{}", path, name); 34 let dl_path_file = format!("{}/{}", path, name);
28 let res = Client::new() 35 let res = Client::new()
29 .get(String::from(&url)) 36 .get(String::from(&url))
@@ -43,7 +50,7 @@ async fn download_file(url: String, path: String, name: String) -> MLE<()> {
43} 50}
44 51
45pub fn disable_version(config: Cfg, current_list: List, versionid: String, mod_id: String) -> MLE<()> { 52pub fn disable_version(config: Cfg, current_list: List, versionid: String, mod_id: String) -> MLE<()> {
46 println!("Disabling version {} for mod {}", versionid, mod_id); 53 //println!("Disabling version {} for mod {}", versionid, mod_id);
47 let file = get_file_path(current_list.clone(), String::from(&versionid))?; 54 let file = get_file_path(current_list.clone(), String::from(&versionid))?;
48 let disabled = format!("{}.disabled", file); 55 let disabled = format!("{}.disabled", file);
49 56
@@ -85,15 +92,25 @@ pub fn get_file_path(list: List, versionid: String) -> MLE<String> {
85 Ok(filename.to_owned()) 92 Ok(filename.to_owned())
86} 93}
87 94
88pub fn get_downloaded_versions(list: List) -> Result<HashMap<String, String>, Box<dyn std::error::Error>> { 95pub fn get_downloaded_versions(list: List) -> MLE<HashMap<String, String>> {
89 let mut versions: HashMap<String, String> = HashMap::new(); 96 let mut versions: HashMap<String, String> = HashMap::new();
90 for file in read_dir(&list.download_folder)? { 97 for file in read_dir(&list.download_folder)? {
91 let path = file?.path(); 98 let path = file?.path();
92 if path.is_file() && path.extension().ok_or("BAH")? == "jar" { 99 if path.is_file() && path.extension().ok_or("BAH").unwrap() == "jar" {
93 let pathstr = path.to_str().ok_or("BAH")?; 100 let pathstr = path.to_str().ok_or("BAH").unwrap();
94 let namesplit: Vec<&str> = pathstr.split('.').collect(); 101 let namesplit: Vec<&str> = pathstr.split('.').collect();
95 versions.insert(String::from(namesplit[namesplit.len() - 3]), String::from(namesplit[namesplit.len() - 2])); 102 versions.insert(String::from(namesplit[namesplit.len() - 3]), String::from(namesplit[namesplit.len() - 2]));
96 } 103 }
97 } 104 }
98 Ok(versions) 105 Ok(versions)
99} 106}
107
108pub fn clean_list_dir(list: &List) -> MLE<()> {
109 let dl_path = &list.download_folder;
110 println!("Clean directory for: {}", list.id);
111 for entry in std::fs::read_dir(dl_path)? {
112 let entry = entry?;
113 std::fs::remove_file(entry.path())?;
114 };
115 Ok(())
116}
diff --git a/src/input.rs b/src/input.rs
index 28a0b7b..144f22a 100644
--- a/src/input.rs
+++ b/src/input.rs
@@ -1,85 +1,24 @@
1use std::env; 1use crate::{error::{MLE, MLError, ErrorType}, Modloader, config::Cfg, db::lists_get, get_current_list, List, modrinth::{get_minecraft_version, MCVersionType}};
2use crate::{config::Cfg, list, modification, update, setup, download, io, error::{MLError, ErrorType, MLE}};
3 2
4#[derive(Debug, Clone, PartialEq, Eq)] 3#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct Input { 4pub struct Input {
6 pub command: Cmd, 5 pub command: Option<Cmd>,
7 pub subcommand: Option<Subcmd>, 6 pub mod_options: Option<ModOptions>,
8 pub args: Option<Vec<String>>, 7 pub mod_id: Option<String>,
9 pub direct_download: bool, 8 pub mod_version: Option<String>,
9 pub set_version: bool,
10 pub all_lists: bool, 10 pub all_lists: bool,
11 pub delete_old: bool,
12 pub clean: bool, 11 pub clean: bool,
13 pub disable_download: bool, 12 pub direct_download: bool,
14 pub version: bool, 13 pub delete_old: bool,
15} 14 pub list: Option<List>,
16 15 pub list_options: Option<ListOptions>,
17impl Input { 16 pub list_id: Option<String>,
18 fn from(string: &str) -> MLE<Self> { 17 pub list_mcversion: Option<String>,
19 let mut split: Vec<&str> = string.split(' ').collect(); 18 pub modloader: Option<Modloader>,
20 19 pub directory: Option<String>,
21 let mut direct_download = false; 20 pub io_options: Option<IoOptions>,
22 let mut all_lists = false; 21 pub file: Option<String>,
23 let mut delete_old = false;
24 let mut clean = false;
25 let mut disable_download = false;
26 let mut version = false;
27
28 let mut toremove: Vec<usize> = vec![];
29 for (i, input) in split.clone().into_iter().enumerate() {
30 if input.starts_with("--") {
31 match input {
32 "--direct-download" => direct_download = true,
33 "--all-lists" => all_lists = true,
34 "--delete-old" => delete_old = true,
35 "--clean" => clean = true,
36 "--disable-download" => disable_download = true,
37 "--version" => version = true,
38 _ => continue,
39 }
40 toremove.push(i)
41 }
42 }
43
44 for rem in toremove.into_iter().rev() {
45 split.remove(rem);
46 }
47
48 if version {
49 match std::env::var("DEV") {
50 Ok(dev) => {
51 let devint = dev.parse::<i32>().unwrap();
52 if devint >= 1 {
53 println!("Modlist by FxQnLr v{} (DEV)", env!("CARGO_PKG_VERSION"));
54 } else {
55 println!("Modlist by FxQnLr v{}", env!("CARGO_PKG_VERSION"));
56 }
57 },
58 Err(..) => println!("Modlist by FxQnLr v{}", env!("CARGO_PKG_VERSION")),
59 }
60
61 std::process::exit(0);
62 }
63
64 let command = Cmd::from(split.remove(0))?;
65 let subcommand = match split.is_empty() {
66 false => Some(Subcmd::from(split.remove(0))?),
67 true => None
68 };
69
70 let args = match split.is_empty() {
71 true => None,
72 false => {
73 let mut strsplit: Vec<String> = Vec::new();
74 for s in split {
75 strsplit.push(String::from(s))
76 }
77 Some(strsplit)
78 }
79 };
80
81 Ok(Self { command, subcommand, args, direct_download, all_lists, delete_old, clean, disable_download, version })
82 }
83} 22}
84 23
85#[derive(Debug, Clone, PartialEq, Eq)] 24#[derive(Debug, Clone, PartialEq, Eq)]
@@ -88,90 +27,318 @@ pub enum Cmd {
88 List, 27 List,
89 Update, 28 Update,
90 Download, 29 Download,
91 Setup, 30 Io,
92 Io 31 Version,
93} 32}
94 33
95impl Cmd { 34#[derive(Debug, Clone, PartialEq, Eq)]
96 fn from(string: &str) -> MLE<Self> { 35pub enum ModOptions {
97 let cmd = match string { 36 Add,
98 "mod" => Self::Mod, 37 Remove
99 "list" => Self::List,
100 "update" => Self::Update,
101 "download" => Self::Download,
102 "setup" => Self::Setup,
103 "io" => Self::Io,
104 _ => return Err(MLError::new(ErrorType::ArgumentError, "Unknown command"))
105 };
106 Ok(cmd)
107 }
108} 38}
109 39
110#[derive(Debug, Clone, PartialEq, Eq)] 40#[derive(Debug, Clone, PartialEq, Eq)]
111pub enum Subcmd { 41pub enum ListOptions {
112 Add, 42 Add,
113 Remove, 43 Remove,
114 Change, 44 Change,
115 Version, 45 Version,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum IoOptions {
116 Export, 50 Export,
117 Import, 51 Import
118} 52}
119 53
120impl Subcmd { 54impl Input {
121 fn from(string: &str) -> MLE<Self> { 55 fn from(config: Cfg, input: Vec<String>) -> MLE<Self> {
122 let cmd = match string { 56 let input_string = input.join(" ");
123 "add" => Self::Add, 57 let mut args: Vec<&str> = input_string.split(" -").collect();
124 "remove" => Self::Remove, 58 args[0] = args[0].split_at(1).1;
125 "change" => Self::Change, 59
126 "version" => Self::Version, 60 let mut command: Option<Cmd> = None;
127 "export" => Self::Export, 61
128 "import" => Self::Import, 62 let mut mod_options: Option<ModOptions> = None;
129 _ => return Err(MLError::new(ErrorType::ArgumentError, "SUBCMD_NOT_FOUND")) 63 let mut mod_id: Option<String> = None;
130 }; 64 let mut mod_version: Option<String> = None;
131 Ok(cmd) 65 let mut set_version = false;
66 let mut all_lists = false;
67 let mut clean = false;
68 let mut direct_download = true;
69 let mut delete_old = false;
70 let mut list: Option<List> = None;
71 let mut list_options: Option<ListOptions> = None;
72 let mut list_id: Option<String> = None;
73 let mut list_mcversion: Option<String> = None;
74 let mut modloader: Option<Modloader> = None;
75 let mut directory: Option<String> = None;
76 let mut io_options: Option<IoOptions> = None;
77 let mut file: Option<String> = None;
78
79 for arg in args {
80 let arg_split: Vec<&str> = arg.trim().split(" ").collect();
81 match arg_split[0] {
82 "v" | "version" => {
83 command = Some(Cmd::Version);
84 },
85 "d" | "download" => {
86 command = Some(Cmd::Download);
87 },
88 "u" | "update" => {
89 command = Some(Cmd::Update);
90 },
91 "ma" => {
92 command = Some(Cmd::Mod);
93 mod_options = Some(ModOptions::Add);
94 if arg_split.len() == 2 {
95 mod_id = Some(String::from(arg_split[1]));
96 } else {
97 return Err(MLError::new(ErrorType::ArgumentError, "Please specify a list mod slug or id"));
98 }
99 },
100 "mv" => {
101 command = Some(Cmd::Mod);
102 mod_options = Some(ModOptions::Add);
103 if arg_split.len() == 2 {
104 mod_version = Some(String::from(arg_split[1]));
105 } else {
106 return Err(MLError::new(ErrorType::ArgumentError, "Please specify a version id"));
107 };
108 },
109 "mr" => {
110 command = Some(Cmd::Mod);
111 mod_options = Some(ModOptions::Remove);
112 if arg_split.len() == 2 {
113 mod_id = Some(String::from(arg_split[1]));
114 } else {
115 return Err(MLError::new(ErrorType::ArgumentError, "Please specify a mod id"));
116 };
117 },
118 "set_version" => {
119 set_version = true;
120 },
121 "all_lists" => {
122 all_lists = true;
123 },
124 "clean" => {
125 clean = true;
126 },
127 "no_download" => {
128 direct_download = false;
129 },
130 "delete_old" => {
131 delete_old = true;
132 },
133 "l" => {
134 if arg_split.len() == 2 {
135 list = Some(lists_get(config.clone(), String::from(arg_split[1]))?);
136 } else {
137 return Err(MLError::new(ErrorType::ArgumentError, "Please specify a list via it's id"));
138 }
139 }
140 "la" => {
141 command = Some(Cmd::List);
142 list_options = Some(ListOptions::Add);
143 if arg_split.len() == 2 {
144 list_id = Some(String::from(arg_split[1]));
145 } else {
146 return Err(MLError::new(ErrorType::ArgumentError, "Please give the new list an id"));
147 }
148 },
149 "lr" => {
150 command = Some(Cmd::List);
151 list_options = Some(ListOptions::Remove);
152 },
153 "lc" => {
154 command = Some(Cmd::List);
155 list_options = Some(ListOptions::Change);
156 },
157 "lv" => {
158 command = Some(Cmd::List);
159 list_options = Some(ListOptions::Version);
160 if arg_split.len() == 2 {
161 list_mcversion = Some(String::from(arg_split[1]));
162 } else {
163 return Err(MLError::new(ErrorType::ArgumentError, "Please specify a minecraft version"));
164 }
165 },
166 "mcv" => {
167 if arg_split.len() == 2 {
168 list_mcversion = Some(String::from(arg_split[1]));
169 } else {
170 return Err(MLError::new(ErrorType::ArgumentError, "Please specify a minecraft version"));
171 }
172 },
173 "ml" => {
174 if arg_split.len() == 2 {
175 modloader = Some(Modloader::from(arg_split[1])?);
176 } else {
177 return Err(MLError::new(ErrorType::ArgumentError, "Please specify a modloader"));
178 }
179 },
180 "dir" => {
181 if arg_split.len() == 2 {
182 directory = Some(String::from(arg_split[1]));
183 } else {
184 return Err(MLError::new(ErrorType::ArgumentError, "Please specify a directory"));
185 }
186 },
187 "export" => {
188 command = Some(Cmd::Io);
189 io_options = Some(IoOptions::Export);
190 },
191 "import" => {
192 command = Some(Cmd::Io);
193 io_options = Some(IoOptions::Import);
194 },
195 "f" => {
196 file = Some(String::from(arg_split[1]));
197 },
198 _ => return Err(MLError::new(ErrorType::ArgumentError, format!("Unknown Argument ({})", arg_split[0]).as_str())),
199 }
200 }
201
202 Ok(Self {
203 command,
204 mod_options,
205 mod_id,
206 mod_version,
207 set_version,
208 all_lists,
209 clean,
210 direct_download,
211 delete_old,
212 list,
213 list_options,
214 list_id,
215 list_mcversion,
216 modloader,
217 directory,
218 io_options,
219 file
220 })
132 } 221 }
133} 222}
134 223
135pub async fn get_input(config: Cfg) -> Result<(), Box<dyn std::error::Error>> { 224pub async fn get_input(config: Cfg, args: Vec<String>) -> MLE<Input> {
136 let mut args: Vec<String> = env::args().collect(); 225 let input = Input::from(config.clone(), args)?;
137 args.reverse(); 226
138 args.pop(); 227 if input.command.is_none() { return Err(MLError::new(ErrorType::ArgumentError, "No command specified")); };
139 args.reverse();
140 228
141 let input = Input::from(&args.join(" "))?; 229 match input.clone().command.unwrap() {
230 Cmd::Mod => check_mod(input, config),
231 Cmd::List => check_list(input, config).await,
232 _ => Ok(input),
233 }
234}
142 235
143 match input.command { 236fn check_mod(mut input: Input, config: Cfg) -> MLE<Input> {
144 Cmd::Mod => { 237 if input.mod_options.is_none() {
145 modification(config, input).await 238 return Err(MLError::new(ErrorType::ArgumentError, "No mod option"));
239 };
240 match input.clone().mod_options.unwrap() {
241 ModOptions::Add => {
242 if input.mod_id.is_none() && input.mod_version.is_none() { return Err(MLError::new(ErrorType::ArgumentError, "No mod id/slug or version id")); };
243 if input.list_id.is_none() { input.list = Some(get_current_list(config.clone())?); };
244 Ok(input)
146 }, 245 },
147 Cmd::List => { 246 ModOptions::Remove => {
148 list(config, input).await 247 if input.mod_id.is_none() { return Err(MLError::new(ErrorType::ArgumentError, "MODS_NO_MODID")); };
248 Ok(input)
149 }, 249 },
150 Cmd::Update => { 250 }
151 match update(config, input).await { 251}
152 Ok(..) => Ok(()), 252
153 Err(..) => Err(Box::new(MLError::new(ErrorType::Other, "UPDATE_ERR"))) 253async fn check_list(mut input: Input, config: Cfg) -> MLE<Input> {
154 } 254 if input.list_options.is_none() {
255 return Err(MLError::new(ErrorType::ArgumentError, "NO_LIST_ARGUMENT"));
256 };
257 match input.clone().list_options.unwrap() {
258 ListOptions::Add => {
259 if input.list_id.is_none() { return Err(MLError::new(ErrorType::ArgumentError, "no list id specified")); };
260 if input.list_mcversion.is_none() {
261 println!("No Minecraft Version specified, defaulting to latest release");
262 input.list_mcversion = Some(get_minecraft_version(config.apis.modrinth, MCVersionType::Release).await);
263 };
264 if input.directory.is_none() {
265 let id = input.clone().list_id.unwrap();
266 println!("No download directory specified, defaulting to ./downloads/{}", id);
267 input.directory = Some(format!("./downloads/{}", id))
268 };
269 if input.modloader.is_none() { return Err(MLError::new(ErrorType::ArgumentError, "no modloader specified")); };
270 Ok(input)
155 }, 271 },
156 Cmd::Setup => { 272 ListOptions::Remove => {
157 setup(config).await 273 if input.list.is_none() { return Err(MLError::new(ErrorType::ArgumentError, "NO_LIST_SPECIFIED")); };
274 Ok(input)
158 }, 275 },
159 Cmd::Download => { 276 ListOptions::Change => {
160 download(config, input).await 277 //TODO check if no change
278 if input.list.is_none() { return Err(MLError::new(ErrorType::ArgumentError, "NO_LIST_SPECIFIED")); };
279 Ok(input)
161 }, 280 },
162 Cmd::Io => { 281 ListOptions::Version => {
163 io(config, input).await 282 if input.list.is_none() {
283 println!("No list specified, using default");
284 input.list = Some(get_current_list(config)?);
285 };
286 Ok(input)
164 } 287 }
165 } 288 }
166} 289}
167 290
168#[test] 291#[test]
169fn input_from() { 292fn input_from() {
170 let string = "list add test 1.19.2 fabric"; 293 let config = Cfg::init("modlist.toml").unwrap();
171 let input = Input{ command: Cmd::List, subcommand: Some(Subcmd::Add), args: Some(vec![String::from("test"), String::from("1.19.2"), String::from("fabric")]), direct_download: false, all_lists: false, clean: false, delete_old: false, disable_download: false, version: false }; 294 assert_eq!(
172 assert_eq!(Input::from(string).unwrap(), input); 295 Input::from(config.clone(), vec![String::from("-la test -lv 1.19.3")]).unwrap(),
296 Input {
297 command: Some(Cmd::List),
298 mod_options: None,
299 mod_id: None,
300 mod_version: None,
301 set_version: false,
302 all_lists: false,
303 clean: false,
304 direct_download: false,
305 delete_old: false,
306 list: None,
307 list_options: Some(ListOptions::Add),
308 list_id: Some(String::from("test")),
309 list_mcversion: Some(String::from("1.19.3")),
310 modloader: None,
311 directory: None,
312 io_options: None,
313 file: None
314 }
315 );
173 316
174 let string = "update --direct-download --delete-old"; 317}
175 let input = Input{ command: Cmd::Update, subcommand: None, args: None, direct_download: true, all_lists: false, clean: false, delete_old: true, disable_download: false, version: false }; 318
176 assert_eq!(Input::from(string).unwrap(), input); 319#[tokio::test]
320async fn get_input_test() {
321 let config = Cfg::init("modlist.toml").unwrap();
322 assert_eq!(
323 get_input(config.clone(), vec![String::from("-ma test")]).await.unwrap(),
324 Input {
325 command: Some(Cmd::Mod),
326 mod_options: Some(ModOptions::Add),
327 mod_id: Some(String::from("test")),
328 mod_version: None,
329 set_version: false,
330 all_lists: false,
331 clean: false,
332 direct_download: false,
333 delete_old: false,
334 list: Some(lists_get(config.clone(), String::from("one")).unwrap()),
335 list_options: None,
336 list_id: None,
337 list_mcversion: None,
338 modloader: None,
339 directory: None,
340 io_options: None,
341 file: None
342 }
343 )
177} 344}
diff --git a/src/main.rs b/src/main.rs
index 59d41c5..d177c3e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,13 +1,59 @@
1use modlist::{config::Cfg, input::get_input}; 1use std::{env, process};
2
3use modlist::{config::Cfg, input::{get_input, Cmd}, update, download, list, io, modification};
2 4
3#[tokio::main] 5#[tokio::main]
4async fn main() { 6async fn main() {
5 let config = Cfg::init("modlist.toml").unwrap(); 7 let config = Cfg::init("modlist.toml").unwrap();
6 8
7 match get_input(config).await { 9 let mut args: Vec<String> = env::args().collect();
8 Ok(..) => (), 10 args.reverse();
11 args.pop();
12 args.reverse();
13
14 let input = match get_input(config.clone(), args).await {
15 Ok(i) => i,
9 Err(e) => { 16 Err(e) => {
10 println!("{}", e); 17 println!("{}", e);
18 process::exit(1);
11 } 19 }
12 }; 20 };
21
22 //dbg!(&input);
23
24 match input.clone().command.unwrap() {
25 Cmd::Mod => {
26 modification(config, input).await
27 },
28 Cmd::List => {
29 list(config, input).await
30 },
31 Cmd::Update => {
32 update(config, input).await
33 },
34 Cmd::Download => {
35 download(config, input).await
36 },
37 Cmd::Io => {
38 io(config, input).await
39 },
40 Cmd::Version => {
41 show_version();
42 Ok(())
43 },
44 }.unwrap()
45}
46
47fn show_version() {
48 match std::env::var("DEV") {
49 Ok(dev) => {
50 let devint = dev.parse::<i32>().unwrap();
51 if devint >= 1 {
52 println!("Modlist by FxQnLr v{} (DEV)", env!("CARGO_PKG_VERSION"));
53 } else {
54 println!("Modlist by FxQnLr v{}", env!("CARGO_PKG_VERSION"));
55 }
56 },
57 Err(..) => println!("Modlist by FxQnLr v{}", env!("CARGO_PKG_VERSION")),
58 }
13} 59}