dynamic-cli 0.2.0

A framework for building configurable CLI and REPL applications from YAML/JSON configuration files
Documentation
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! CLI (Command-Line Interface) implementation
//!
//! This module provides a simple CLI interface that parses command-line
//! arguments, executes the corresponding command, and exits.
//!
//! # Example
//!
//! ```no_run
//! use dynamic_cli::interface::CliInterface;
//! use dynamic_cli::prelude::*;
//!
//! # #[derive(Default)]
//! # struct MyContext;
//! # impl ExecutionContext for MyContext {
//! #     fn as_any(&self) -> &dyn std::any::Any { self }
//! #     fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self }
//! # }
//! # fn main() -> dynamic_cli::Result<()> {
//! let registry = CommandRegistry::new();
//! let context = Box::new(MyContext::default());
//!
//! let cli = CliInterface::new(registry, context);
//! cli.run(std::env::args().skip(1).collect())?;
//! # Ok(())
//! # }
//! ```

use crate::context::ExecutionContext;
use crate::error::{display_error, DynamicCliError, Result};
use crate::parser::CliParser;
use crate::registry::CommandRegistry;
use std::process;

/// CLI (Command-Line Interface) handler
///
/// Provides a simple interface for executing commands from command-line arguments.
/// The CLI parses arguments, executes the command, and exits.
///
/// # Architecture
///
/// ```text
/// Command-line args → CliParser → CommandExecutor → Handler
//////                                  ExecutionContext
/// ```
///
/// # Error Handling
///
/// Errors are displayed to stderr with colored formatting (if enabled)
/// and the process exits with appropriate exit codes:
/// - `0`: Success
/// - `1`: Execution error
/// - `2`: Argument parsing error
/// - `3`: Other errors
pub struct CliInterface {
    /// Command registry containing all available commands
    registry: CommandRegistry,

    /// Execution context (owned by the interface)
    context: Box<dyn ExecutionContext>,
}

impl CliInterface {
    /// Create a new CLI interface
    ///
    /// # Arguments
    ///
    /// * `registry` - Command registry with all registered commands
    /// * `context` - Execution context (will be consumed by the interface)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use dynamic_cli::interface::CliInterface;
    /// use dynamic_cli::prelude::*;
    ///
    /// # #[derive(Default)]
    /// # struct MyContext;
    /// # impl ExecutionContext for MyContext {
    /// #     fn as_any(&self) -> &dyn std::any::Any { self }
    /// #     fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self }
    /// # }
    /// let registry = CommandRegistry::new();
    /// let context = Box::new(MyContext::default());
    ///
    /// let cli = CliInterface::new(registry, context);
    /// ```
    pub fn new(registry: CommandRegistry, context: Box<dyn ExecutionContext>) -> Self {
        Self { registry, context }
    }

