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
use std::marker::PhantomData;
use std::mem;

use mddd_traits::{IRunner, IUseCase, IUseCaseRequest};

use crate::constants::HELP_KEYS;
use crate::runners::helper::make_leaf_help;
use crate::runners::main_executor;
use crate::utils::print_n_exit;

pub struct LeafRunner<UC, R, E> {
    constructor: Box<dyn FnOnce() -> UC>,
    phantom: PhantomData<(UC, R, E)>,
}

impl<R: IUseCaseRequest, E: std::fmt::Debug, UC: IUseCase<Request = R, Error = E>>
    LeafRunner<UC, R, E>
{
    pub fn new(constructor: impl FnOnce() -> UC + 'static) -> Self {
        Self {
            constructor: Box::new(constructor),
            phantom: PhantomData::default(),
        }
    }

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

impl<R: IUseCaseRequest, E: std::fmt::Debug, UC: IUseCase<Request = R, Error = E>> IRunner
    for LeafRunner<UC, R, E>
{
    fn short_description(&self) -> String {
        UC::short_description()
    }

    fn execute(&mut self, prefix: &str, args: &[&str]) {
        let plug: Box<dyn FnOnce() -> UC> = Box::new(|| -> UC { unreachable!() });
        let constructor = mem::replace(&mut self.constructor, plug);
        let mut uc: UC = constructor();
        if !args.is_empty() && HELP_KEYS.contains(&args[0]) {
            let help = make_leaf_help::<R, UC>(prefix, &uc);
            println!("{}", help);
            return;
        }
        let request = match R::build(args) {
            Ok(val) => val,
            Err(err) => print_n_exit(&err),
        };
        if let Err(err) = uc.execute(request) {
            print_n_exit(&format!("{:?}", err))
        }
    }
}