clap_runner/command/
facade.rs1use faststr::FastStr;
2
3use super::error::*;
4use super::model::*;
5
6pub struct BoxSafeRunnableCommand(pub(crate) Box<dyn SafeRunnableCommand>);
7
8impl BoxSafeRunnableCommand {
9 pub fn self_check(&self) -> Result<()> {
10 if self.0.command().get_name().contains(".") {
11 return Err(Error::CommandNameIllegal {
12 hint: FastStr::new("command name cannot contains '.'"),
13 });
14 }
15 Ok(())
16 }
17}
18
19impl<T: RunnableCommand> From<T> for BoxSafeRunnableCommand {
20 fn from(value: T) -> Self {
21 Self(Box::new(value))
22 }
23}
24
25#[async_trait::async_trait]
26pub(crate) trait SafeRunnableCommand {
27 async fn callback(&self, cx: crate::context::Context) -> Result<CallbackStatus>;
28 fn command(&self) -> clap::Command;
29 fn bind_matches(&mut self, matches: clap::ArgMatches) -> Result<()>;
30}
31
32#[async_trait::async_trait]
33impl<T: RunnableCommand> SafeRunnableCommand for T {
34 async fn callback(&self, cx: crate::context::Context) -> Result<CallbackStatus> {
35 self.callback(cx).await
36 }
37 fn command(&self) -> clap::Command {
38 T::command()
39 }
40 fn bind_matches(&mut self, matches: clap::ArgMatches) -> Result<()> {
41 self.bind_matches(matches)
42 }
43}
44
45#[async_trait::async_trait]
46pub trait RunnableCommand: clap::Parser + Send + Sync + 'static {
47 async fn callback(&self, _cx: crate::context::Context) -> Result<CallbackStatus> {
48 Ok(CallbackStatus::Continue)
49 }
50 fn bind_matches(&mut self, mut matches: clap::ArgMatches) -> Result<()> {
51 <Self as clap::FromArgMatches>::update_from_arg_matches(self, &mut matches).map_err(|e| {
52 Error::Param {
53 hint: FastStr::new(e.to_string()),
54 }
55 })
56 }
57}