    /// Run the CLI with provided arguments
    ///
    /// Parses the arguments, executes the corresponding command, and handles errors.
    /// This method consumes `self` as the CLI typically runs once and exits.
    ///
    /// # Arguments
    ///
    /// * `args` - Command-line arguments (typically from `env::args().skip(1)`)
    ///
    /// # Returns
    ///
    /// - `Ok(())` on success
    /// - `Err(DynamicCliError)` on any error (parsing, validation, execution)
    ///
    /// # Exit Codes
    ///
    /// The caller should handle errors and exit with appropriate codes:
    /// - Parse errors → exit code 2
    /// - Execution errors → exit code 1
    /// - Other errors → exit code 3
    ///
    /// # Example
    ///
    /// ```no_run
    /// use dynamic_cli::interface::CliInterface;
    /// use dynamic_cli::prelude::*;
    /// use std::process;
    ///
    /// # #[derive(Default)]
    /// # struct MyContext;
    /// # impl ExecutionContext for MyContext {
    /// #     fn as_any(&self) -> &dyn std::any::Any { self }
    /// #     fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self }
    /// # }
    /// # fn main() {
    /// let registry = CommandRegistry::new();
    /// let context = Box::new(MyContext::default());
    /// let cli = CliInterface::new(registry, context);
    ///
    /// if let Err(e) = cli.run(std::env::args().skip(1).collect()) {
    ///     eprintln!("Error: {}", e);
    ///     process::exit(1);
    /// }
    /// # }
    /// ```
    pub fn run(mut self, args: Vec<String>) -> Result<()> {
        // Handle empty arguments (show help or error)
        if args.is_empty() {
            return Err(DynamicCliError::Parse(
                crate::error::ParseError::InvalidSyntax {
                    details: "No command specified".to_string(),
                    hint: Some("Try 'help' to see available commands".to_string()),
                },
            ));
        }

        // First argument is the command name
        let command_name = &args[0];

        // Resolve command name (handles aliases)
        let resolved_name = self.registry.resolve_name(command_name).ok_or_else(|| {
            crate::error::ParseError::unknown_command_with_suggestions(
                command_name,
                &self
                    .registry
                    .list_commands()
                    .iter()
                    .map(|cmd| cmd.name.clone())
                    .collect::<Vec<_>>(),
            )
        })?;

        // Get command definition
        let definition = self.registry.get_definition(resolved_name).ok_or_else(|| {
            DynamicCliError::Registry(crate::error::RegistryError::missing_handler(resolved_name))
        })?;

        // Parse arguments using CLI parser
        let parser = CliParser::new(definition);
        let parsed_args = parser.parse(&args[1..])?;

        // Get handler and execute command
        let handler = self.registry.get_handler(resolved_name).ok_or_else(|| {
            DynamicCliError::Execution(crate::error::ExecutionError::handler_not_found(
                resolved_name,
                &definition.implementation,
            ))
        })?;

        handler.execute(&mut *self.context, &parsed_args)?;

        Ok(())
    }

