Skip to main content

larastvel_core/console/
mod.rs

1use std::collections::HashMap;
2use std::fmt;
3use std::sync::{Arc, RwLock};
4
5use crate::foundation::Application;
6
7/// Error type for console command execution.
8#[derive(Debug, Clone)]
9pub struct ConsoleError(pub String);
10
11impl fmt::Display for ConsoleError {
12    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13        write!(f, "{}", self.0)
14    }
15}
16
17impl std::error::Error for ConsoleError {}
18
19impl From<String> for ConsoleError {
20    fn from(s: String) -> Self {
21        ConsoleError(s)
22    }
23}
24
25/// A registered CLI command — the Rust equivalent of a Laravel `Artisan`
26/// console command.
27///
28/// # Example
29///
30/// ```rust,ignore
31/// use larastvel_core::console::Command;
32///
33/// struct InspireCommand;
34///
35/// impl Command for InspireCommand {
36///     fn name(&self) -> &'static str {
37///         "inspire"
38///     }
39///     fn description(&self) -> &'static str {
40///         "Display an inspiring quote"
41///     }
42///     fn handle(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
43///         println!("“Simplicity is the ultimate sophistication.” — Leonardo da Vinci");
44///         Ok(())
45///     }
46/// }
47/// ```
48pub trait Command: Send + Sync {
49    /// The command name used on the CLI (e.g. `"make:model"`, `"serve"`).
50    fn name(&self) -> &'static str;
51
52    /// A short description shown in `list` / `--help`.
53    fn description(&self) -> &'static str;
54
55    /// Execute the command with the given arguments (excluding the binary and
56    /// command name).
57    fn handle(&self, app: &Application, args: &[String]) -> Result<(), ConsoleError>;
58}
59
60/// The console kernel — registers and dispatches CLI commands.
61///
62/// Analogous to `App\Console\Kernel` in Laravel. Supports loading commands
63/// from a closure, which mirrors the `routes/console.php` pattern.
64///
65/// # Example
66///
67/// ```rust,ignore
68/// use larastvel_core::console::{ConsoleKernel, Command};
69/// use std::sync::Arc;
70///
71/// let app = larastvel_core::Application::new(None);
72/// let kernel = app.console_kernel();
73///
74/// kernel.add_command(Arc::new(MyCommand));
75/// kernel.call("my-command", &[]).await?;
76/// ```
77pub struct ConsoleKernel {
78    app: Application,
79    commands: Arc<RwLock<HashMap<&'static str, Arc<dyn Command>>>>,
80    loaded: Arc<RwLock<bool>>,
81}
82
83impl ConsoleKernel {
84    /// Create a new kernel bound to the given application.
85    pub fn new(app: Application) -> Self {
86        Self {
87            app,
88            commands: Arc::new(RwLock::new(HashMap::new())),
89            loaded: Arc::new(RwLock::new(false)),
90        }
91    }
92
93    /// Register a command.
94    ///
95    /// If a command with the same `name()` already exists it is overwritten.
96    pub fn add_command(&self, cmd: Arc<dyn Command>) {
97        let name = cmd.name();
98        self.commands.write().unwrap().insert(name, cmd);
99    }
100
101    /// Register multiple commands at once.
102    pub fn add_commands(&self, cmds: Vec<Arc<dyn Command>>) {
103        let mut map = self.commands.write().unwrap();
104        for cmd in cmds {
105            map.insert(cmd.name(), cmd);
106        }
107    }
108
109    /// Returns `true` if a command with the given `name` has been registered.
110    pub fn has_command(&self, name: &str) -> bool {
111        self.commands.read().unwrap().contains_key(name)
112    }
113
114    /// Returns the number of registered commands.
115    pub fn command_count(&self) -> usize {
116        self.commands.read().unwrap().len()
117    }
118
119    /// Returns a list of all registered command names.
120    pub fn command_names(&self) -> Vec<String> {
121        self.commands
122            .read()
123            .unwrap()
124            .keys()
125            .map(|k| k.to_string())
126            .collect()
127    }
128
129    /// Returns the command with the given name, if registered.
130    pub fn get_command(&self, name: &str) -> Option<Arc<dyn Command>> {
131        self.commands.read().unwrap().get(name).cloned()
132    }
133
134    /// Load commands via a closure — the Rust equivalent of defining
135    /// Artisan commands in `routes/console.php`.
136    ///
137    /// The closure receives this kernel so commands can be registered
138    /// with [`add_command`](Self::add_command) or
139    /// [`add_commands`](Self::add_commands).
140    ///
141    /// The closure is guaranteed to run at most once.
142    pub fn load(&self, f: impl FnOnce(&Self)) {
143        let mut loaded = self.loaded.write().unwrap();
144        if !*loaded {
145            f(self);
146            *loaded = true;
147        }
148    }
149
150    /// Execute a command by name with the given arguments.
151    ///
152    /// Returns `Ok(())` on success, or `Err(message)` on failure.
153    pub fn call(&self, name: &str, args: &[String]) -> Result<(), ConsoleError> {
154        let cmd = self
155            .commands
156            .read()
157            .unwrap()
158            .get(name)
159            .cloned()
160            .ok_or_else(|| format!("Unknown command: {}", name))?;
161        cmd.handle(&self.app, args)
162    }
163
164    /// Return the underlying application.
165    pub fn app(&self) -> &Application {
166        &self.app
167    }
168}
169
170impl Clone for ConsoleKernel {
171    fn clone(&self) -> Self {
172        Self {
173            app: self.app.clone(),
174            commands: self.commands.clone(),
175            loaded: self.loaded.clone(),
176        }
177    }
178}
179
180// ============================================================================
181// Built-in stub commands
182// ============================================================================
183
184macro_rules! stub_command {
185    ($name:ident, $cmd:expr, $desc:expr) => {
186        pub struct $name;
187        impl Command for $name {
188            fn name(&self) -> &'static str {
189                $cmd
190            }
191            fn description(&self) -> &'static str {
192                $desc
193            }
194            fn handle(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
195                println!("[stub] {} — {}", $cmd, $desc);
196                Ok(())
197            }
198        }
199    };
200}
201
202stub_command!(
203    ServeCommand,
204    "serve",
205    "Start the Larastvel development server"
206);
207stub_command!(RouteListCommand, "route:list", "List all registered routes");
208stub_command!(MakeModelCommand, "make:model", "Create a new model class");
209stub_command!(
210    MakeControllerCommand,
211    "make:controller",
212    "Create a new controller class"
213);
214stub_command!(
215    MakeMigrationCommand,
216    "make:migration",
217    "Create a new migration file"
218);
219stub_command!(MigrateCommand, "migrate", "Run the database migrations");
220stub_command!(DbSeedCommand, "db:seed", "Seed the database with records");
221stub_command!(
222    KeyGenerateCommand,
223    "key:generate",
224    "Generate a new application key"
225);
226
227// ============================================================================
228// TESTS
229// ============================================================================
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    struct GreetCommand;
236    impl Command for GreetCommand {
237        fn name(&self) -> &'static str {
238            "greet"
239        }
240        fn description(&self) -> &'static str {
241            "Greet someone"
242        }
243        fn handle(&self, _app: &Application, args: &[String]) -> Result<(), ConsoleError> {
244            let name = args.first().map(|s| s.as_str()).unwrap_or("world");
245            println!("Hello, {}!", name);
246            Ok(())
247        }
248    }
249
250    struct FailCommand;
251    impl Command for FailCommand {
252        fn name(&self) -> &'static str {
253            "fail"
254        }
255        fn description(&self) -> &'static str {
256            "Always fails"
257        }
258        fn handle(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
259            Err("Something went wrong".to_string().into())
260        }
261    }
262
263    #[test]
264    fn test_add_and_has_command() {
265        let app = Application::new(None);
266        let kernel = ConsoleKernel::new(app);
267        kernel.add_command(Arc::new(GreetCommand));
268        assert!(kernel.has_command("greet"));
269        assert!(!kernel.has_command("nonexistent"));
270    }
271
272    #[test]
273    fn test_command_count() {
274        let app = Application::new(None);
275        let kernel = ConsoleKernel::new(app);
276        assert_eq!(kernel.command_count(), 0);
277        kernel.add_command(Arc::new(GreetCommand));
278        assert_eq!(kernel.command_count(), 1);
279        kernel.add_command(Arc::new(FailCommand));
280        assert_eq!(kernel.command_count(), 2);
281    }
282
283    #[test]
284    fn test_command_names() {
285        let app = Application::new(None);
286        let kernel = ConsoleKernel::new(app);
287        kernel.add_command(Arc::new(GreetCommand));
288        kernel.add_command(Arc::new(FailCommand));
289        let mut names = kernel.command_names();
290        names.sort();
291        assert_eq!(names, vec!["fail", "greet"]);
292    }
293
294    #[test]
295    fn test_get_command_returns_arc() {
296        let app = Application::new(None);
297        let kernel = ConsoleKernel::new(app);
298        kernel.add_command(Arc::new(GreetCommand));
299        let cmd = kernel.get_command("greet");
300        assert!(cmd.is_some());
301        assert_eq!(cmd.unwrap().name(), "greet");
302    }
303
304    #[test]
305    fn test_get_command_nonexistent() {
306        let app = Application::new(None);
307        let kernel = ConsoleKernel::new(app);
308        assert!(kernel.get_command("nope").is_none());
309    }
310
311    #[test]
312    fn test_call_unknown_command() {
313        let app = Application::new(None);
314        let kernel = ConsoleKernel::new(app);
315        let result = kernel.call("unknown", &[]);
316        assert!(result.is_err());
317        assert_eq!(result.unwrap_err().0, "Unknown command: unknown");
318    }
319
320    #[test]
321    fn test_call_success() {
322        let app = Application::new(None);
323        let kernel = ConsoleKernel::new(app);
324        kernel.add_command(Arc::new(GreetCommand));
325        let result = kernel.call("greet", &[]);
326        assert!(result.is_ok());
327    }
328
329    #[test]
330    fn test_call_failure() {
331        let app = Application::new(None);
332        let kernel = ConsoleKernel::new(app);
333        kernel.add_command(Arc::new(FailCommand));
334        let result = kernel.call("fail", &[]);
335        assert!(result.is_err());
336        assert_eq!(result.unwrap_err().0, "Something went wrong");
337    }
338
339    #[test]
340    fn test_call_with_args() {
341        let app = Application::new(None);
342        let kernel = ConsoleKernel::new(app);
343        kernel.add_command(Arc::new(GreetCommand));
344        let result = kernel.call("greet", &["Alice".to_string()]);
345        assert!(result.is_ok());
346    }
347
348    #[test]
349    fn test_add_commands_bulk() {
350        let app = Application::new(None);
351        let kernel = ConsoleKernel::new(app);
352        kernel.add_commands(vec![Arc::new(GreetCommand), Arc::new(FailCommand)]);
353        assert_eq!(kernel.command_count(), 2);
354        assert!(kernel.has_command("greet"));
355        assert!(kernel.has_command("fail"));
356    }
357
358    #[test]
359    fn test_last_command_wins_on_name_collision() {
360        let app = Application::new(None);
361        let kernel = ConsoleKernel::new(app);
362
363        struct CmdA;
364        impl Command for CmdA {
365            fn name(&self) -> &'static str {
366                "same"
367            }
368            fn description(&self) -> &'static str {
369                "first"
370            }
371            fn handle(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
372                Ok(())
373            }
374        }
375
376        struct CmdB;
377        impl Command for CmdB {
378            fn name(&self) -> &'static str {
379                "same"
380            }
381            fn description(&self) -> &'static str {
382                "second"
383            }
384            fn handle(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
385                Ok(())
386            }
387        }
388
389        kernel.add_command(Arc::new(CmdA));
390        kernel.add_command(Arc::new(CmdB));
391        let cmd = kernel.get_command("same").unwrap();
392        assert_eq!(cmd.description(), "second");
393    }
394
395    #[test]
396    fn test_load_runs_once() {
397        let app = Application::new(None);
398        let kernel = ConsoleKernel::new(app);
399        let counter = std::sync::atomic::AtomicUsize::new(0);
400
401        kernel.load(|k| {
402            counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
403            k.add_command(Arc::new(GreetCommand));
404        });
405
406        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
407        assert!(kernel.has_command("greet"));
408
409        // Second call should be a no-op
410        kernel.load(|_k| {
411            counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
412        });
413
414        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
415    }
416
417    #[test]
418    fn test_stub_commands_are_registrable() {
419        let app = Application::new(None);
420        let kernel = ConsoleKernel::new(app);
421
422        let stubs: Vec<Arc<dyn Command>> = vec![
423            Arc::new(ServeCommand),
424            Arc::new(RouteListCommand),
425            Arc::new(MakeModelCommand),
426            Arc::new(MakeControllerCommand),
427            Arc::new(MakeMigrationCommand),
428            Arc::new(MigrateCommand),
429            Arc::new(DbSeedCommand),
430            Arc::new(KeyGenerateCommand),
431        ];
432
433        for stub in &stubs {
434            kernel.add_command(stub.clone());
435        }
436
437        assert_eq!(kernel.command_count(), 8);
438        assert!(kernel.has_command("serve"));
439        assert!(kernel.has_command("route:list"));
440        assert!(kernel.has_command("make:model"));
441        assert!(kernel.has_command("migrate"));
442        assert!(kernel.has_command("key:generate"));
443
444        for stub in &stubs {
445            let result = kernel.call(stub.name(), &[]);
446            assert!(result.is_ok(), "stub {} failed: {:?}", stub.name(), result);
447        }
448    }
449
450    // -----------------------------------------------------------------------
451    // #[command] macro tests
452    // -----------------------------------------------------------------------
453
454    use larastvel_macros::command;
455
456    #[command("test:hello", description = "A hello command")]
457    struct TestHelloCommand;
458
459    impl TestHelloCommand {
460        fn run(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
461            println!("Hello from test command!");
462            Ok(())
463        }
464    }
465
466    #[command("test:fail")]
467    struct TestFailCommand;
468
469    impl TestFailCommand {
470        fn run(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
471            Err(ConsoleError("fail".to_string()))
472        }
473    }
474
475    #[test]
476    fn test_command_macro_name_and_description() {
477        let cmd = TestHelloCommand;
478        assert_eq!(cmd.name(), "test:hello");
479        assert_eq!(cmd.description(), "A hello command");
480    }
481
482    #[test]
483    fn test_command_macro_handle_delegates_to_run() {
484        let app = Application::new(None);
485        let cmd = TestHelloCommand;
486        let result = cmd.handle(&app, &[]);
487        assert!(result.is_ok());
488    }
489
490    #[test]
491    fn test_command_macro_error() {
492        let app = Application::new(None);
493        let cmd = TestFailCommand;
494        let result = cmd.handle(&app, &[]);
495        assert!(result.is_err());
496        assert_eq!(result.unwrap_err().0, "fail");
497    }
498
499    #[test]
500    fn test_command_macro_empty_description() {
501        let cmd = TestFailCommand;
502        assert_eq!(cmd.name(), "test:fail");
503        assert_eq!(cmd.description(), "");
504    }
505
506    #[test]
507    fn test_command_macro_can_be_registered_with_kernel() {
508        let app = Application::new(None);
509        let kernel = ConsoleKernel::new(app);
510        kernel.add_command(Arc::new(TestHelloCommand));
511        assert!(kernel.has_command("test:hello"));
512        assert_eq!(kernel.command_count(), 1);
513        let result = kernel.call("test:hello", &[]);
514        assert!(result.is_ok());
515    }
516
517    #[test]
518    fn test_command_macro_string_arg() {
519        let app = Application::new(None);
520        let cmd = TestHelloCommand;
521        let result = cmd.handle(&app, &["world".to_string()]);
522        assert!(result.is_ok());
523    }
524}