clap_nested_commands/
sync_commands.rs

1#[macro_export]
2macro_rules! generate_sync_commands {
3    // 1) No return type, no default command
4    ($($(#[$attr:meta])* $module:ident),*) => (
5        generate_sync_commands!(return_type = (); $($(#[$attr])* $module),*);
6    );
7
8    // 2) With return type, no default command
9    (return_type = $return_type:ty; $($(#[$attr:meta])* $module:ident),*) => (
10        paste::paste! {
11            #[derive(Debug, Subcommand)]
12            pub enum Commands {
13                $(
14                    $(#[$attr])*
15                    [<$module:camel>]($module::Command),
16                )*
17            }
18
19            pub fn execute(cli_context: &CliContext, cmd: Command) -> $return_type {
20                match cmd.command {
21                    $(
22                        Commands::[<$module:camel>](cmd) => $module::execute(cli_context, cmd),
23                    )*
24                }
25            }
26        }
27    );
28
29    // 3) No return type, with default command
30    (default_command = $default:ident; $($(#[$attr:meta])* $module:ident),*) => (
31        generate_sync_commands!(return_type = (), default_command = $default; $($(#[$attr])* $module),*);
32    );
33
34    // 4) With return type, with default command
35    (return_type = $return_type:ty, default_command = $default:ident; $($(#[$attr:meta])* $module:ident),*) => (
36        paste::paste! {
37            #[derive(Debug, Subcommand)]
38            pub enum Commands {
39                $(
40                    $(#[$attr])*
41                    [<$module:camel>]($module::Command),
42                )*
43            }
44
45            pub fn execute(cli_context: &CliContext, cmd: Command) -> $return_type {
46                match cmd.command {
47                    $(
48                        Some(Commands::[<$module:camel>](cmd)) => $module::execute(cli_context, cmd),
49                    )*
50                    None => $default::execute(cli_context, $default::Command::default()),
51                }
52            }
53        }
54    );
55}