Skip to main content

cli_core/
commands.rs

1use server::command::{Argument, CmdError, CmdResult, config::SelectColumn};
2use std::collections::HashMap;
3use std::fmt::Debug;
4use std::future::Future;
5use std::pin::Pin;
6use thiserror::Error;
7
8pub trait CliRunnable: Debug + Send {
9    fn run<'a>(
10        &'a self,
11        args: &'a HashMap<&str, &Argument>,
12    ) -> Pin<Box<dyn Future<Output = Result<Option<CmdResult>, CommandError>> + Send + 'a>>;
13}
14
15#[derive(Debug)]
16pub struct CommandNode {
17    pub name: String,
18    pub is_leaf: bool,
19    pub subcommands: Vec<CommandNode>,
20}
21
22#[derive(Debug, Error)]
23pub enum CommandError {
24    #[error("{0}")]
25    Command(String),
26    #[error("Arguments error: {0}")]
27    Argument(String),
28    #[error("Execution: {0}")]
29    Execution(#[from] CmdError),
30    #[error("{}", .0.join("\n"))]
31    FormInvalid(Vec<String>),
32}
33
34pub trait CliCommand: Debug + Send {
35    fn node() -> CommandNode;
36}
37
38#[derive(Debug)]
39pub struct CliGetConfig;
40
41impl CliCommand for CliGetConfig {
42    fn node() -> CommandNode {
43        CommandNode {
44            name: "get".to_string(),
45            is_leaf: true,
46            subcommands: vec![],
47        }
48    }
49}
50
51#[derive(Debug)]
52pub struct CliSetConfig;
53
54impl CliCommand for CliSetConfig {
55    fn node() -> CommandNode {
56        CommandNode {
57            name: "set".to_string(),
58            is_leaf: true,
59            subcommands: vec![],
60        }
61    }
62}
63
64#[derive(Debug)]
65pub struct CliVersion;
66
67impl CliCommand for CliVersion {
68    fn node() -> CommandNode {
69        CommandNode {
70            name: "version".to_string(),
71            is_leaf: true,
72            subcommands: vec![],
73        }
74    }
75}
76
77#[derive(Debug)]
78pub struct CliSelectColumn;
79
80impl CliRunnable for CliSelectColumn {
81    fn run<'a>(
82        &'a self,
83        args: &'a HashMap<&str, &Argument>,
84    ) -> Pin<Box<dyn Future<Output = Result<Option<CmdResult>, CommandError>> + Send + 'a>> {
85        Box::pin(async move {
86            match (args.get("field"), args.get("table")) {
87                (Some(Argument::String(field)), Some(Argument::String(table))) => {
88                    Ok(SelectColumn::new()
89                        .field(field.clone())
90                        .table(table.clone())
91                        .run()
92                        .await?)
93                }
94                _ => Err(CommandError::Argument(
95                    "No column or table provided".to_string(),
96                )),
97            }
98        })
99    }
100}
101
102#[derive(Debug)]
103pub struct CliCommodityCreate;
104
105impl CliCommand for CliCommodityCreate {
106    fn node() -> CommandNode {
107        CommandNode {
108            name: "create".to_string(),
109            is_leaf: true,
110            subcommands: vec![],
111        }
112    }
113}
114
115#[derive(Debug)]
116pub struct CliCommodityList;
117
118impl CliCommand for CliCommodityList {
119    fn node() -> CommandNode {
120        CommandNode {
121            name: "list".to_string(),
122            is_leaf: true,
123            subcommands: vec![],
124        }
125    }
126}
127
128#[derive(Debug)]
129pub struct CliAccountCreate;
130
131impl CliCommand for CliAccountCreate {
132    fn node() -> CommandNode {
133        CommandNode {
134            name: "create".to_string(),
135            is_leaf: true,
136            subcommands: vec![],
137        }
138    }
139}
140
141#[derive(Debug)]
142pub struct CliAccountList;
143
144impl CliCommand for CliAccountList {
145    fn node() -> CommandNode {
146        CommandNode {
147            name: "list".to_string(),
148            is_leaf: true,
149            subcommands: vec![],
150        }
151    }
152}
153
154#[derive(Debug)]
155pub struct CliTransactionCreate;
156
157impl CliCommand for CliTransactionCreate {
158    fn node() -> CommandNode {
159        CommandNode {
160            name: "create".to_string(),
161            is_leaf: true,
162            subcommands: vec![],
163        }
164    }
165}
166
167#[derive(Debug)]
168pub struct CliTransactionList;
169
170impl CliCommand for CliTransactionList {
171    fn node() -> CommandNode {
172        CommandNode {
173            name: "list".to_string(),
174            is_leaf: true,
175            subcommands: vec![],
176        }
177    }
178}
179
180#[derive(Debug)]
181pub struct CliAccountBalance;
182
183impl CliCommand for CliAccountBalance {
184    fn node() -> CommandNode {
185        CommandNode {
186            name: "balance".to_string(),
187            is_leaf: true,
188            subcommands: vec![],
189        }
190    }
191}
192
193#[derive(Debug)]
194pub struct CliListDataFindings;
195
196impl CliRunnable for CliListDataFindings {
197    fn run<'a>(
198        &'a self,
199        args: &'a HashMap<&str, &Argument>,
200    ) -> Pin<Box<dyn Future<Output = Result<Option<CmdResult>, CommandError>> + Send + 'a>> {
201        Box::pin(async move {
202            let mut cmd = server::command::data_findings::ListDataFindings::new();
203            if let Some(Argument::String(kind)) = args.get("kind") {
204                cmd = cmd.kind(kind.clone());
205            }
206            Ok(cmd.run().await?)
207        })
208    }
209}
210
211#[derive(Debug)]
212pub struct CliSshKeyRemove;
213
214impl CliCommand for CliSshKeyRemove {
215    fn node() -> CommandNode {
216        CommandNode {
217            name: "remove".to_string(),
218            is_leaf: true,
219            subcommands: vec![],
220        }
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    fn block_on<F: Future>(f: F) -> F::Output {
229        tokio::runtime::Builder::new_current_thread()
230            .enable_all()
231            .build()
232            .expect("runtime")
233            .block_on(f)
234    }
235
236    #[test]
237    fn select_column_rejects_missing_table() {
238        let field = Argument::String("foo".to_string());
239        let mut args: HashMap<&str, &Argument> = HashMap::new();
240        args.insert("field", &field);
241        let err = block_on(CliSelectColumn.run(&args)).expect_err("missing table should error");
242        assert!(matches!(err, CommandError::Argument(_)));
243    }
244}