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
#![deny(missing_docs)]
use proc_macro::TokenStream;
use syn::*;
#[proc_macro_attribute]
pub fn cmd(_: TokenStream, input: TokenStream) -> TokenStream {
let cmd_enum = syn::parse_macro_input!(input as ItemEnum);
let ItemEnum {
attrs: cmd_attrs, vis: cmd_vis, ident: cmd_name, variants: cmd_variants, ..
} = cmd_enum;
let cmd_variant_names =
cmd_variants.iter().map(|variant| variant.ident.clone()).collect::<Vec<_>>();
let cmd_variants = cmd_variants
.into_iter()
.map(|Variant { attrs, ident, .. }| {
let cmd = quote::format_ident!("{ident}Cmd");
quote::quote! {
#(#attrs)*
#ident(#cmd)
}
})
.collect::<Vec<_>>();
quote::quote! {
#[derive(Debug, clap::Subcommand)]
#(#cmd_attrs)*
#cmd_vis enum #cmd_name {
#(#cmd_variants,)*
}
impl #cmd_name {
#cmd_vis fn run(&self) -> crate::prelude::Result<()> {
match self {
#(
Self::#cmd_variant_names(cmd) => cmd.run(),
)*
}
}
}
}
.into()
}