Skip to main content

elemental_addon/builtins/
custom_patch.rs

1use async_trait::async_trait;
2use elemental_driver::families::version_json::MetadataPatch;
3
4use crate::{
5    addon::{
6        Addon, AddonCompatibility, AddonContext, AddonDescriptor, AddonPrepareOutput,
7        AddonPrepareRequest,
8    },
9    error::Result,
10};
11
12/// Addon wrapping a user-provided declarative [`MetadataPatch`].
13#[derive(Debug, Clone)]
14pub struct CustomPatchAddon {
15    descriptor: AddonDescriptor,
16    version: Option<String>,
17    patch: MetadataPatch,
18    allowed_drivers: Option<Vec<&'static str>>,
19}
20
21impl CustomPatchAddon {
22    /// Creates an addon that applies `patch` under the given `id` and `name`.
23    pub fn new(
24        id: impl Into<std::borrow::Cow<'static, str>>,
25        name: impl Into<std::borrow::Cow<'static, str>>,
26        patch: MetadataPatch,
27    ) -> Self {
28        Self {
29            descriptor: AddonDescriptor::new(id, name),
30            version: None,
31            patch,
32            allowed_drivers: None,
33        }
34    }
35
36    /// Sets the default version string recorded when the caller omits one.
37    pub fn with_version(mut self, version: impl Into<String>) -> Self {
38        self.version = Some(version.into());
39        self
40    }
41
42    /// Restricts compatibility to instances using one of the specified driver IDs.
43    pub fn with_allowed_drivers(mut self, drivers: Vec<&'static str>) -> Self {
44        self.allowed_drivers = Some(drivers);
45        self
46    }
47}
48
49#[async_trait]
50impl Addon for CustomPatchAddon {
51    fn descriptor(&self) -> AddonDescriptor {
52        self.descriptor.clone()
53    }
54
55    fn check_compatibility(&self, ctx: &AddonContext<'_>) -> AddonCompatibility {
56        if let Some(allowed) = &self.allowed_drivers
57            && !allowed.contains(&ctx.driver.id)
58        {
59            return AddonCompatibility::Incompatible {
60                reason: format!(
61                    "driver '{}' is not in allowed drivers {:?}",
62                    ctx.driver.id, allowed
63                ),
64            };
65        }
66        AddonCompatibility::Compatible
67    }
68
69    async fn prepare(&self, request: &AddonPrepareRequest<'_>) -> Result<AddonPrepareOutput> {
70        Ok(AddonPrepareOutput {
71            version: request
72                .addon_version
73                .map(str::to_owned)
74                .or_else(|| self.version.clone()),
75            metadata_patch: Some(self.patch.clone()),
76            managed_files: Vec::new(),
77        })
78    }
79}