Skip to main content

santa_data/
schemas.rs

1// Schema-based data structures for Santa Package Manager
2// These structs match the YAML schemas defined in /data/*.yaml files
3
4use crate::models::{Platform, OS};
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7
8/// Package definition matching package_schema.yaml
9/// Supports both simple array format and complex object format
10#[derive(Debug, Clone, Serialize, Deserialize)]
11#[serde(untagged)]
12pub enum PackageDefinition {
13    /// Simple array format: just a list of source names
14    Simple(Vec<String>),
15    /// Complex object format: with metadata and source-specific configs
16    Complex(ComplexPackageDefinition),
17}
18
19impl PackageDefinition {
20    /// Get all sources where this package is available
21    pub fn get_sources(&self) -> Vec<&str> {
22        match self {
23            PackageDefinition::Simple(sources) => sources.iter().map(|s| s.as_str()).collect(),
24            PackageDefinition::Complex(complex) => complex.get_sources(),
25        }
26    }
27
28    /// Get source-specific configuration for a source
29    pub fn get_source_config(&self, source: &str) -> Option<&SourceSpecificConfig> {
30        match self {
31            PackageDefinition::Simple(_) => None,
32            PackageDefinition::Complex(complex) => complex.get_source_config(source),
33        }
34    }
35
36    /// Check if package is available in a specific source
37    pub fn is_available_in(&self, source: &str) -> bool {
38        self.get_sources().contains(&source)
39    }
40
41    /// Get the package description if available
42    pub fn get_description(&self) -> Option<&str> {
43        match self {
44            PackageDefinition::Simple(_) => None,
45            PackageDefinition::Complex(complex) => complex.description.as_deref(),
46        }
47    }
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize, Default)]
51#[serde(default)]
52#[non_exhaustive]
53pub struct ComplexPackageDefinition {
54    /// Short description of the package
55    #[serde(rename = "_description", skip_serializing_if = "Option::is_none")]
56    pub description: Option<String>,
57
58    /// List of sources where package is available with same name as key
59    #[serde(rename = "_sources", skip_serializing_if = "Option::is_none")]
60    pub sources: Option<Vec<String>>,
61
62    /// Platforms where this package is available
63    #[serde(rename = "_platforms", skip_serializing_if = "Option::is_none")]
64    pub platforms: Option<Vec<String>>,
65
66    /// Alternative names for search and discovery
67    #[serde(rename = "_aliases", skip_serializing_if = "Option::is_none")]
68    pub aliases: Option<Vec<String>>,
69
70    /// Source-specific configurations (flatten other fields)
71    #[serde(flatten)]
72    pub source_configs: HashMap<String, SourceSpecificConfig>,
73}
74
75/// Source-specific configuration for a package
76#[derive(Debug, Clone, Serialize, Deserialize)]
77#[serde(untagged)]
78pub enum SourceSpecificConfig {
79    /// Simple name override
80    Name(String),
81    /// Complex configuration with hooks and modifications
82    Complex(SourceConfig),
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[non_exhaustive]
87pub struct SourceConfig {
88    /// Override package name for this source
89    pub name: Option<String>,
90    /// Command to run before installation
91    pub pre: Option<String>,
92    /// Command to run after successful installation  
93    pub post: Option<String>,
94    /// String to prepend to package name during installation
95    pub prefix: Option<String>,
96    /// String to append to the install command
97    pub install_suffix: Option<String>,
98}
99
100/// Sources configuration matching sources_schema.yaml
101pub type SourcesDefinition = HashMap<String, SourceDefinition>;
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
104#[non_exhaustive]
105pub struct SourceDefinition {
106    /// Emoji icon to represent this source
107    pub emoji: String,
108    /// Command template to install packages
109    pub install: String,
110    /// Command to list installed packages from this source
111    pub check: String,
112    /// String to prepend to package names (optional)
113    pub prefix: Option<String>,
114    /// Platform-specific command overrides
115    #[serde(rename = "_overrides", skip_serializing_if = "Option::is_none")]
116    pub overrides: Option<HashMap<String, PlatformOverride>>,
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize)]
120#[non_exhaustive]
121pub struct PlatformOverride {
122    pub install: Option<String>,
123    pub check: Option<String>,
124}
125
126/// Configuration matching config_schema.yaml
127#[derive(Debug, Clone, Serialize, Deserialize)]
128#[non_exhaustive]
129pub struct ConfigDefinition {
130    /// List of package sources to use (in priority order)
131    pub sources: Vec<String>,
132    /// List of packages to install/manage
133    pub packages: Vec<String>,
134    /// Advanced configuration options
135    #[serde(rename = "_settings", skip_serializing_if = "Option::is_none")]
136    pub settings: Option<ConfigSettings>,
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize)]
140#[non_exhaustive]
141pub struct ConfigSettings {
142    /// Automatically update packages
143    #[serde(default)]
144    pub auto_update: bool,
145    /// Maximum parallel package installations
146    #[serde(default = "default_parallel_installs")]
147    pub parallel_installs: u8,
148    /// Ask for confirmation before installing packages
149    #[serde(default = "default_true")]
150    pub confirm_before_install: bool,
151}
152
153fn default_parallel_installs() -> u8 {
154    3
155}
156fn default_true() -> bool {
157    true
158}
159
160impl ComplexPackageDefinition {
161    /// Create a new ComplexPackageDefinition with the given sources
162    pub fn with_sources(sources: Vec<String>) -> Self {
163        Self {
164            sources: Some(sources),
165            ..Default::default()
166        }
167    }
168
169    /// Set the platforms for this package definition
170    pub fn set_platforms(&mut self, platforms: Vec<String>) {
171        self.platforms = Some(platforms);
172    }
173
174    /// Set the aliases for this package definition
175    pub fn set_aliases(&mut self, aliases: Vec<String>) {
176        self.aliases = Some(aliases);
177    }
178
179    /// Set the description for this package definition
180    pub fn set_description(&mut self, description: String) {
181        self.description = Some(description);
182    }
183
184    /// Get all sources where this package is available
185    pub fn get_sources(&self) -> Vec<&str> {
186        let mut all_sources = Vec::new();
187
188        // Add sources from _sources array
189        if let Some(sources) = &self.sources {
190            all_sources.extend(sources.iter().map(|s| s.as_str()));
191        }
192
193        // Add sources from explicit configurations
194        all_sources.extend(self.source_configs.keys().map(|s| s.as_str()));
195
196        all_sources
197    }
198
199    /// Get source-specific configuration for a source
200    pub fn get_source_config(&self, source: &str) -> Option<&SourceSpecificConfig> {
201        self.source_configs.get(source)
202    }
203
204    /// Check if package is available in a specific source
205    pub fn is_available_in(&self, source: &str) -> bool {
206        self.get_sources().contains(&source)
207    }
208}
209
210impl SourceConfig {
211    /// Create a new `SourceConfig` with the given source-specific overrides.
212    pub fn new(
213        name: Option<String>,
214        pre: Option<String>,
215        post: Option<String>,
216        prefix: Option<String>,
217        install_suffix: Option<String>,
218    ) -> Self {
219        Self {
220            name,
221            pre,
222            post,
223            prefix,
224            install_suffix,
225        }
226    }
227}
228
229impl PlatformOverride {
230    /// Create a new `PlatformOverride` with the given install and check commands.
231    pub fn new(install: Option<String>, check: Option<String>) -> Self {
232        Self { install, check }
233    }
234}
235
236impl ConfigDefinition {
237    /// Create a new `ConfigDefinition` with the given sources, packages, and settings.
238    pub fn new(
239        sources: Vec<String>,
240        packages: Vec<String>,
241        settings: Option<ConfigSettings>,
242    ) -> Self {
243        Self {
244            sources,
245            packages,
246            settings,
247        }
248    }
249}
250
251impl ConfigSettings {
252    /// Create a new `ConfigSettings` with the given values.
253    pub fn new(auto_update: bool, parallel_installs: u8, confirm_before_install: bool) -> Self {
254        Self {
255            auto_update,
256            parallel_installs,
257            confirm_before_install,
258        }
259    }
260}
261
262impl SourceDefinition {
263    /// Create a new `SourceDefinition` with the given fields.
264    pub fn new(
265        emoji: String,
266        install: String,
267        check: String,
268        prefix: Option<String>,
269        overrides: Option<HashMap<String, PlatformOverride>>,
270    ) -> Self {
271        Self {
272            emoji,
273            install,
274            check,
275            prefix,
276            overrides,
277        }
278    }
279
280    /// Get the appropriate command for the current platform
281    pub fn get_install_command(&self, platform: &Platform) -> &str {
282        if let Some(overrides) = &self.overrides {
283            let platform_key = match platform.os {
284                OS::Windows => "windows",
285                OS::Linux => "linux",
286                OS::Macos => "macos",
287            };
288
289            if let Some(platform_override) = overrides.get(platform_key) {
290                if let Some(install) = &platform_override.install {
291                    return install;
292                }
293            }
294        }
295        &self.install
296    }
297
298    /// Get the appropriate check command for the current platform
299    pub fn get_check_command(&self, platform: &Platform) -> &str {
300        if let Some(overrides) = &self.overrides {
301            let platform_key = match platform.os {
302                OS::Windows => "windows",
303                OS::Linux => "linux",
304                OS::Macos => "macos",
305            };
306
307            if let Some(platform_override) = overrides.get(platform_key) {
308                if let Some(check) = &platform_override.check {
309                    return check;
310                }
311            }
312        }
313        &self.check
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    #[test]
322    fn test_package_definition_simple_format() {
323        // Test simple array format using our custom ccl-parser
324        let ccl = r#"
325bat =
326  = brew
327  = scoop
328  = pacman
329  = nix
330"#;
331        let packages: HashMap<String, PackageDefinition> = crate::parse_ccl_to(ccl).unwrap();
332        let def = packages.get("bat").unwrap();
333
334        assert!(def.is_available_in("brew"));
335        assert!(def.is_available_in("scoop"));
336        assert!(def.is_available_in("pacman"));
337        assert!(def.is_available_in("nix"));
338
339        // Simple format should not have source configs
340        assert!(def.get_source_config("brew").is_none());
341
342        // Check that all sources are present
343        let sources = def.get_sources();
344        assert_eq!(sources.len(), 4);
345        assert!(sources.contains(&"brew"));
346        assert!(sources.contains(&"scoop"));
347        assert!(sources.contains(&"pacman"));
348        assert!(sources.contains(&"nix"));
349    }
350
351    #[test]
352    fn test_package_definition_complex_format() {
353        let ccl = r#"
354ripgrep =
355  brew = gh
356  _sources =
357    = scoop
358    = apt
359    = pacman
360    = nix
361"#;
362        let packages: HashMap<String, PackageDefinition> = crate::parse_ccl_to(ccl).unwrap();
363        let def = packages.get("ripgrep").unwrap();
364
365        assert!(def.is_available_in("brew"));
366        assert!(def.is_available_in("scoop"));
367        assert!(def.get_source_config("brew").is_some());
368
369        // Check that sources list includes all sources
370        let sources = def.get_sources();
371        assert!(sources.contains(&"scoop"));
372        assert!(sources.contains(&"apt"));
373        assert!(sources.contains(&"pacman"));
374        assert!(sources.contains(&"nix"));
375        assert!(sources.contains(&"brew"));
376    }
377
378    #[test]
379    fn test_source_definition() {
380        let ccl = r#"
381emoji = 🍺
382install = brew install {package}
383check = brew leaves --installed-on-request
384"#;
385        let def: SourceDefinition = sickle::from_str(ccl).unwrap();
386
387        assert_eq!(def.emoji, "🍺");
388        assert!(def.install.contains("{package}"));
389    }
390
391    #[test]
392    fn test_package_with_description() {
393        let ccl = r#"
394bat =
395  _description = A cat clone with syntax highlighting.
396  _sources =
397    = brew
398    = scoop
399"#;
400        let packages: HashMap<String, PackageDefinition> = crate::parse_ccl_to(ccl).unwrap();
401        let def = packages.get("bat").unwrap();
402
403        // Should have description
404        assert_eq!(
405            def.get_description(),
406            Some("A cat clone with syntax highlighting.")
407        );
408
409        // Should still have sources
410        assert!(def.is_available_in("brew"));
411        assert!(def.is_available_in("scoop"));
412    }
413
414    #[test]
415    fn test_simple_package_no_description() {
416        let ccl = r#"
417jq =
418  = brew
419  = apt
420"#;
421        let packages: HashMap<String, PackageDefinition> = crate::parse_ccl_to(ccl).unwrap();
422        let def = packages.get("jq").unwrap();
423
424        // Simple format has no description
425        assert_eq!(def.get_description(), None);
426    }
427}