Skip to main content

polyxml_cli/
config.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use glob::glob;
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8
9#[derive(Debug, Error)]
10pub enum ConfigError {
11    #[error("I/O error reading configuration: {0}")]
12    Io(#[from] std::io::Error),
13
14    #[error("TOML syntax error: {0}")]
15    Toml(#[from] toml::de::Error),
16
17    #[error("Invalid glob pattern '{pattern}': {error}")]
18    GlobPattern {
19        pattern: String,
20        error: glob::PatternError,
21    },
22
23    #[error("Failed to read glob path: {0}")]
24    Glob(#[from] glob::GlobError),
25
26    #[error("Module '{module}' depends on unknown module '{dependency}'")]
27    UnknownModuleDependency { module: String, dependency: String },
28
29    #[error("Cycle in workspace module dependencies involving '{0}'")]
30    ModuleCycle(String),
31
32    #[error("Invalid module name '{0}': use ASCII letters, digits, and underscores, starting with a letter or underscore")]
33    InvalidModuleName(String),
34}
35
36/// The top-level `polyxml.toml` workspace manifest.
37#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
38pub struct WorkspaceManifest {
39    pub workspace: Option<WorkspaceSection>,
40    #[serde(default)]
41    pub generate: Vec<TargetConfig>,
42    pub codegen: Option<HashMap<String, CodegenTargetConfig>>,
43    #[serde(default)]
44    pub modules: BTreeMap<String, ModuleConfig>,
45}
46
47/// A schema package compiled once and imported by dependent packages.
48#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct ModuleConfig {
51    #[serde(default)]
52    pub schemas: Vec<String>,
53    #[serde(default)]
54    pub root_elements: Vec<String>,
55    #[serde(default)]
56    pub depends_on: Vec<String>,
57}
58
59#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
60pub struct WorkspaceSection {
61    pub name: Option<String>,
62    #[serde(default)]
63    pub schemas: Vec<String>,
64    #[serde(default)]
65    pub root_elements: Vec<String>,
66    pub include_dirs: Option<Vec<String>>,
67    pub output_base_dir: Option<String>,
68    pub custom_header: Option<String>,
69    pub go_module: Option<String>,
70}
71
72/// Target configuration from either `[[generate]]` or `[codegen.<target>]`.
73/// Unknown keys are rejected so misspelled or unsupported options fail
74/// instead of being silently ignored.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct TargetConfig {
78    pub target: String,
79    pub output: String,
80    pub enabled: Option<bool>,
81    pub backend: Option<String>,
82    #[serde(default)]
83    pub features: Vec<String>,
84    pub package: Option<String>,
85    pub namespace: Option<String>,
86    pub strict_facets: Option<bool>,
87    pub slots: Option<bool>,
88    pub kw_only: Option<bool>,
89    pub zero_copy: Option<bool>,
90    pub codecs: Option<bool>,
91    pub standard: Option<String>,
92    pub derive_traits: Option<Vec<String>>,
93    pub box_cycles: Option<bool>,
94    pub modules: Option<bool>,
95    pub mode: Option<String>,
96    pub serializer: Option<String>,
97    pub style: Option<String>,
98    pub custom_header: Option<String>,
99    pub split_units: Option<bool>,
100    pub chunk_size: Option<usize>,
101}
102
103#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(deny_unknown_fields)]
105pub struct CodegenTargetConfig {
106    pub enabled: Option<bool>,
107    pub output: Option<String>,
108    pub backend: Option<String>,
109    #[serde(default)]
110    pub features: Vec<String>,
111    pub package: Option<String>,
112    pub namespace: Option<String>,
113    pub strict_facets: Option<bool>,
114    pub slots: Option<bool>,
115    pub kw_only: Option<bool>,
116    pub zero_copy: Option<bool>,
117    pub codecs: Option<bool>,
118    pub standard: Option<String>,
119    pub derive_traits: Option<Vec<String>>,
120    pub box_cycles: Option<bool>,
121    pub modules: Option<bool>,
122    pub mode: Option<String>,
123    pub serializer: Option<String>,
124    pub style: Option<String>,
125    pub custom_header: Option<String>,
126    pub split_units: Option<bool>,
127    pub chunk_size: Option<usize>,
128}
129
130impl std::str::FromStr for WorkspaceManifest {
131    type Err = ConfigError;
132
133    fn from_str(toml_str: &str) -> Result<Self, Self::Err> {
134        let manifest: WorkspaceManifest = toml::from_str(toml_str)?;
135        Ok(manifest)
136    }
137}
138
139impl WorkspaceManifest {
140    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
141        let content = fs::read_to_string(path)?;
142        content.parse()
143    }
144
145    /// Retrieve all configured target configurations, combining `[[generate]]`
146    /// and `[codegen.<target>]` definitions.
147    pub fn resolved_targets(&self) -> Vec<TargetConfig> {
148        let mut targets = Vec::new();
149
150        let ws_header = self
151            .workspace
152            .as_ref()
153            .and_then(|w| w.custom_header.clone());
154
155        // 1. Array of tables [[generate]]
156        for gen in &self.generate {
157            if gen.enabled.unwrap_or(true) {
158                let mut target = gen.clone();
159                if target.custom_header.is_none() {
160                    target.custom_header = ws_header.clone();
161                }
162                targets.push(target);
163            }
164        }
165
166        // 2. Table-based [codegen.<lang>]
167        if let Some(ref codegen_map) = self.codegen {
168            for (lang, cfg) in codegen_map {
169                if cfg.enabled.unwrap_or(true) {
170                    let output = cfg
171                        .output
172                        .clone()
173                        .unwrap_or_else(|| format!("generated/{}", lang));
174
175                    targets.push(TargetConfig {
176                        target: lang.clone(),
177                        output,
178                        enabled: cfg.enabled,
179                        backend: cfg.backend.clone(),
180                        features: cfg.features.clone(),
181                        package: cfg.package.clone(),
182                        namespace: cfg.namespace.clone(),
183                        strict_facets: cfg.strict_facets,
184                        slots: cfg.slots,
185                        kw_only: cfg.kw_only,
186                        zero_copy: cfg.zero_copy,
187                        codecs: cfg.codecs,
188                        standard: cfg.standard.clone(),
189                        derive_traits: cfg.derive_traits.clone(),
190                        box_cycles: cfg.box_cycles,
191                        modules: cfg.modules,
192                        mode: cfg.mode.clone(),
193                        serializer: cfg.serializer.clone(),
194                        style: cfg.style.clone(),
195                        custom_header: cfg.custom_header.clone().or_else(|| ws_header.clone()),
196                        split_units: cfg.split_units,
197                        chunk_size: cfg.chunk_size,
198                    });
199                }
200            }
201        }
202
203        targets
204    }
205
206    /// Expand all schema glob patterns in `workspace.schemas` relative to base directory.
207    pub fn expand_schemas(&self, base_dir: &Path) -> Result<Vec<PathBuf>, ConfigError> {
208        let Some(ref ws) = self.workspace else {
209            return Ok(Vec::new());
210        };
211
212        expand_patterns(&ws.schemas, base_dir)
213    }
214
215    pub fn expand_module_schemas(
216        &self,
217        name: &str,
218        base_dir: &Path,
219    ) -> Result<Vec<PathBuf>, ConfigError> {
220        let Some(module) = self.modules.get(name) else {
221            return Ok(Vec::new());
222        };
223        expand_patterns(&module.schemas, base_dir)
224    }
225
226    pub fn module_order(&self) -> Result<Vec<String>, ConfigError> {
227        for name in self.modules.keys() {
228            let mut chars = name.chars();
229            if !chars
230                .next()
231                .is_some_and(|ch| ch.is_ascii_alphabetic() || ch == '_')
232                || !chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
233            {
234                return Err(ConfigError::InvalidModuleName(name.clone()));
235            }
236        }
237        let mut order = Vec::new();
238        let mut visiting = HashSet::new();
239        let mut visited = HashSet::new();
240        fn visit(
241            name: &str,
242            manifest: &WorkspaceManifest,
243            visiting: &mut HashSet<String>,
244            visited: &mut HashSet<String>,
245            order: &mut Vec<String>,
246        ) -> Result<(), ConfigError> {
247            if visited.contains(name) {
248                return Ok(());
249            }
250            if !visiting.insert(name.to_string()) {
251                return Err(ConfigError::ModuleCycle(name.to_string()));
252            }
253            let module = &manifest.modules[name];
254            for dependency in &module.depends_on {
255                if !manifest.modules.contains_key(dependency) {
256                    return Err(ConfigError::UnknownModuleDependency {
257                        module: name.to_string(),
258                        dependency: dependency.clone(),
259                    });
260                }
261                visit(dependency, manifest, visiting, visited, order)?;
262            }
263            visiting.remove(name);
264            visited.insert(name.to_string());
265            order.push(name.to_string());
266            Ok(())
267        }
268        for name in self.modules.keys() {
269            visit(name, self, &mut visiting, &mut visited, &mut order)?;
270        }
271        Ok(order)
272    }
273}
274
275fn expand_patterns(patterns: &[String], base_dir: &Path) -> Result<Vec<PathBuf>, ConfigError> {
276    let mut paths = Vec::new();
277    for pattern in patterns {
278        let full_pattern = if Path::new(pattern).is_absolute() {
279            pattern.clone()
280        } else {
281            base_dir.join(pattern).to_string_lossy().to_string()
282        };
283
284        let entries = glob(&full_pattern).map_err(|e| ConfigError::GlobPattern {
285            pattern: full_pattern.clone(),
286            error: e,
287        })?;
288
289        for entry in entries {
290            let path = entry?;
291            if path.is_file() {
292                paths.push(path);
293            }
294        }
295    }
296
297    paths.sort();
298    paths.dedup();
299    Ok(paths)
300}