use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, RwLock};
use crate::foundation::Application;
#[derive(Debug, Clone)]
pub struct ConsoleError(pub String);
impl fmt::Display for ConsoleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for ConsoleError {}
impl From<String> for ConsoleError {
fn from(s: String) -> Self {
ConsoleError(s)
}
}
pub trait Command: Send + Sync {
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
fn handle(&self, app: &Application, args: &[String]) -> Result<(), ConsoleError>;
}
pub struct ConsoleKernel {
app: Application,
commands: Arc<RwLock<HashMap<&'static str, Arc<dyn Command>>>>,
loaded: Arc<RwLock<bool>>,
}
impl ConsoleKernel {
pub fn new(app: Application) -> Self {
Self {
app,
commands: Arc::new(RwLock::new(HashMap::new())),
loaded: Arc::new(RwLock::new(false)),
}
}
pub fn add_command(&self, cmd: Arc<dyn Command>) {
let name = cmd.name();
self.commands.write().unwrap().insert(name, cmd);
}
pub fn add_commands(&self, cmds: Vec<Arc<dyn Command>>) {
let mut map = self.commands.write().unwrap();
for cmd in cmds {
map.insert(cmd.name(), cmd);
}
}
pub fn has_command(&self, name: &str) -> bool {
self.commands.read().unwrap().contains_key(name)
}
pub fn command_count(&self) -> usize {
self.commands.read().unwrap().len()
}
pub fn command_names(&self) -> Vec<String> {
self.commands
.read()
.unwrap()
.keys()
.map(|k| k.to_string())
.collect()
}
pub fn get_command(&self, name: &str) -> Option<Arc<dyn Command>> {
self.commands.read().unwrap().get(name).cloned()
}
pub fn load(&self, f: impl FnOnce(&Self)) {
let mut loaded = self.loaded.write().unwrap();
if !*loaded {
f(self);
*loaded = true;
}
}
pub fn call(&self, name: &str, args: &[String]) -> Result<(), ConsoleError> {
let cmd = self
.commands
.read()
.unwrap()
.get(name)
.cloned()
.ok_or_else(|| format!("Unknown command: {}", name))?;
cmd.handle(&self.app, args)
}
pub fn app(&self) -> &Application {
&self.app
}
}
impl Clone for ConsoleKernel {
fn clone(&self) -> Self {
Self {
app: self.app.clone(),
commands: self.commands.clone(),
loaded: self.loaded.clone(),
}
}
}
macro_rules! stub_command {
($name:ident, $cmd:expr, $desc:expr) => {
pub struct $name;
impl Command for $name {
fn name(&self) -> &'static str {
$cmd
}
fn description(&self) -> &'static str {
$desc
}
fn handle(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
println!("[stub] {} — {}", $cmd, $desc);
Ok(())
}
}
};
}
stub_command!(
ServeCommand,
"serve",
"Start the Larastvel development server"
);
stub_command!(RouteListCommand, "route:list", "List all registered routes");
stub_command!(MakeModelCommand, "make:model", "Create a new model class");
stub_command!(
MakeControllerCommand,
"make:controller",
"Create a new controller class"
);
stub_command!(
MakeMigrationCommand,
"make:migration",
"Create a new migration file"
);
stub_command!(MigrateCommand, "migrate", "Run the database migrations");
stub_command!(DbSeedCommand, "db:seed", "Seed the database with records");
stub_command!(
KeyGenerateCommand,
"key:generate",
"Generate a new application key"
);
#[cfg(test)]
mod tests {
use super::*;
struct GreetCommand;
impl Command for GreetCommand {
fn name(&self) -> &'static str {
"greet"
}
fn description(&self) -> &'static str {
"Greet someone"
}
fn handle(&self, _app: &Application, args: &[String]) -> Result<(), ConsoleError> {
let name = args.first().map(|s| s.as_str()).unwrap_or("world");
println!("Hello, {}!", name);
Ok(())
}
}
struct FailCommand;
impl Command for FailCommand {
fn name(&self) -> &'static str {
"fail"
}
fn description(&self) -> &'static str {
"Always fails"
}
fn handle(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
Err("Something went wrong".to_string().into())
}
}
#[test]
fn test_add_and_has_command() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
kernel.add_command(Arc::new(GreetCommand));
assert!(kernel.has_command("greet"));
assert!(!kernel.has_command("nonexistent"));
}
#[test]
fn test_command_count() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
assert_eq!(kernel.command_count(), 0);
kernel.add_command(Arc::new(GreetCommand));
assert_eq!(kernel.command_count(), 1);
kernel.add_command(Arc::new(FailCommand));
assert_eq!(kernel.command_count(), 2);
}
#[test]
fn test_command_names() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
kernel.add_command(Arc::new(GreetCommand));
kernel.add_command(Arc::new(FailCommand));
let mut names = kernel.command_names();
names.sort();
assert_eq!(names, vec!["fail", "greet"]);
}
#[test]
fn test_get_command_returns_arc() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
kernel.add_command(Arc::new(GreetCommand));
let cmd = kernel.get_command("greet");
assert!(cmd.is_some());
assert_eq!(cmd.unwrap().name(), "greet");
}
#[test]
fn test_get_command_nonexistent() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
assert!(kernel.get_command("nope").is_none());
}
#[test]
fn test_call_unknown_command() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
let result = kernel.call("unknown", &[]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().0, "Unknown command: unknown");
}
#[test]
fn test_call_success() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
kernel.add_command(Arc::new(GreetCommand));
let result = kernel.call("greet", &[]);
assert!(result.is_ok());
}
#[test]
fn test_call_failure() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
kernel.add_command(Arc::new(FailCommand));
let result = kernel.call("fail", &[]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().0, "Something went wrong");
}
#[test]
fn test_call_with_args() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
kernel.add_command(Arc::new(GreetCommand));
let result = kernel.call("greet", &["Alice".to_string()]);
assert!(result.is_ok());
}
#[test]
fn test_add_commands_bulk() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
kernel.add_commands(vec![Arc::new(GreetCommand), Arc::new(FailCommand)]);
assert_eq!(kernel.command_count(), 2);
assert!(kernel.has_command("greet"));
assert!(kernel.has_command("fail"));
}
#[test]
fn test_last_command_wins_on_name_collision() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
struct CmdA;
impl Command for CmdA {
fn name(&self) -> &'static str {
"same"
}
fn description(&self) -> &'static str {
"first"
}
fn handle(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
Ok(())
}
}
struct CmdB;
impl Command for CmdB {
fn name(&self) -> &'static str {
"same"
}
fn description(&self) -> &'static str {
"second"
}
fn handle(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
Ok(())
}
}
kernel.add_command(Arc::new(CmdA));
kernel.add_command(Arc::new(CmdB));
let cmd = kernel.get_command("same").unwrap();
assert_eq!(cmd.description(), "second");
}
#[test]
fn test_load_runs_once() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
let counter = std::sync::atomic::AtomicUsize::new(0);
kernel.load(|k| {
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
k.add_command(Arc::new(GreetCommand));
});
assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
assert!(kernel.has_command("greet"));
kernel.load(|_k| {
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
});
assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
}
#[test]
fn test_stub_commands_are_registrable() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
let stubs: Vec<Arc<dyn Command>> = vec![
Arc::new(ServeCommand),
Arc::new(RouteListCommand),
Arc::new(MakeModelCommand),
Arc::new(MakeControllerCommand),
Arc::new(MakeMigrationCommand),
Arc::new(MigrateCommand),
Arc::new(DbSeedCommand),
Arc::new(KeyGenerateCommand),
];
for stub in &stubs {
kernel.add_command(stub.clone());
}
assert_eq!(kernel.command_count(), 8);
assert!(kernel.has_command("serve"));
assert!(kernel.has_command("route:list"));
assert!(kernel.has_command("make:model"));
assert!(kernel.has_command("migrate"));
assert!(kernel.has_command("key:generate"));
for stub in &stubs {
let result = kernel.call(stub.name(), &[]);
assert!(result.is_ok(), "stub {} failed: {:?}", stub.name(), result);
}
}
use larastvel_macros::command;
#[command("test:hello", description = "A hello command")]
struct TestHelloCommand;
impl TestHelloCommand {
fn run(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
println!("Hello from test command!");
Ok(())
}
}
#[command("test:fail")]
struct TestFailCommand;
impl TestFailCommand {
fn run(&self, _app: &Application, _args: &[String]) -> Result<(), ConsoleError> {
Err(ConsoleError("fail".to_string()))
}
}
#[test]
fn test_command_macro_name_and_description() {
let cmd = TestHelloCommand;
assert_eq!(cmd.name(), "test:hello");
assert_eq!(cmd.description(), "A hello command");
}
#[test]
fn test_command_macro_handle_delegates_to_run() {
let app = Application::new(None);
let cmd = TestHelloCommand;
let result = cmd.handle(&app, &[]);
assert!(result.is_ok());
}
#[test]
fn test_command_macro_error() {
let app = Application::new(None);
let cmd = TestFailCommand;
let result = cmd.handle(&app, &[]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().0, "fail");
}
#[test]
fn test_command_macro_empty_description() {
let cmd = TestFailCommand;
assert_eq!(cmd.name(), "test:fail");
assert_eq!(cmd.description(), "");
}
#[test]
fn test_command_macro_can_be_registered_with_kernel() {
let app = Application::new(None);
let kernel = ConsoleKernel::new(app);
kernel.add_command(Arc::new(TestHelloCommand));
assert!(kernel.has_command("test:hello"));
assert_eq!(kernel.command_count(), 1);
let result = kernel.call("test:hello", &[]);
assert!(result.is_ok());
}
#[test]
fn test_command_macro_string_arg() {
let app = Application::new(None);
let cmd = TestHelloCommand;
let result = cmd.handle(&app, &["world".to_string()]);
assert!(result.is_ok());
}
}