Skip to main content

santa_data/
lib.rs

1//! Santa Data - Data models, configuration, and CCL parser for Santa Package Manager
2//!
3//! This crate provides:
4//! - Core data models (Platform, KnownSources, PackageData, etc.)
5//! - Configuration loading and management (SantaConfig, ConfigLoader)
6//! - CCL schema definitions (PackageDefinition, SourceDefinition, etc.)
7//! - CCL parsing that handles both simple and complex formats
8
9use anyhow::{Context, Result};
10use serde::de::DeserializeOwned;
11use serde_json::Value;
12use std::collections::HashMap;
13
14pub mod config;
15pub mod models;
16pub mod schemas;
17
18pub use config::{
19    ConfigLoader, ConfigPackageSource, PackageNameOverride, SantaConfig, SantaConfigBuilder,
20    SourceList,
21};
22pub use models::{
23    Arch, CommandName, Distro, KnownSources, PackageData, PackageDataList, PackageName, Platform,
24    SourceName, OS,
25};
26pub use schemas::{
27    ComplexPackageDefinition, ConfigDefinition, ConfigSettings, PackageDefinition,
28    PlatformOverride, SourceConfig, SourceDefinition, SourceSpecificConfig, SourcesDefinition,
29};
30
31/// Parse CCL string into a HashMap where values can be either arrays or objects
32///
33/// With sickle, this function directly deserializes CCL into proper Value types.
34///
35/// # Examples
36///
37/// ```
38/// use santa_data::parse_to_hashmap;
39/// use serde_json::Value;
40///
41/// let ccl = r#"
42/// simple_pkg =
43///   = brew
44///   = scoop
45///
46/// complex_pkg =
47///   _sources =
48///     = brew
49///   brew = gh
50/// "#;
51///
52/// let result = parse_to_hashmap(ccl).unwrap();
53/// assert!(result.contains_key("simple_pkg"));
54/// assert!(result.contains_key("complex_pkg"));
55/// ```
56pub fn parse_to_hashmap(ccl_content: &str) -> Result<HashMap<String, Value>> {
57    // Parse using sickle's load function (parse + build_hierarchy)
58    let model = sickle::load(ccl_content).context("Failed to parse CCL with sickle")?;
59
60    // Convert the model to a HashMap<String, Value>
61    model_to_hashmap(&model)
62}
63
64/// Convert a sickle Model to a HashMap<String, Value>
65fn model_to_hashmap(model: &sickle::CclObject) -> Result<HashMap<String, Value>> {
66    let mut result = HashMap::new();
67
68    for (key, value) in model.iter() {
69        result.insert(key.clone(), model_to_value(value)?);
70    }
71
72    Ok(result)
73}
74
75/// Convert a sickle Model to a serde_json Value
76fn model_to_value(model: &sickle::CclObject) -> Result<Value> {
77    // Check if this is a list with empty keys (CCL: = item1\n = item2)
78    // Empty keys have all their values stored in a Vec under the "" key
79    if let Ok(empty_key_values) = model.get_all("") {
80        if !empty_key_values.is_empty() {
81            // Check if all values are simple string values (single key with empty value)
82            let all_simple_strings = empty_key_values
83                .iter()
84                .all(|v| v.len() == 1 && v.values().all(|child| child.is_empty()));
85
86            if all_simple_strings {
87                // Extract string values
88                let values: Vec<Value> = empty_key_values
89                    .iter()
90                    .filter_map(|v| v.keys().next().cloned())
91                    .map(Value::String)
92                    .collect();
93                return Ok(Value::Array(values));
94            } else {
95                // Convert each value recursively
96                let values: Vec<Value> = empty_key_values
97                    .iter()
98                    .map(model_to_value)
99                    .collect::<Result<Vec<_>>>()?;
100                return Ok(Value::Array(values));
101            }
102        }
103    }
104
105    // Fast path for singleton maps
106    if model.len() == 1 {
107        let (key, value) = model.iter().next().unwrap();
108
109        // Check if this is a singleton string: {"value": {}}
110        if value.is_empty() {
111            return Ok(Value::String(key.clone()));
112        }
113    }
114
115    // Check if this is a list (multiple keys all with empty values)
116    if model.len() > 1 && model.values().all(|v| v.is_empty()) {
117        // This is a list - keys are the list items
118        let values: Vec<Value> = model.keys().map(|k| Value::String(k.clone())).collect();
119        return Ok(Value::Array(values));
120    }
121
122    // Otherwise, it's a map (object)
123    let mut obj = serde_json::Map::new();
124    for (k, v) in model.iter() {
125        obj.insert(k.clone(), model_to_value(v)?);
126    }
127    Ok(Value::Object(obj))
128}
129
130/// Parse CCL string and deserialize into a specific type
131///
132/// # Examples
133///
134/// ```
135/// use santa_data::parse_ccl_to;
136/// use serde::Deserialize;
137/// use std::collections::HashMap;
138///
139/// #[derive(Deserialize)]
140/// struct Package {
141///     #[serde(rename = "_sources")]
142///     sources: Option<Vec<String>>,
143/// }
144///
145/// let ccl = r#"
146/// bat =
147///   _sources =
148///     = brew
149///     = scoop
150/// "#;
151///
152/// let packages: HashMap<String, Package> = parse_ccl_to(ccl).unwrap();
153/// assert!(packages.contains_key("bat"));
154/// ```
155pub fn parse_ccl_to<T: DeserializeOwned>(ccl_content: &str) -> Result<T> {
156    // Normalize CRLF to LF for cross-platform compatibility (e.g. Windows checkouts)
157    let options =
158        sickle::ParserOptions::default().with_crlf(sickle::options::CrlfBehavior::NormalizeToLf);
159    sickle::from_str_with_options(ccl_content, &options).context("Failed to deserialize parsed CCL")
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn test_parse_simple_array() {
168        let ccl = r#"
169test_pkg =
170  = brew
171  = scoop
172  = pacman
173"#;
174        let result = parse_to_hashmap(ccl).unwrap();
175
176        assert!(result.contains_key("test_pkg"));
177        let value = &result["test_pkg"];
178        println!("DEBUG test_pkg value: {:#?}", value);
179        assert!(value.is_array());
180
181        let arr = value.as_array().unwrap();
182        assert_eq!(arr.len(), 3);
183        assert_eq!(arr[0].as_str().unwrap(), "brew");
184        assert_eq!(arr[1].as_str().unwrap(), "scoop");
185        assert_eq!(arr[2].as_str().unwrap(), "pacman");
186    }
187
188    #[test]
189    fn test_parse_complex_object() {
190        let ccl = r#"
191test_pkg =
192  _sources =
193    = brew
194    = scoop
195  brew = gh
196"#;
197        let result = parse_to_hashmap(ccl).unwrap();
198
199        assert!(result.contains_key("test_pkg"));
200        let value = &result["test_pkg"];
201        println!("Parsed value: {:#?}", value);
202        assert!(value.is_object());
203
204        let obj = value.as_object().unwrap();
205        println!("Object keys: {:?}", obj.keys().collect::<Vec<_>>());
206        assert!(obj.contains_key("_sources"));
207        assert!(obj.contains_key("brew"));
208
209        let sources_value = &obj["_sources"];
210        println!("_sources value: {:#?}", sources_value);
211        let sources = sources_value.as_array().unwrap();
212        assert_eq!(sources.len(), 2);
213
214        let brew_override = obj["brew"].as_str().unwrap();
215        assert_eq!(brew_override, "gh");
216    }
217
218    #[test]
219    fn test_parse_multiple_packages() {
220        let ccl = r#"
221simple =
222  = brew
223  = scoop
224
225complex =
226  _sources =
227    = pacman
228  _platforms =
229    = linux
230"#;
231        let result = parse_to_hashmap(ccl).unwrap();
232
233        assert_eq!(result.len(), 2);
234        assert!(result["simple"].is_array());
235        assert!(result["complex"].is_object());
236    }
237}