soph_console/support/
service.rs1use crate::{
2 async_trait,
3 support::{Command, STYLES},
4 traits::{ApplicationTrait, ServiceTrait},
5 Console, Result,
6};
7
8const LOGO: &str = r"
9░░ ░░░░ ░░░ ░░░ ░░░░ ░
10▒ ▒▒▒▒▒▒▒▒ ▒▒▒▒ ▒▒ ▒▒▒▒ ▒▒ ▒▒▒▒ ▒
11▓▓ ▓▓▓ ▓▓▓▓ ▓▓ ▓▓▓ ▓
12███████ ██ ████ ██ ████████ ████ █
13██ ████ ███ ████████ ████ █
14";
15
16#[async_trait]
17impl ServiceTrait for Console {
18 type Item = Command;
19
20 fn new() -> Self {
21 let command = clap::Command::default()
22 .styles(STYLES)
23 .name("soph")
24 .version(env!("CARGO_PKG_VERSION"))
25 .about(format!("\n {} \n {}", LOGO, env!("CARGO_PKG_DESCRIPTION")));
26
27 Self {
28 inner: command,
29 ..Default::default()
30 }
31 }
32
33 fn register(mut self, command: Self::Item) -> Self {
34 self.commands
35 .insert(command.name().to_string(), command.command().clone());
36 self.closures
37 .insert(command.name().to_string(), command.handler().clone());
38
39 self
40 }
41
42 fn init<A: ApplicationTrait>() -> Self {
43 let mut console = (&A::with_console() as &dyn std::any::Any)
44 .downcast_ref::<Self>()
45 .cloned()
46 .unwrap_or_default();
47
48 console = console.register(Command::new::<A, crate::support::commands::Publish>());
49
50 #[cfg(feature = "command-make")]
51 {
52 console = console.register(Command::new::<A, crate::support::commands::Make>());
53 }
54
55 #[cfg(feature = "command-migrate")]
56 {
57 console = console.register(Command::new::<A, crate::support::commands::Migrate>());
58 }
59
60 #[cfg(feature = "command-new")]
61 {
62 console = console.register(Command::new::<A, crate::support::commands::New>());
63 }
64
65 #[cfg(feature = "command-queue")]
66 {
67 console = console.register(Command::new::<A, crate::support::commands::Queue>());
68 }
69
70 #[cfg(feature = "command-server")]
71 {
72 console = console.register(Command::new::<A, crate::support::commands::Server>());
73 }
74
75 #[cfg(feature = "command-schedule")]
76 {
77 console = console.register(Command::new::<A, crate::support::commands::Schedule>());
78 }
79
80 #[cfg(any(
81 feature = "cache",
82 feature = "database",
83 feature = "mail",
84 feature = "redis",
85 feature = "storage",
86 feature = "tracing",
87 ))]
88 {
89 console = console.register(Command::new::<A, crate::support::commands::Status>());
90 }
91
92 console
93 }
94
95 async fn run(self) -> Result<()> {
96 let commands = self.inner.subcommands(self.commands.values());
97
98 match commands.clone().get_matches().subcommand() {
99 Some((name, arg_matches)) => {
100 if let Some(closure) = self.closures.get(name) {
101 if let Some(err) = closure(arg_matches.to_owned()).await.err() {
102 tracing::error!("[command] `{}` handle error: {}", name, err);
103 }
104 }
105 }
106 None => commands.clone().print_help()?,
107 }
108
109 Ok(())
110 }
111}