diff options
Diffstat (limited to 'src/input.rs')
-rw-r--r-- | src/input.rs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/src/input.rs b/src/input.rs new file mode 100644 index 0000000..689389e --- /dev/null +++ b/src/input.rs | |||
@@ -0,0 +1,59 @@ | |||
1 | use std::io::{stdin, Error, ErrorKind}; | ||
2 | use crate::{add, config::Cfg}; | ||
3 | |||
4 | pub struct Input { | ||
5 | pub command: String, | ||
6 | pub args: Option<Vec<String>>, | ||
7 | } | ||
8 | |||
9 | impl Input { | ||
10 | pub fn from(string: String) -> Result<Self, Box<dyn std::error::Error>> { | ||
11 | let mut split: Vec<&str> = string.split(' ').collect(); | ||
12 | |||
13 | let command: String; | ||
14 | let mut args: Option<Vec<String>> = None; | ||
15 | |||
16 | if split[0].is_empty() { split.remove(0); }; | ||
17 | |||
18 | dbg!(&split); | ||
19 | |||
20 | match split.len() { | ||
21 | 0 => { Err(Box::new(Error::new(ErrorKind::InvalidInput, "NO_ARGS"))) } | ||
22 | 1 => Ok( Input { command: split[0].to_string(), args }), | ||
23 | 2.. => { | ||
24 | command = split[0].to_string(); | ||
25 | split.remove(0); | ||
26 | let mut str_args: Vec<String> = vec![]; | ||
27 | for e in split { | ||
28 | str_args.push(e.to_string()); | ||
29 | } | ||
30 | args = Some(str_args); | ||
31 | Ok(Input { command, args }) | ||
32 | }, | ||
33 | _ => { panic!("This should never happen") } | ||
34 | } | ||
35 | |||
36 | |||
37 | } | ||
38 | } | ||
39 | |||
40 | pub async fn get_input(config: Cfg) -> Result<(), Box<dyn std::error::Error>> { | ||
41 | let mut user_input = String::new(); | ||
42 | stdin() | ||
43 | .read_line(&mut user_input) | ||
44 | .expect("ERROR"); | ||
45 | |||
46 | dbg!(&user_input); | ||
47 | |||
48 | let input = Input::from(user_input.trim().to_string())?; | ||
49 | |||
50 | match input.command.as_str() { | ||
51 | "add" => { | ||
52 | if input.args == None { return Err(Box::new(Error::new(ErrorKind::InvalidInput, "TOO_FEW_ARGUMENTS"))) }; | ||
53 | if input.args.as_ref().unwrap().len() != 1 { return Err(Box::new(Error::new(ErrorKind::InvalidInput, "TOO_MANY_ARGUMENTS"))) }; | ||
54 | add(config, input.args.unwrap()[0].to_string()).await?; | ||
55 | Ok(()) | ||
56 | }, | ||
57 | _ => Err(Box::new(Error::new(ErrorKind::InvalidInput, "UNKNOWN_COMMAND"))), | ||
58 | } | ||
59 | } | ||