Skip to main content

lefthk_core/config/command/
mod.rs

1mod chord;
2mod execute;
3mod exit_chord;
4mod kill;
5mod reload;
6
7pub mod utils;
8
9use self::utils::{
10    denormalize_function::DenormalizeCommandFunction, normalized_command::NormalizedCommand,
11};
12use crate::errors::{Error, LeftError, Result};
13use crate::worker::Worker;
14
15pub use self::{chord::Chord, execute::Execute, exit_chord::ExitChord, kill::Kill, reload::Reload};
16
17inventory::collect!(DenormalizeCommandFunction);
18
19/// When adding a command:
20///  - a command has to submit itself to the inventory
21///  - write a test that it's conversion between normalizel and denormalize works
22pub trait Command: std::fmt::Debug {
23    fn normalize(&self) -> NormalizedCommand;
24
25    fn denormalize(generalized: &NormalizedCommand) -> Option<Box<Self>>
26    where
27        Self: Sized;
28
29    /// # Errors
30    ///
31    /// This errors when the command cannot be executed by the worker
32    fn execute(&self, worker: &mut Worker) -> Error;
33
34    fn get_name(&self) -> &'static str;
35}
36
37/// # Errors
38///
39/// This errors when the command cannot be matched with the known commands
40pub fn denormalize(normalized_command: &NormalizedCommand) -> Result<Box<dyn Command>> {
41    for denormalizer in inventory::iter::<DenormalizeCommandFunction> {
42        if let Some(denormalized_command) = (denormalizer.0)(normalized_command) {
43            return Ok(denormalized_command);
44        }
45    }
46    Err(LeftError::UnmatchingCommand)
47}