clap_nested_commands/
async_commands.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#[macro_export]
macro_rules! generate_async_commands {
    // 1) No return type, no default command
    ($($(#[$attr:meta])* $module:ident),*) => (
        generate_async_commands!(return_type = (); $($(#[$attr])* $module),*);
    );

    // 2) With return type, no default command
    (return_type = $return_type:ty; $($(#[$attr:meta])* $module:ident),*) => (
        paste::paste! {
            #[derive(Debug, Subcommand)]
            pub enum Commands {
                $(
                    $(#[$attr])*
                    [<$module:camel>]($module::Command),
                )*
            }

            pub async fn execute(cli_context: &CliContext, cmd: Command) -> Result<$return_type, anyhow::Error> {
                match cmd.command {
                    $(
                        Commands::[<$module:camel>](cmd) => $module::execute(cli_context, cmd).await,
                    )*
                }
            }
        }
    );

    // 3) No return type, with default command
    (default_command = $default:ident; $($(#[$attr:meta])* $module:ident),*) => (
        generate_async_commands!(return_type = (), default_command = $default; $($(#[$attr])* $module),*);
    );

    // 4) With return type, with default command
    (return_type = $return_type:ty, default_command = $default:ident; $($(#[$attr:meta])* $module:ident),*) => (
        paste::paste! {
            #[derive(Debug, Subcommand)]
            pub enum Commands {
                $(
                    $(#[$attr])*
                    [<$module:camel>]($module::Command),
                )*
            }

            pub async fn execute(cli_context: &CliContext, cmd: Command) -> Result<$return_type, anyhow::Error> {
                match cmd.command {
                    $(
                        Some(Commands::[<$module:camel>](cmd)) => $module::execute(cli_context, cmd).await,
                    )*
                    None => $default::execute(cli_context, $default::Command::default()).await,
                }
            }
        }
    );
}