Skip to main content

serenade_console/
compile_pass.rs

1//! Compile pass that collects tagged commands into an [`Application`].
2
3use std::sync::Arc;
4
5use serenade_di::{CompilePass, ContainerBuilder, DiError, Reference, ServiceDefinition};
6
7use crate::{Application, Command};
8
9/// Service tag applied to console command definitions.
10pub const COMMAND_TAG: &str = "console.command";
11
12/// Container id of the compiled [`Application`].
13pub const APPLICATION_SERVICE: &str = "console.application";
14
15/// Newtype so command trait objects can be stored in the container.
16#[derive(Clone)]
17pub struct CommandService(pub Arc<dyn Command>);
18
19/// Registers [`APPLICATION_SERVICE`] from services tagged [`COMMAND_TAG`].
20#[derive(Debug, Default)]
21pub struct RegisterCommandsPass;
22
23impl CompilePass for RegisterCommandsPass {
24    fn name(&self) -> &'static str {
25        "register_console_commands"
26    }
27
28    fn process(&self, builder: &mut ContainerBuilder) -> Result<(), DiError> {
29        let tagged: Vec<String> = builder
30            .definitions()
31            .iter()
32            .filter(|definition| definition.tags().iter().any(|tag| tag == COMMAND_TAG))
33            .map(|definition| definition.id().to_owned())
34            .collect();
35
36        let dependencies = tagged
37            .iter()
38            .map(|id| Reference::from(id.clone()))
39            .collect();
40        builder.register(
41            ServiceDefinition::new(APPLICATION_SERVICE).with_dependencies(dependencies),
42            move |container| {
43                let mut application = Application::new();
44                for id in &tagged {
45                    let wrapped = container.get_as::<CommandService>(id)?;
46                    application.add(Arc::clone(&wrapped.0));
47                }
48                Ok(Box::new(application))
49            },
50        )
51    }
52}