rusty_cli/
runner.rs

1use std::env::Args;
2use crate::command_handler::{CommandHandler, CommandHandlerArguments};
3use crate::meta_data::ApplicationMetaData;
4use crate::option_resolver::clone_meta_data_option;
5
6type CustomExecutor = fn(arguments: Args);
7
8pub struct Runner {
9    command_handler: Option<CommandHandler>,
10    custom_executor: Option<CustomExecutor>,
11    meta_data: Option<ApplicationMetaData>
12}
13
14impl Runner {
15
16    /// Creates a new instance of the runner
17    /// and sets all default values
18    pub fn new() -> Self {
19        Runner {
20            command_handler: None,
21            custom_executor: None,
22            meta_data: None
23        }
24    }
25
26    /// Enables the internal command handler
27    /// And sets the provided arguments of the command handler
28    ///
29    /// NOTE: This method that should be executed as final step, because it
30    /// depends on steps before.
31    pub fn enable_command_handler(&mut self, config: CommandHandlerArguments) {
32        let mut handler = CommandHandler::new();
33        handler.set_args(CommandHandlerArguments {
34            commands: config.commands.to_vec(),
35            default_no_argument_callback: config.default_no_argument_callback,
36            flags: config.flags
37        });
38        handler.set_meta_data(clone_meta_data_option(&self.meta_data));
39        self.command_handler = Some(handler);
40    }
41
42    /// Sets the custom executor that can contain any argument based operation with the
43    /// system.
44    pub fn enable_custom_executor(&mut self, executor: CustomExecutor) {
45        self.custom_executor = Some(executor);
46    }
47
48    /// Sets the meta data of the application
49    pub fn set_meta_data(&mut self, data: ApplicationMetaData) {
50        self.meta_data = Some(data);
51    }
52
53    /// Executes the main runner. If there is a command handler
54    /// provided, the command handler will be used for executing the commands.
55    /// Otherwise a custom handler has been provided that is executed
56    pub fn run(&mut self) {
57        if self.command_handler.is_some() {
58            let mut handler = self.command_handler.as_ref().unwrap().clone();
59            handler.execute_command();
60        } else if self.custom_executor.is_some() {
61            self.custom_executor.unwrap()(std::env::args());
62        } else {
63            println!("You have to provide a custom executor or configure the internal command handler");
64        }
65    }
66}