dynamic_cli/interface/cli.rs
1//! CLI (Command-Line Interface) implementation
2//!
3//! This module provides a simple CLI interface that parses command-line
4//! arguments, executes the corresponding command, and exits.
5//!
6//! # Example
7//!
8//! ```no_run
9//! use dynamic_cli::interface::CliInterface;
10//! use dynamic_cli::prelude::*;
11//!
12//! # #[derive(Default)]
13//! # struct MyContext;
14//! # impl ExecutionContext for MyContext {
15//! # fn as_any(&self) -> &dyn std::any::Any { self }
16//! # fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self }
17//! # }
18//! # fn main() -> dynamic_cli::Result<()> {
19//! let registry = CommandRegistry::new();
20//! let context = Box::new(MyContext::default());
21//!
22//! let cli = CliInterface::new(registry, context);
23//! cli.run(std::env::args().skip(1).collect())?;
24//! # Ok(())
25//! # }
26//! ```
27
28use crate::context::ExecutionContext;
29use crate::error::{display_error, DynamicCliError, Result};
30use crate::parser::CliParser;
31use crate::registry::CommandRegistry;
32use std::process;
33
34/// CLI (Command-Line Interface) handler
35///
36/// Provides a simple interface for executing commands from command-line arguments.
37/// The CLI parses arguments, executes the command, and exits.
38///
39/// # Architecture
40///
41/// ```text
42/// Command-line args → CliParser → CommandExecutor → Handler
43/// ↓
44/// ExecutionContext
45/// ```
46///
47/// # Error Handling
48///
49/// Errors are displayed to stderr with colored formatting (if enabled)
50/// and the process exits with appropriate exit codes:
51/// - `0`: Success
52/// - `1`: Execution error
53/// - `2`: Argument parsing error
54/// - `3`: Other errors
55pub struct CliInterface {
56 /// Command registry containing all available commands
57 registry: CommandRegistry,
58
59 /// Execution context (owned by the interface)
60 context: Box<dyn ExecutionContext>,
61}
62
63impl CliInterface {
64 /// Create a new CLI interface
65 ///
66 /// # Arguments
67 ///
68 /// * `registry` - Command registry with all registered commands
69 /// * `context` - Execution context (will be consumed by the interface)
70 ///
71 /// # Example
72 ///
73 /// ```no_run
74 /// use dynamic_cli::interface::CliInterface;
75 /// use dynamic_cli::prelude::*;
76 ///
77 /// # #[derive(Default)]
78 /// # struct MyContext;
79 /// # impl ExecutionContext for MyContext {
80 /// # fn as_any(&self) -> &dyn std::any::Any { self }
81 /// # fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self }
82 /// # }
83 /// let registry = CommandRegistry::new();
84 /// let context = Box::new(MyContext::default());
85 ///
86 /// let cli = CliInterface::new(registry, context);
87 /// ```
88 pub fn new(registry: CommandRegistry, context: Box<dyn ExecutionContext>) -> Self {
89 Self { registry, context }
90 }
91
92 /// Run the CLI with provided arguments
93 ///
94 /// Parses the arguments, executes the corresponding command, and handles errors.
95 /// This method consumes `self` as the CLI typically runs once and exits.
96 ///
97 /// # Arguments
98 ///
99 /// * `args` - Command-line arguments (typically from `env::args().skip(1)`)
100 ///
101 /// # Returns
102 ///
103 /// - `Ok(())` on success
104 /// - `Err(DynamicCliError)` on any error (parsing, validation, execution)
105 ///
106 /// # Exit Codes
107 ///
108 /// The caller should handle errors and exit with appropriate codes:
109 /// - Parse errors → exit code 2
110 /// - Execution errors → exit code 1
111 /// - Other errors → exit code 3
112 ///
113 /// # Example
114 ///
115 /// ```no_run
116 /// use dynamic_cli::interface::CliInterface;
117 /// use dynamic_cli::prelude::*;
118 /// use std::process;
119 ///
120 /// # #[derive(Default)]
121 /// # struct MyContext;
122 /// # impl ExecutionContext for MyContext {
123 /// # fn as_any(&self) -> &dyn std::any::Any { self }
124 /// # fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self }
125 /// # }
126 /// # fn main() {
127 /// let registry = CommandRegistry::new();
128 /// let context = Box::new(MyContext::default());
129 /// let cli = CliInterface::new(registry, context);
130 ///
131 /// if let Err(e) = cli.run(std::env::args().skip(1).collect()) {
132 /// eprintln!("Error: {}", e);
133 /// process::exit(1);
134 /// }
135 /// # }
136 /// ```
137 pub fn run(mut self, args: Vec<String>) -> Result<()> {
138 // Handle empty arguments (show help or error)
139 if args.is_empty() {
140 return Err(DynamicCliError::Parse(
141 crate::error::ParseError::InvalidSyntax {
142 details: "No command specified".to_string(),
143 hint: Some("Try 'help' to see available commands".to_string()),
144 },
145 ));
146 }
147
148 // First argument is the command name
149 let command_name = &args[0];
150
151 // Resolve command name (handles aliases)
152 let resolved_name = self.registry.resolve_name(command_name).ok_or_else(|| {
153 crate::error::ParseError::unknown_command_with_suggestions(
154 command_name,
155 &self
156 .registry
157 .list_commands()
158 .iter()
159 .map(|cmd| cmd.name.clone())
160 .collect::<Vec<_>>(),
161 )
162 })?;
163
164 // Get command definition
165 let definition = self.registry.get_definition(resolved_name).ok_or_else(|| {
166 DynamicCliError::Registry(crate::error::RegistryError::missing_handler(resolved_name))
167 })?;
168
169 // Parse arguments using CLI parser
170 let parser = CliParser::new(definition);
171 let parsed_args = parser.parse(&args[1..])?;
172
173 // Get handler and execute command. Sync is tried first (unchanged
174 // behaviour); if no sync handler matches, fall through to the async
175 // path (DD-022) and drive it via `block_on`. Safe here because
176 // `run()` is a strictly sequential, one-shot dispatch — there is no
177 // other async task waiting behind it that `block_on` could starve.
178 if let Some(handler) = self.registry.get_handler_sync(resolved_name) {
179 handler.execute(&mut *self.context, &parsed_args)?;
180 } else if let Some(handler) = self.registry.get_handler_async(resolved_name) {
181 futures::executor::block_on(handler.execute(&mut *self.context, &parsed_args))?;
182 } else {
183 return Err(DynamicCliError::Execution(
184 crate::error::ExecutionError::handler_not_found(
185 resolved_name,
186 &definition.implementation,
187 ),
188 ));
189 }
190
191 Ok(())
192 }
193
194 /// Run the CLI with automatic error handling and exit
195 ///
196 /// This is a convenience method that:
197 /// 1. Runs the CLI with provided arguments
198 /// 2. Handles errors by displaying them to stderr
199 /// 3. Exits the process with appropriate exit code
200 ///
201 /// This method never returns.
202 ///
203 /// # Arguments
204 ///
205 /// * `args` - Command-line arguments
206 ///
207 /// # Example
208 ///
209 /// ```no_run
210 /// use dynamic_cli::interface::CliInterface;
211 /// use dynamic_cli::prelude::*;
212 ///
213 /// # #[derive(Default)]
214 /// # struct MyContext;
215 /// # impl ExecutionContext for MyContext {
216 /// # fn as_any(&self) -> &dyn std::any::Any { self }
217 /// # fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self }
218 /// # }
219 /// # fn main() {
220 /// let registry = CommandRegistry::new();
221 /// let context = Box::new(MyContext::default());
222 /// let cli = CliInterface::new(registry, context);
223 ///
224 /// // This will handle errors and exit automatically
225 /// cli.run_and_exit(std::env::args().skip(1).collect());
226 /// # }
227 /// ```
228 pub fn run_and_exit(self, args: Vec<String>) -> ! {
229 match self.run(args) {
230 Ok(()) => process::exit(0),
231 Err(e) => {
232 display_error(&e);
233
234 // Exit with appropriate code based on error type
235 let exit_code = match e {
236 DynamicCliError::Parse(_) => 2,
237 DynamicCliError::Validation(_) => 2,
238 DynamicCliError::Execution(_) => 1,
239 _ => 3,
240 };
241
242 process::exit(exit_code);
243 }
244 }
245 }
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251 use crate::config::schema::{ArgumentDefinition, ArgumentType, CommandDefinition};
252 use std::collections::HashMap;
253
254 // Test context
255 #[derive(Default)]
256 struct TestContext {
257 executed_command: Option<String>,
258 }
259
260 impl ExecutionContext for TestContext {
261 fn as_any(&self) -> &dyn std::any::Any {
262 self
263 }
264
265 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
266 self
267 }
268 }
269
270 // Test handler
271 struct TestHandler {
272 name: String,
273 }
274
275 impl crate::executor::CommandHandler for TestHandler {
276 fn execute(
277 &self,
278 context: &mut dyn ExecutionContext,
279 _args: &HashMap<String, String>,
280 ) -> Result<()> {
281 let ctx = crate::context::downcast_mut::<TestContext>(context)
282 .expect("Failed to downcast context");
283 ctx.executed_command = Some(self.name.clone());
284 Ok(())
285 }
286 }
287
288 fn create_test_registry() -> CommandRegistry {
289 let mut registry = CommandRegistry::new();
290
291 // Create a simple command definition
292 let cmd_def = CommandDefinition {
293 name: "test".to_string(),
294 aliases: vec!["t".to_string()],
295 description: "Test command".to_string(),
296 required: false,
297 arguments: vec![],
298 options: vec![],
299 implementation: "test_handler".to_string(),
300 };
301
302 let handler = Box::new(TestHandler {
303 name: "test".to_string(),
304 });
305
306 registry
307 .register_sync(cmd_def, handler)
308 .expect("Failed to register command");
309
310 registry
311 }
312
313 #[test]
314 fn test_cli_interface_creation() {
315 let registry = create_test_registry();
316 let context = Box::new(TestContext::default());
317
318 let _cli = CliInterface::new(registry, context);
319 // If this compiles and runs, creation works
320 }
321
322 #[test]
323 fn test_cli_run_simple_command() {
324 let registry = create_test_registry();
325 let context = Box::new(TestContext::default());
326 let cli = CliInterface::new(registry, context);
327
328 let result = cli.run(vec!["test".to_string()]);
329 assert!(result.is_ok());
330 }
331
332 #[test]
333 fn test_cli_run_with_alias() {
334 let registry = create_test_registry();
335 let context = Box::new(TestContext::default());
336 let cli = CliInterface::new(registry, context);
337
338 let result = cli.run(vec!["t".to_string()]);
339 assert!(result.is_ok());
340 }
341
342 #[test]
343 fn test_cli_empty_args() {
344 let registry = create_test_registry();
345 let context = Box::new(TestContext::default());
346 let cli = CliInterface::new(registry, context);
347
348 let result = cli.run(vec![]);
349 assert!(result.is_err());
350
351 match result.unwrap_err() {
352 DynamicCliError::Parse(crate::error::ParseError::InvalidSyntax { .. }) => {}
353 other => panic!("Expected InvalidSyntax error, got: {:?}", other),
354 }
355 }
356
357 #[test]
358 fn test_cli_unknown_command() {
359 let registry = create_test_registry();
360 let context = Box::new(TestContext::default());
361 let cli = CliInterface::new(registry, context);
362
363 let result = cli.run(vec!["unknown".to_string()]);
364 assert!(result.is_err());
365
366 match result.unwrap_err() {
367 DynamicCliError::Parse(crate::error::ParseError::UnknownCommand { .. }) => {}
368 other => panic!("Expected UnknownCommand error, got: {:?}", other),
369 }
370 }
371
372 #[test]
373 fn test_cli_command_with_args() {
374 let mut registry = CommandRegistry::new();
375
376 // Command with argument
377 let cmd_def = CommandDefinition {
378 name: "greet".to_string(),
379 aliases: vec![],
380 description: "Greet someone".to_string(),
381 required: false,
382 arguments: vec![ArgumentDefinition {
383 name: "name".to_string(),
384 arg_type: ArgumentType::String,
385 required: true,
386 description: "Name to greet".to_string(),
387 validation: vec![],
388 secure: false,
389 }],
390 options: vec![],
391 implementation: "greet_handler".to_string(),
392 };
393
394 struct GreetHandler;
395 impl crate::executor::CommandHandler for GreetHandler {
396 fn execute(
397 &self,
398 _context: &mut dyn ExecutionContext,
399 args: &HashMap<String, String>,
400 ) -> Result<()> {
401 assert_eq!(args.get("name"), Some(&"Alice".to_string()));
402 Ok(())
403 }
404 }
405
406 registry
407 .register_sync(cmd_def, Box::new(GreetHandler))
408 .unwrap();
409
410 let context = Box::new(TestContext::default());
411 let cli = CliInterface::new(registry, context);
412
413 let result = cli.run(vec!["greet".to_string(), "Alice".to_string()]);
414 assert!(result.is_ok());
415 }
416}