Skip to main content

polyxml_cli/
config.rs

1use std::collections::HashMap;
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
27/// The top-level `polyxml.toml` workspace manifest.
28#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
29pub struct WorkspaceManifest {
30    pub workspace: Option<WorkspaceSection>,
31    #[serde(default)]
32    pub generate: Vec<TargetConfig>,
33    pub codegen: Option<HashMap<String, CodegenTargetConfig>>,
34}
35
36#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
37pub struct WorkspaceSection {
38    pub name: Option<String>,
39    #[serde(default)]
40    pub schemas: Vec<String>,
41    pub include_dirs: Option<Vec<String>>,
42    pub output_base_dir: Option<String>,
43    pub custom_header: Option<String>,
44}
45
46/// Target configuration from either `[[generate]]` or `[codegen.<target>]`.
47/// Unknown keys are rejected so misspelled or unsupported options fail
48/// instead of being silently ignored.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct TargetConfig {
52    pub target: String,
53    pub output: String,
54    pub enabled: Option<bool>,
55    pub backend: Option<String>,
56    #[serde(default)]
57    pub features: Vec<String>,
58    pub package: Option<String>,
59    pub namespace: Option<String>,
60    pub strict_facets: Option<bool>,
61    pub slots: Option<bool>,
62    pub kw_only: Option<bool>,
63    pub zero_copy: Option<bool>,
64    pub codecs: Option<bool>,
65    pub standard: Option<String>,
66    pub derive_traits: Option<Vec<String>>,
67    pub box_cycles: Option<bool>,
68    pub modules: Option<bool>,
69    pub mode: Option<String>,
70    pub serializer: Option<String>,
71    pub style: Option<String>,
72    pub custom_header: Option<String>,
73}
74
75#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct CodegenTargetConfig {
78    pub enabled: Option<bool>,
79    pub output: Option<String>,
80    pub backend: Option<String>,
81    #[serde(default)]
82    pub features: Vec<String>,
83    pub package: Option<String>,
84    pub namespace: Option<String>,
85    pub strict_facets: Option<bool>,
86    pub slots: Option<bool>,
87    pub kw_only: Option<bool>,
88    pub zero_copy: Option<bool>,
89    pub codecs: Option<bool>,
90    pub standard: Option<String>,
91    pub derive_traits: Option<Vec<String>>,
92    pub box_cycles: Option<bool>,
93    pub modules: Option<bool>,
94    pub mode: Option<String>,
95    pub serializer: Option<String>,
96    pub style: Option<String>,
97    pub custom_header: Option<String>,
98}
99
100impl std::str::FromStr for WorkspaceManifest {
101    type Err = ConfigError;
102
103    fn from_str(toml_str: &str) -> Result<Self, Self::Err> {
104        let manifest: WorkspaceManifest = toml::from_str(toml_str)?;
105        Ok(manifest)
106    }
107}
108
109impl WorkspaceManifest {
110    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
111        let content = fs::read_to_string(path)?;
112        content.parse()
113    }
114
115    /// Retrieve all configured target configurations, combining `[[generate]]`
116    /// and `[codegen.<target>]` definitions.
117    pub fn resolved_targets(&self) -> Vec<TargetConfig> {
118        let mut targets = Vec::new();
119
120        let ws_header = self
121            .workspace
122            .as_ref()
123            .and_then(|w| w.custom_header.clone());
124
125        // 1. Array of tables [[generate]]
126        for gen in &self.generate {
127            if gen.enabled.unwrap_or(true) {
128                let mut target = gen.clone();
129                if target.custom_header.is_none() {
130                    target.custom_header = ws_header.clone();
131                }
132                targets.push(target);
133            }
134        }
135
136        // 2. Table-based [codegen.<lang>]
137        if let Some(ref codegen_map) = self.codegen {
138            for (lang, cfg) in codegen_map {
139                if cfg.enabled.unwrap_or(true) {
140                    let output = cfg
141                        .output
142                        .clone()
143                        .unwrap_or_else(|| format!("generated/{}", lang));
144
145                    targets.push(TargetConfig {
146                        target: lang.clone(),
147                        output,
148                        enabled: cfg.enabled,
149                        backend: cfg.backend.clone(),
150                        features: cfg.features.clone(),
151                        package: cfg.package.clone(),
152                        namespace: cfg.namespace.clone(),
153                        strict_facets: cfg.strict_facets,
154                        slots: cfg.slots,
155                        kw_only: cfg.kw_only,
156                        zero_copy: cfg.zero_copy,
157                        codecs: cfg.codecs,
158                        standard: cfg.standard.clone(),
159                        derive_traits: cfg.derive_traits.clone(),
160                        box_cycles: cfg.box_cycles,
161                        modules: cfg.modules,
162                        mode: cfg.mode.clone(),
163                        serializer: cfg.serializer.clone(),
164                        style: cfg.style.clone(),
165                        custom_header: cfg.custom_header.clone().or_else(|| ws_header.clone()),
166                    });
167                }
168            }
169        }
170
171        targets
172    }
173
174    /// Expand all schema glob patterns in `workspace.schemas` relative to base directory.
175    pub fn expand_schemas(&self, base_dir: &Path) -> Result<Vec<PathBuf>, ConfigError> {
176        let mut paths = Vec::new();
177
178        let Some(ref ws) = self.workspace else {
179            return Ok(paths);
180        };
181
182        for pattern in &ws.schemas {
183            let full_pattern = if Path::new(pattern).is_absolute() {
184                pattern.clone()
185            } else {
186                base_dir.join(pattern).to_string_lossy().to_string()
187            };
188
189            let entries = glob(&full_pattern).map_err(|e| ConfigError::GlobPattern {
190                pattern: full_pattern.clone(),
191                error: e,
192            })?;
193
194            for entry in entries {
195                let path = entry?;
196                if path.is_file() {
197                    paths.push(path);
198                }
199            }
200        }
201
202        paths.sort();
203        paths.dedup();
204        Ok(paths)
205    }
206}