use std::env;
use crate::{config::Cfg, list, modification, update, setup, download, error::{MLError, ErrorType, MLE}};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Input {
pub command: Cmd,
pub subcommand: Option<Subcmd>,
pub args: Option<Vec<String>>,
pub direct_download: bool,
pub force_download: bool,
pub all_lists: bool,
pub delete_old: bool,
pub clean: bool,
}
impl Input {
pub fn from(string: &str) -> MLE<Self> {
let mut split: Vec<&str> = string.split(' ').collect();
let mut direct_download = false;
let mut force_download = false;
let mut all_lists = false;
let mut delete_old = false;
let mut clean = false;
for (i, input) in split.clone().into_iter().enumerate() {
if input.starts_with("--") {
match input {
"--direct-download" => direct_download = true,
"--force-download" => force_download = true,
"--all_lists" => all_lists = true,
"--delete_old" => delete_old = true,
"--clean" => clean = true,
_ => continue,
}
split.remove(i);
}
}
let command = Cmd::from(split.remove(0))?;
let subcommand = match split.is_empty() {
false => Some(Subcmd::from(split.remove(0))?),
true => None
};
let args = match split.is_empty() {
true => None,
false => {
let mut strsplit: Vec<String> = Vec::new();
for s in split {
strsplit.push(String::from(s))
}
Some(strsplit)
}
};
Ok(Self { command, subcommand, args, direct_download, force_download, all_lists, delete_old, clean })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Cmd {
Mod,
List,
Update,
Download,
Setup
}
impl Cmd {
pub fn from(string: &str) -> MLE<Self> {
let cmd = match string {
"mod" => Self::Mod,
"list" => Self::List,
"update" => Self::Update,
"download" => Self::Download,
"setup" => Self::Setup,
_ => return Err(MLError::new(ErrorType::ArgumentError, "Unknown command"))
};
Ok(cmd)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Subcmd {
Add,
Remove,
Change
}
impl Subcmd {
fn from(string: &str) -> MLE<Self> {
let cmd = match string {
"add" => Self::Add,
"remove" => Self::Remove,
"change" => Self::Change,
_ => return Err(MLError::new(ErrorType::ArgumentError, "SUBCMD_NOT_FOUND"))
};
Ok(cmd)
}
}
pub async fn get_input(config: Cfg) -> Result<(), Box<dyn std::error::Error>> {
let mut args: Vec<String> = env::args().collect();
args.reverse();
args.pop();
args.reverse();
let input = Input::from(&args.join(" "))?;
match input.command {
Cmd::Mod => {
modification(config, input).await
},
Cmd::List => {
list(config, input)
},
Cmd::Update => {
update(config, input).await
},
Cmd::Setup => {
setup(config).await
},
Cmd::Download => {
download(config).await
}
}
}
#[test]
fn input_from() {
let string = "lis add test 1.19.2 fabric";
let input = Input{ command: Cmd::List, subcommand: Some(Subcmd::Add), args: Some(vec![String::from("test"), String::from("1.19.2"), String::from("fabric")]), force_download: false, direct_download: false, all_lists: false };
assert_eq!(Input::from(string).unwrap(), input);
}