Skip to main content

santa_data/
config.rs

1//! Configuration loading and management for Santa Package Manager
2//!
3//! This module provides the core configuration structures and loading logic
4//! for Santa. It handles CCL parsing, validation, and provides a clean API
5//! for configuration access.
6
7use crate::models::KnownSources;
8use anyhow::Context;
9use derive_builder::Builder;
10use serde::{Deserialize, Deserializer, Serialize};
11use std::collections::{BTreeMap, HashMap, HashSet};
12use std::path::Path;
13use tracing::{debug, warn};
14use validator::Validate;
15
16/// Type alias for lists of package sources
17pub type SourceList = Vec<ConfigPackageSource>;
18
19/// Helper struct to deserialize custom source with name from HashMap key
20#[derive(Deserialize)]
21struct CustomSourceWithoutName {
22    emoji: String,
23    shell_command: String,
24    #[serde(alias = "install")]
25    install_command: String,
26    #[serde(alias = "check")]
27    check_command: String,
28    #[serde(default)]
29    prepend_to_package_name: Option<String>,
30    #[serde(default)]
31    overrides: Option<Vec<PackageNameOverride>>,
32}
33
34/// Custom deserializer for custom_sources that converts HashMap to Vec and sets names
35fn deserialize_custom_sources<'de, D>(
36    deserializer: D,
37) -> std::result::Result<Option<SourceList>, D::Error>
38where
39    D: Deserializer<'de>,
40{
41    // Use BTreeMap to maintain sorted order by key name
42    let map_opt: Option<BTreeMap<String, CustomSourceWithoutName>> =
43        Option::deserialize(deserializer)?;
44
45    match map_opt {
46        None => Ok(None),
47        Some(map) => {
48            let mut sources = Vec::new();
49            for (name, source_data) in map {
50                // Create ConfigPackageSource with name from HashMap key
51                let source = ConfigPackageSource {
52                    name: KnownSources::Unknown(name),
53                    emoji: source_data.emoji,
54                    shell_command: source_data.shell_command,
55                    install_command: source_data.install_command,
56                    check_command: source_data.check_command,
57                    prepend_to_package_name: source_data.prepend_to_package_name,
58                    overrides: source_data.overrides,
59                };
60                sources.push(source);
61            }
62            Ok(Some(sources))
63        }
64    }
65}
66
67/// Represents a package name override (renaming packages for specific sources)
68#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
69#[non_exhaustive]
70pub struct PackageNameOverride {
71    pub package: String,
72    pub replacement: String,
73}
74
75/// Represents a custom package source configuration
76#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
77#[non_exhaustive]
78pub struct ConfigPackageSource {
79    pub name: KnownSources,
80    pub emoji: String,
81    pub shell_command: String,
82    pub install_command: String,
83    pub check_command: String,
84    #[serde(default)]
85    pub prepend_to_package_name: Option<String>,
86    #[serde(default)]
87    pub overrides: Option<Vec<PackageNameOverride>>,
88}
89
90/// Main configuration structure for Santa
91#[derive(Serialize, Deserialize, Clone, Debug, Builder, Validate)]
92#[builder(setter(into))]
93#[non_exhaustive]
94pub struct SantaConfig {
95    #[validate(length(min = 1, message = "At least one source must be configured"))]
96    pub sources: Vec<KnownSources>,
97    #[validate(length(min = 1, message = "At least one package should be configured"))]
98    pub packages: Vec<String>,
99    #[serde(
100        default,
101        deserialize_with = "deserialize_custom_sources",
102        skip_serializing_if = "Option::is_none"
103    )]
104    pub custom_sources: Option<SourceList>,
105
106    #[serde(skip)]
107    pub _groups: Option<HashMap<KnownSources, Vec<String>>>,
108    #[serde(skip)]
109    pub log_level: u8,
110}
111
112impl PackageNameOverride {
113    /// Create a new `PackageNameOverride` mapping `package` to `replacement`.
114    pub fn new(package: String, replacement: String) -> Self {
115        Self {
116            package,
117            replacement,
118        }
119    }
120}
121
122impl ConfigPackageSource {
123    /// Create a new `ConfigPackageSource` describing a custom package source.
124    pub fn new(
125        name: KnownSources,
126        emoji: String,
127        shell_command: String,
128        install_command: String,
129        check_command: String,
130        prepend_to_package_name: Option<String>,
131        overrides: Option<Vec<PackageNameOverride>>,
132    ) -> Self {
133        Self {
134            name,
135            emoji,
136            shell_command,
137            install_command,
138            check_command,
139            prepend_to_package_name,
140            overrides,
141        }
142    }
143}
144
145impl SantaConfig {
146    /// Create a new `SantaConfig` from the given sources and packages. The
147    /// `custom_sources`, `_groups`, and `log_level` fields are initialized to
148    /// their defaults.
149    pub fn new(sources: Vec<KnownSources>, packages: Vec<String>) -> Self {
150        Self {
151            sources,
152            packages,
153            custom_sources: None,
154            _groups: None,
155            log_level: 0,
156        }
157    }
158
159    /// Load configuration from a string (CCL format)
160    ///
161    /// # Example
162    /// ```
163    /// use santa_data::config::SantaConfig;
164    ///
165    /// let ccl = r#"
166    /// sources =
167    ///   = brew
168    ///   = cargo
169    /// packages =
170    ///   = git
171    /// "#;
172    ///
173    /// let config = SantaConfig::load_from_str(ccl).unwrap();
174    /// assert_eq!(config.sources.len(), 2);
175    /// ```
176    pub fn load_from_str(config_str: &str) -> anyhow::Result<Self> {
177        let data: SantaConfig = sickle::from_str(config_str)
178            .with_context(|| format!("Failed to parse CCL config: {config_str}"))?;
179
180        // Validate the configuration
181        data.validate_basic()
182            .with_context(|| "Configuration validation failed")?;
183
184        Ok(data)
185    }
186
187    /// Load configuration from a file path
188    ///
189    /// # Example
190    /// ```no_run
191    /// use santa_data::config::SantaConfig;
192    /// use std::path::Path;
193    ///
194    /// let config = SantaConfig::load_from(Path::new("santa.ccl")).unwrap();
195    /// ```
196    pub fn load_from(file: &Path) -> anyhow::Result<Self> {
197        debug!("Loading config from: {}", file.display());
198
199        if file.exists() {
200            let config_str = std::fs::read_to_string(file)
201                .with_context(|| format!("Failed to read config file: {}", file.display()))?;
202
203            let config: SantaConfig = sickle::from_str(&config_str)
204                .with_context(|| format!("Failed to parse CCL config file: {}", file.display()))?;
205
206            config
207                .validate_basic()
208                .with_context(|| "Configuration validation failed")?;
209
210            Ok(config)
211        } else {
212            warn!("Can't find config file: {}", file.display());
213            warn!("Returning error - no default config in santa-data");
214            Err(anyhow::anyhow!("Config file not found: {}", file.display()))
215        }
216    }
217
218    /// Basic configuration validation
219    ///
220    /// Checks for:
221    /// - At least one source is configured
222    /// - No duplicate sources
223    /// - Warns about duplicate packages
224    pub fn validate_basic(&self) -> anyhow::Result<()> {
225        if self.sources.is_empty() {
226            return Err(anyhow::anyhow!("At least one source must be configured"));
227        }
228
229        if self.packages.is_empty() {
230            warn!("No packages configured - santa will not track any packages");
231        }
232
233        // Check for duplicate sources
234        let mut seen_sources = HashSet::new();
235        for source in &self.sources {
236            if !seen_sources.insert(source) {
237                return Err(anyhow::anyhow!("Duplicate source found: {:?}", source));
238            }
239        }
240
241        // Check for duplicate packages
242        let mut seen_packages = HashSet::new();
243        for package in &self.packages {
244            if !seen_packages.insert(package) {
245                warn!("Duplicate package found: {}", package);
246            }
247        }
248
249        Ok(())
250    }
251}
252
253/// Configuration loader - provides static methods for loading configurations
254pub struct ConfigLoader;
255
256impl ConfigLoader {
257    /// Load configuration from a file path
258    pub fn load_from_path(path: &Path) -> anyhow::Result<SantaConfig> {
259        SantaConfig::load_from(path)
260    }
261
262    /// Load configuration from a string
263    pub fn load_from_str(contents: &str) -> anyhow::Result<SantaConfig> {
264        SantaConfig::load_from_str(contents)
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271    use crate::KnownSources;
272
273    #[test]
274    fn test_validate_basic_empty_sources() {
275        let config = SantaConfig {
276            sources: vec![],
277            packages: vec!["git".to_string()],
278            custom_sources: None,
279            _groups: None,
280            log_level: 0,
281        };
282
283        let result = config.validate_basic();
284        assert!(result.is_err());
285        assert!(result
286            .unwrap_err()
287            .to_string()
288            .contains("At least one source must be configured"));
289    }
290
291    #[test]
292    fn test_validate_basic_duplicate_sources() {
293        let config = SantaConfig {
294            sources: vec![KnownSources::Brew, KnownSources::Brew],
295            packages: vec!["git".to_string()],
296            custom_sources: None,
297            _groups: None,
298            log_level: 0,
299        };
300
301        let result = config.validate_basic();
302        assert!(result.is_err());
303        assert!(result
304            .unwrap_err()
305            .to_string()
306            .contains("Duplicate source found"));
307    }
308
309    #[test]
310    fn test_validate_basic_valid_config() {
311        let config = SantaConfig {
312            sources: vec![KnownSources::Brew, KnownSources::Cargo],
313            packages: vec!["git".to_string(), "rust".to_string()],
314            custom_sources: None,
315            _groups: None,
316            log_level: 0,
317        };
318
319        let result = config.validate_basic();
320        assert!(result.is_ok());
321    }
322
323    #[test]
324    fn test_load_from_str_valid_ccl() {
325        let ccl = r#"
326sources =
327  = brew
328  = cargo
329packages =
330  = git
331  = rust
332        "#;
333
334        let result = SantaConfig::load_from_str(ccl);
335        assert!(result.is_ok());
336
337        let config = result.unwrap();
338        assert_eq!(config.sources.len(), 2);
339        assert_eq!(config.packages.len(), 2);
340        assert!(config.sources.contains(&KnownSources::Brew));
341        assert!(config.sources.contains(&KnownSources::Cargo));
342    }
343
344    #[test]
345    fn test_load_from_str_invalid_ccl() {
346        let ccl = "invalid = yaml = content = ["; // Malformed CCL
347
348        let result = SantaConfig::load_from_str(ccl);
349        assert!(result.is_err());
350        assert!(result
351            .unwrap_err()
352            .to_string()
353            .contains("Failed to parse CCL config"));
354    }
355
356    #[test]
357    fn test_load_from_str_validation_failure() {
358        let ccl = r#"
359sources =
360packages =
361  = git
362        "#;
363
364        let result = SantaConfig::load_from_str(ccl);
365        assert!(result.is_err());
366        // The error should be about missing sources, which is caught during validation
367        let error_msg = result.unwrap_err().to_string();
368        eprintln!("Actual error message: {}", error_msg);
369        assert!(
370            error_msg.contains("Configuration validation failed")
371                || error_msg.contains("At least one source must be configured")
372                || error_msg.contains("Failed to parse CCL config")
373        );
374    }
375
376    #[test]
377    fn test_config_loader_from_str() {
378        let ccl = r#"
379sources =
380  = cargo
381packages =
382  = ripgrep
383        "#;
384
385        let result = ConfigLoader::load_from_str(ccl);
386        assert!(result.is_ok());
387    }
388}