    /// Run the CLI with automatic error handling and exit
    ///
    /// This is a convenience method that:
    /// 1. Runs the CLI with provided arguments
    /// 2. Handles errors by displaying them to stderr
    /// 3. Exits the process with appropriate exit code
    ///
    /// This method never returns.
    ///
    /// # Arguments
    ///
    /// * `args` - Command-line arguments
    ///
    /// # Example
    ///
    /// ```no_run
    /// use dynamic_cli::interface::CliInterface;
    /// use dynamic_cli::prelude::*;
    ///
    /// # #[derive(Default)]
    /// # struct MyContext;
    /// # impl ExecutionContext for MyContext {
    /// #     fn as_any(&self) -> &dyn std::any::Any { self }
    /// #     fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self }
    /// # }
    /// # fn main() {
    /// let registry = CommandRegistry::new();
    /// let context = Box::new(MyContext::default());
    /// let cli = CliInterface::new(registry, context);
    ///
    /// // This will handle errors and exit automatically
    /// cli.run_and_exit(std::env::args().skip(1).collect());
    /// # }
    /// ```
    pub fn run_and_exit(self, args: Vec<String>) -> ! {
        match self.run(args) {
            Ok(()) => process::exit(0),
            Err(e) => {
                display_error(&e);

                // Exit with appropriate code based on error type
                let exit_code = match e {
                    DynamicCliError::Parse(_) => 2,
                    DynamicCliError::Validation(_) => 2,
                    DynamicCliError::Execution(_) => 1,
                    _ => 3,
                };

                process::exit(exit_code);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::schema::{ArgumentDefinition, ArgumentType, CommandDefinition};
    use std::collections::HashMap;

    // Test context
    #[derive(Default)]
    struct TestContext {
        executed_command: Option<String>,
    }

    impl ExecutionContext for TestContext {
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }

        fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
            self
        }
    }

    // Test handler
    struct TestHandler {
        name: String,
    }

    impl crate::executor::CommandHandler for TestHandler {
        fn execute(
            &self,
            context: &mut dyn ExecutionContext,
            _args: &HashMap<String, String>,
        ) -> Result<()> {
            let ctx = crate::context::downcast_mut::<TestContext>(context)
                .expect("Failed to downcast context");
            ctx.executed_command = Some(self.name.clone());
            Ok(())
        }
    }

    fn create_test_registry() -> CommandRegistry {
        let mut registry = CommandRegistry::new();

        // Create a simple command definition
        let cmd_def = CommandDefinition {
            name: "test".to_string(),
            aliases: vec!["t".to_string()],
            description: "Test command".to_string(),
            required: false,
            arguments: vec![],
            options: vec![],
            implementation: "test_handler".to_string(),
        };

        let handler = Box::new(TestHandler {
            name: "test".to_string(),
        });

        registry
            .register(cmd_def, handler)
            .expect("Failed to register command");

        registry
    }

    #[test]
    fn test_cli_interface_creation() {
        let registry = create_test_registry();
        let context = Box::new(TestContext::default());

        let _cli = CliInterface::new(registry, context);
        // If this compiles and runs, creation works
    }

    #[test]
    fn test_cli_run_simple_command() {
        let registry = create_test_registry();
        let context = Box::new(TestContext::default());
        let cli = CliInterface::new(registry, context);

        let result = cli.run(vec!["test".to_string()]);
        assert!(result.is_ok());
    }

    #[test]
    fn test_cli_run_with_alias() {
        let registry = create_test_registry();
        let context = Box::new(TestContext::default());
        let cli = CliInterface::new(registry, context);

        let result = cli.run(vec!["t".to_string()]);
        assert!(result.is_ok());
    }

    #[test]
    fn test_cli_empty_args() {
        let registry = create_test_registry();
        let context = Box::new(TestContext::default());
        let cli = CliInterface::new(registry, context);

        let result = cli.run(vec![]);
        assert!(result.is_err());

        match result.unwrap_err() {
            DynamicCliError::Parse(crate::error::ParseError::InvalidSyntax { .. }) => {}
            other => panic!("Expected InvalidSyntax error, got: {:?}", other),
        }
    }

    #[test]
    fn test_cli_unknown_command() {
        let registry = create_test_registry();
        let context = Box::new(TestContext::default());
        let cli = CliInterface::new(registry, context);

        let result = cli.run(vec!["unknown".to_string()]);
        assert!(result.is_err());

        match result.unwrap_err() {
            DynamicCliError::Parse(crate::error::ParseError::UnknownCommand { .. }) => {}
            other => panic!("Expected UnknownCommand error, got: {:?}", other),
        }
    }

    #[test]
    fn test_cli_command_with_args() {
        let mut registry = CommandRegistry::new();

        // Command with argument
        let cmd_def = CommandDefinition {
            name: "greet".to_string(),
            aliases: vec![],
            description: "Greet someone".to_string(),
            required: false,
            arguments: vec![ArgumentDefinition {
                name: "name".to_string(),
                arg_type: ArgumentType::String,
                required: true,
                description: "Name to greet".to_string(),
                validation: vec![],
            }],
            options: vec![],
            implementation: "greet_handler".to_string(),
        };

        struct GreetHandler;
        impl crate::executor::CommandHandler for GreetHandler {
            fn execute(
                &self,
                _context: &mut dyn ExecutionContext,
                args: &HashMap<String, String>,
            ) -> Result<()> {
                assert_eq!(args.get("name"), Some(&"Alice".to_string()));
                Ok(())
            }
        }

        registry.register(cmd_def, Box::new(GreetHandler)).unwrap();

        let context = Box::new(TestContext::default());
        let cli = CliInterface::new(registry, context);

        let result = cli.run(vec!["greet".to_string(), "Alice".to_string()]);
        assert!(result.is_ok());
    }
}