1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use crate::constants::HELP_KEYS;
use crate::runners::helper::make_node_help;
use crate::runners::main_executor;
use crate::utils::print_n_exit;

use mddd_traits::IRunner;

pub struct NodeRunner {
    description: String,
    runners: Vec<(String, Box<dyn IRunner>)>,
}

impl NodeRunner {
    pub fn new(description: impl ToString) -> Self {
        Self {
            description: description.to_string(),
            runners: Vec::new(),
        }
    }

    pub fn add(mut self, cmd: impl ToString, runner: impl IRunner + 'static) -> Self {
        self.runners.push((cmd.to_string(), Box::new(runner)));
        self
    }

    pub fn add_box(mut self, cmd: impl ToString, runner: Box<dyn IRunner>) -> Self {
        self.runners.push((cmd.to_string(), runner));
        self
    }

    pub fn run(self) {
        main_executor::run(self)
    }

    fn execute_command(&mut self, prefix: &str, cmd: &str, args: &[&str]) {
        let found = self.runners.iter_mut().find(|(key, _)| key == cmd);
        let child = match found {
            Some((_, val)) => val,
            None => print_n_exit(&format!("Invalid command: {}", cmd)),
        };
        let prefix = format!("{} {}", prefix, cmd);
        child.execute(&prefix, args)
    }
}

impl IRunner for NodeRunner {
    fn short_description(&self) -> String {
        self.description.clone()
    }

    fn execute(&mut self, prefix: &str, args: &[&str]) {
        if args.is_empty() || HELP_KEYS.contains(&args[0]) {
            let help = make_node_help(prefix, &self.short_description(), &self.runners);
            println!("{}", help);
        } else {
            self.execute_command(prefix, args[0], &args[1..])
        }
    }
}