Skip to content

Commit

Permalink
feat: implement generics commands (#219)
Browse files Browse the repository at this point in the history
Backport of #206
  • Loading branch information
darkyeg authored Nov 15, 2023
1 parent 557c4cf commit 7844c03
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
23 changes: 23 additions & 0 deletions examples/generic_commands/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//! If you need it, poise-annotated command functions can also be generic over the user data type
//! or error type
//!
//! The original use case for this feature was to have the same command in two different bots
#[poise::command(slash_command)]
pub async fn example<U: Sync, E>(ctx: poise::Context<'_, U, E>) -> Result<(), E> {
ctx.say(format!(
"My user data type is {} and the error type is {}",
std::any::type_name::<U>(),
std::any::type_name::<E>()
))
.await
.unwrap();

Ok(())
}

#[tokio::main]
async fn main() {
let _example1 = example::<(), ()>();
let _example2 = example::<String, Box<dyn std::error::Error>>();
}
3 changes: 2 additions & 1 deletion macros/src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,11 +314,12 @@ fn generate_command(mut inv: Invocation) -> Result<proc_macro2::TokenStream, dar
crate::util::vec_tuple_2_to_hash_map(inv.args.description_localized);

let function_name = std::mem::replace(&mut inv.function.sig.ident, syn::parse_quote! { inner });
let function_generics = &inv.function.sig.generics;
let function_visibility = &inv.function.vis;
let function = &inv.function;
Ok(quote::quote! {
#[allow(clippy::str_to_string)]
#function_visibility fn #function_name() -> ::poise::Command<
#function_visibility fn #function_name #function_generics() -> ::poise::Command<
<#ctx_type_with_static as poise::_GetGenerics>::U,
<#ctx_type_with_static as poise::_GetGenerics>::E,
> {
Expand Down

0 comments on commit 7844c03

Please sign in to comment.