ayun-console 0.24.0

The RUST Framework for Web Rustceans.
Documentation
use crate::{
    support::{commands, Command},
    Console,
};
use ayun_config::{config, support::config};
use ayun_core::{
    traits::{ApplicationTrait, ServiceTrait},
    Result,
};

impl ServiceTrait for Console {
    type Item = Command;

    fn new() -> Self {
        Self::default()
    }

    fn register(mut self, command: Self::Item) -> Self {
        self.commands
            .insert(command.name().to_string(), command.command().clone());
        self.closures
            .insert(command.name().to_string(), command.handler().clone());

        self
    }

    fn init<A: ApplicationTrait>() -> Self {
        let mut console = (&A::with_console() as &dyn std::any::Any)
            .downcast_ref::<Self>()
            .cloned()
            .unwrap_or(Self::default());

        #[cfg(feature = "command-make")]
        {
            console = console.register(Command::new::<A, commands::Make>());
        }

        #[cfg(feature = "command-migrate")]
        {
            console = console.register(Command::new::<A, commands::Migrate>());
        }

        #[cfg(feature = "command-queue")]
        {
            console = console.register(Command::new::<A, commands::Queue>());
        }

        #[cfg(feature = "command-server")]
        {
            console = console.register(Command::new::<A, commands::Server>());
        }

        #[cfg(feature = "command-schedule")]
        {
            console = console.register(Command::new::<A, commands::Schedule>());
        }

        #[cfg(feature = "command-status")]
        {
            console = console.register(Command::new::<A, commands::Status>());
        }

        console = console.register(Command::new::<A, commands::Publish>());

        console
    }

    fn run(self) -> Result<()> {
        let environment = config::<config::App>("app")?.environment;

        let span = tracing::debug_span!("console",environment=%environment);
        let _enter = span.enter();

        let commands = self.inner.subcommands(self.commands.values());

        match commands.clone().get_matches().subcommand() {
            Some((name, arg_matches)) => {
                if let Some(closure) = self.closures.get(name) {
                    if let Some(err) = closure(arg_matches.to_owned()).err() {
                        tracing::error!("[command] `{}` handle error: {}", name, err);
                    }
                }
            }
            None => commands.clone().print_help()?,
        }

        Ok(())
    }
}