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#[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#[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#[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}
100
101#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(deny_unknown_fields)]
103pub struct CodegenTargetConfig {
104 pub enabled: Option<bool>,
105 pub output: Option<String>,
106 pub backend: Option<String>,
107 #[serde(default)]
108 pub features: Vec<String>,
109 pub package: Option<String>,
110 pub namespace: Option<String>,
111 pub strict_facets: Option<bool>,
112 pub slots: Option<bool>,
113 pub kw_only: Option<bool>,
114 pub zero_copy: Option<bool>,
115 pub codecs: Option<bool>,
116 pub standard: Option<String>,
117 pub derive_traits: Option<Vec<String>>,
118 pub box_cycles: Option<bool>,
119 pub modules: Option<bool>,
120 pub mode: Option<String>,
121 pub serializer: Option<String>,
122 pub style: Option<String>,
123 pub custom_header: Option<String>,
124}
125
126impl std::str::FromStr for WorkspaceManifest {
127 type Err = ConfigError;
128
129 fn from_str(toml_str: &str) -> Result<Self, Self::Err> {
130 let manifest: WorkspaceManifest = toml::from_str(toml_str)?;
131 Ok(manifest)
132 }
133}
134
135impl WorkspaceManifest {
136 pub fn from_file(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
137 let content = fs::read_to_string(path)?;
138 content.parse()
139 }
140
141 pub fn resolved_targets(&self) -> Vec<TargetConfig> {
144 let mut targets = Vec::new();
145
146 let ws_header = self
147 .workspace
148 .as_ref()
149 .and_then(|w| w.custom_header.clone());
150
151 for gen in &self.generate {
153 if gen.enabled.unwrap_or(true) {
154 let mut target = gen.clone();
155 if target.custom_header.is_none() {
156 target.custom_header = ws_header.clone();
157 }
158 targets.push(target);
159 }
160 }
161
162 if let Some(ref codegen_map) = self.codegen {
164 for (lang, cfg) in codegen_map {
165 if cfg.enabled.unwrap_or(true) {
166 let output = cfg
167 .output
168 .clone()
169 .unwrap_or_else(|| format!("generated/{}", lang));
170
171 targets.push(TargetConfig {
172 target: lang.clone(),
173 output,
174 enabled: cfg.enabled,
175 backend: cfg.backend.clone(),
176 features: cfg.features.clone(),
177 package: cfg.package.clone(),
178 namespace: cfg.namespace.clone(),
179 strict_facets: cfg.strict_facets,
180 slots: cfg.slots,
181 kw_only: cfg.kw_only,
182 zero_copy: cfg.zero_copy,
183 codecs: cfg.codecs,
184 standard: cfg.standard.clone(),
185 derive_traits: cfg.derive_traits.clone(),
186 box_cycles: cfg.box_cycles,
187 modules: cfg.modules,
188 mode: cfg.mode.clone(),
189 serializer: cfg.serializer.clone(),
190 style: cfg.style.clone(),
191 custom_header: cfg.custom_header.clone().or_else(|| ws_header.clone()),
192 });
193 }
194 }
195 }
196
197 targets
198 }
199
200 pub fn expand_schemas(&self, base_dir: &Path) -> Result<Vec<PathBuf>, ConfigError> {
202 let Some(ref ws) = self.workspace else {
203 return Ok(Vec::new());
204 };
205
206 expand_patterns(&ws.schemas, base_dir)
207 }
208
209 pub fn expand_module_schemas(
210 &self,
211 name: &str,
212 base_dir: &Path,
213 ) -> Result<Vec<PathBuf>, ConfigError> {
214 let Some(module) = self.modules.get(name) else {
215 return Ok(Vec::new());
216 };
217 expand_patterns(&module.schemas, base_dir)
218 }
219
220 pub fn module_order(&self) -> Result<Vec<String>, ConfigError> {
221 for name in self.modules.keys() {
222 let mut chars = name.chars();
223 if !chars
224 .next()
225 .is_some_and(|ch| ch.is_ascii_alphabetic() || ch == '_')
226 || !chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
227 {
228 return Err(ConfigError::InvalidModuleName(name.clone()));
229 }
230 }
231 let mut order = Vec::new();
232 let mut visiting = HashSet::new();
233 let mut visited = HashSet::new();
234 fn visit(
235 name: &str,
236 manifest: &WorkspaceManifest,
237 visiting: &mut HashSet<String>,
238 visited: &mut HashSet<String>,
239 order: &mut Vec<String>,
240 ) -> Result<(), ConfigError> {
241 if visited.contains(name) {
242 return Ok(());
243 }
244 if !visiting.insert(name.to_string()) {
245 return Err(ConfigError::ModuleCycle(name.to_string()));
246 }
247 let module = &manifest.modules[name];
248 for dependency in &module.depends_on {
249 if !manifest.modules.contains_key(dependency) {
250 return Err(ConfigError::UnknownModuleDependency {
251 module: name.to_string(),
252 dependency: dependency.clone(),
253 });
254 }
255 visit(dependency, manifest, visiting, visited, order)?;
256 }
257 visiting.remove(name);
258 visited.insert(name.to_string());
259 order.push(name.to_string());
260 Ok(())
261 }
262 for name in self.modules.keys() {
263 visit(name, self, &mut visiting, &mut visited, &mut order)?;
264 }
265 Ok(order)
266 }
267}
268
269fn expand_patterns(patterns: &[String], base_dir: &Path) -> Result<Vec<PathBuf>, ConfigError> {
270 let mut paths = Vec::new();
271 for pattern in patterns {
272 let full_pattern = if Path::new(pattern).is_absolute() {
273 pattern.clone()
274 } else {
275 base_dir.join(pattern).to_string_lossy().to_string()
276 };
277
278 let entries = glob(&full_pattern).map_err(|e| ConfigError::GlobPattern {
279 pattern: full_pattern.clone(),
280 error: e,
281 })?;
282
283 for entry in entries {
284 let path = entry?;
285 if path.is_file() {
286 paths.push(path);
287 }
288 }
289 }
290
291 paths.sort();
292 paths.dedup();
293 Ok(paths)
294}