1use serde::Deserialize;
11use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13use thiserror::Error;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
17#[serde(rename_all = "lowercase")]
18#[non_exhaustive]
19pub enum Target {
20 Rust,
21 Go,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Default)]
26#[serde(rename_all = "snake_case")]
27#[non_exhaustive]
28pub enum Layout {
29 #[default]
33 OneFilePerModule,
34 FilePerType,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
42#[serde(default, deny_unknown_fields)]
43#[non_exhaustive]
44pub struct TypeSpelling {
45 pub name: String,
48 pub import: Option<String>,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
55#[serde(default, deny_unknown_fields)]
56#[non_exhaustive]
57pub struct Substitution {
58 pub rust: Option<TypeSpelling>,
59 pub go: Option<TypeSpelling>,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
65#[serde(default, deny_unknown_fields)]
66#[non_exhaustive]
67pub struct FieldConfig {
68 pub attrs: Vec<String>,
70 pub go_tags: BTreeMap<String, String>,
72 pub rename: Option<String>,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
79#[serde(default, deny_unknown_fields)]
80#[non_exhaustive]
81pub struct TypeConfig {
82 pub attrs: Vec<String>,
84 pub rename: Option<String>,
86 pub validation: Option<bool>,
88 pub fields: BTreeMap<String, FieldConfig>,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
93#[serde(default, deny_unknown_fields)]
94#[non_exhaustive]
95pub struct RustConfigFile {
96 pub module: Option<String>,
99 pub edition: Option<String>,
100 pub derives: Vec<String>,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
106#[serde(default, deny_unknown_fields)]
107#[non_exhaustive]
108pub struct GoConfigFile {
109 pub package: Option<String>,
111 pub file: Option<String>,
114}
115
116#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
119#[serde(default, deny_unknown_fields, rename_all = "snake_case")]
120#[non_exhaustive]
121pub struct ConfigFile {
122 pub target: Option<Target>,
123 pub layout: Option<Layout>,
124 pub validation: Option<bool>,
125 pub exact_numbers: Option<bool>,
126 pub header: Option<String>,
127 pub extra_imports: Vec<String>,
128 pub allow_codegen_extensions: Option<bool>,
129 pub template_dir: Option<PathBuf>,
132 pub rust: RustConfigFile,
133 pub go: GoConfigFile,
134 pub substitutions: BTreeMap<String, Substitution>,
136 pub types: BTreeMap<String, TypeConfig>,
137}
138
139impl ConfigFile {
140 pub fn from_path(path: &Path) -> Result<ConfigFile, ConfigError> {
144 let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
145 path: path.to_path_buf(),
146 source,
147 })?;
148 let base = path.parent().unwrap_or_else(|| Path::new("."));
149 ConfigFile::from_toml(&text, base).map_err(|error| match error {
150 ConfigError::Parse { source, .. } => ConfigError::Parse {
151 path: Some(path.to_path_buf()),
152 source,
153 },
154 other => other,
155 })
156 }
157
158 pub fn from_toml(text: &str, base: &Path) -> Result<ConfigFile, ConfigError> {
161 let mut file: ConfigFile =
162 toml::from_str(text).map_err(|source| ConfigError::Parse { path: None, source })?;
163 if let Some(dir) = file.template_dir.take() {
164 file.template_dir = Some(if dir.is_absolute() {
165 dir
166 } else {
167 base.join(dir)
168 });
169 }
170 Ok(file)
171 }
172
173 pub fn merge(mut self, over: ConfigFile) -> ConfigFile {
179 self.target = over.target.or(self.target);
180 self.layout = over.layout.or(self.layout);
181 self.validation = over.validation.or(self.validation);
182 self.exact_numbers = over.exact_numbers.or(self.exact_numbers);
183 self.header = over.header.or(self.header);
184 self.extra_imports.extend(over.extra_imports);
185 self.allow_codegen_extensions = over
186 .allow_codegen_extensions
187 .or(self.allow_codegen_extensions);
188 self.template_dir = over.template_dir.or(self.template_dir);
189 self.rust.module = over.rust.module.or(self.rust.module);
190 self.rust.edition = over.rust.edition.or(self.rust.edition);
191 self.rust.derives.extend(over.rust.derives);
192 self.go.package = over.go.package.or(self.go.package);
193 self.go.file = over.go.file.or(self.go.file);
194 self.substitutions.extend(over.substitutions);
195 self.types.extend(over.types);
196 self
197 }
198
199 pub fn build(self) -> Result<Config, ConfigError> {
202 let target = self.target.ok_or(ConfigError::MissingTarget)?;
203 Ok(Config {
204 target,
205 layout: self.layout.unwrap_or_default(),
206 validation: self.validation.unwrap_or(false),
207 exact_numbers: self.exact_numbers.unwrap_or(false),
208 header: self.header,
209 extra_imports: self.extra_imports,
210 allow_codegen_extensions: self.allow_codegen_extensions.unwrap_or(false),
211 template_dir: self.template_dir,
212 rust: RustConfig {
213 module: match self.rust.module {
214 Some(module) => {
215 if !is_module_name(&module) {
216 return Err(ConfigError::InvalidModule(module));
217 }
218 module
219 }
220 None => "types".to_owned(),
221 },
222 edition: self.rust.edition.unwrap_or_else(|| "2024".to_owned()),
223 derives: self.rust.derives,
224 },
225 go: GoConfig {
226 package: match self.go.package {
227 Some(package) => {
228 if !crate::go::naming::is_package_name(&package) {
229 return Err(ConfigError::InvalidPackage(package));
230 }
231 package
232 }
233 None => "api".to_owned(),
234 },
235 file: match self.go.file {
236 Some(file) => {
237 if !crate::go::naming::is_file_stem(&file) {
238 return Err(ConfigError::InvalidGoFile(file));
239 }
240 file
241 }
242 None => "types".to_owned(),
243 },
244 },
245 substitutions: self.substitutions,
246 types: self.types,
247 })
248 }
249}
250
251fn shadows_a_crate(module: &str) -> bool {
257 matches!(
258 module,
259 "std" | "core" | "alloc" | "proc_macro" | "test" | "serde" | "serde_json" | "lib" | "main"
260 )
261}
262
263pub(crate) fn is_module_name(module: &str) -> bool {
267 crate::write::windows_safe(module)
269 && !shadows_a_crate(module)
270 && !crate::rust::naming::is_keyword(module)
271 && module.starts_with(|c: char| c.is_ascii_lowercase())
272 && module
273 .bytes()
274 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
275}
276
277pub fn rust_module_name(text: &str) -> String {
282 let mut module: String = text
283 .chars()
284 .map(|c| {
285 if c.is_ascii_alphanumeric() {
286 c.to_ascii_lowercase()
287 } else {
288 '_'
289 }
290 })
291 .collect();
292 while module.contains("__") {
293 module = module.replace("__", "_");
294 }
295 let module = module.trim_matches('_').to_owned();
296 let module = match module.chars().next() {
297 None => "api".to_owned(),
298 Some(c) if c.is_ascii_digit() => format!("m_{module}"),
299 Some(_) => module,
300 };
301 if crate::rust::naming::is_keyword(&module)
302 || !crate::write::windows_safe(&module)
303 || shadows_a_crate(&module)
304 {
305 format!("{module}_types")
306 } else {
307 module
308 }
309}
310
311#[derive(Debug, Clone, PartialEq, Eq)]
313#[non_exhaustive]
314pub struct RustConfig {
315 pub module: String,
317 pub edition: String,
318 pub derives: Vec<String>,
319}
320
321#[derive(Debug, Clone, PartialEq, Eq)]
323#[non_exhaustive]
324pub struct GoConfig {
325 pub package: String,
327 pub file: String,
329}
330
331#[derive(Debug, Clone, PartialEq, Eq)]
335#[non_exhaustive]
336pub struct Config {
337 pub target: Target,
338 pub layout: Layout,
339 pub validation: bool,
340 pub exact_numbers: bool,
343 pub header: Option<String>,
344 pub extra_imports: Vec<String>,
345 pub allow_codegen_extensions: bool,
346 pub template_dir: Option<PathBuf>,
348 pub rust: RustConfig,
349 pub go: GoConfig,
350 pub substitutions: BTreeMap<String, Substitution>,
351 pub types: BTreeMap<String, TypeConfig>,
352}
353
354#[derive(Debug, Error)]
356#[non_exhaustive]
357pub enum ConfigError {
358 #[error("cannot read configuration file {path}")]
359 Read {
360 path: PathBuf,
361 #[source]
362 source: std::io::Error,
363 },
364 #[error("configuration{} is not valid: {source}", match path { Some(p) => format!(" file {}", p.display()), None => String::new() })]
365 Parse {
366 path: Option<PathBuf>,
367 #[source]
368 source: toml::de::Error,
369 },
370 #[error("no target language: set `target`")]
371 MissingTarget,
372 #[error(
373 "`rust.module = {0:?}` must be a lowercase Rust module name: a letter, then letters, digits or `_`; not a keyword, a crate name such as `std` or `serde`, `lib` or `main`, or a name Windows reserves"
374 )]
375 InvalidModule(String),
376 #[error(
377 "`go.package = {0:?}` must be a lowercase Go package name: a letter, then letters, digits or `_`; not a keyword, nor `main`, `init` or `documentation`, which no other package can import"
378 )]
379 InvalidPackage(String),
380 #[error(
381 "`go.file = {0:?}` must be a lowercase file stem `go build` reads as plain source: a letter, then letters, digits or `_`; no `_test`, `_<os>` or `_<arch>` suffix, and not a name Windows reserves"
382 )]
383 InvalidGoFile(String),
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 #[test]
391 fn a_two_line_file_parses_and_builds_with_a_target() {
392 let file = ConfigFile::from_toml(
393 "[types.Pet.fields.tag]\nattrs = ['#[validate(length(min = 1))]']\n",
394 Path::new("/cfg"),
395 )
396 .unwrap();
397 assert_eq!(
398 file.types["Pet"].fields["tag"].attrs,
399 vec!["#[validate(length(min = 1))]".to_owned()]
400 );
401 assert!(matches!(
402 file.clone().build(),
403 Err(ConfigError::MissingTarget)
404 ));
405 let config = file
406 .merge(ConfigFile {
407 target: Some(Target::Rust),
408 ..Default::default()
409 })
410 .build()
411 .unwrap();
412 assert_eq!(config.target, Target::Rust);
413 assert_eq!(config.layout, Layout::OneFilePerModule);
414 assert!(!config.validation);
415 assert_eq!(config.rust.edition, "2024");
416 assert_eq!(config.go.package, "api");
417 }
418
419 #[test]
420 fn unknown_keys_are_rejected_at_every_level() {
421 for text in [
422 "validaton = true\n",
423 "[rust]\ncrate = \"x\"\n",
424 "[types.Pet]\nattr = []\n",
425 "[types.Pet.fields.tag]\nattr = []\n",
426 "[substitutions.uuid.rust]\ntype = \"x\"\n",
427 ] {
428 let error = ConfigFile::from_toml(text, Path::new("/cfg")).unwrap_err();
429 assert!(
430 matches!(error, ConfigError::Parse { .. }),
431 "{text:?} -> {error}"
432 );
433 }
434 }
435
436 #[test]
437 fn relative_template_dir_resolves_against_the_base() {
438 let file = ConfigFile::from_toml("template_dir = \"templates\"\n", Path::new("/proj/cfg"))
439 .unwrap();
440 assert_eq!(
441 file.template_dir.as_deref(),
442 Some(Path::new("/proj/cfg/templates"))
443 );
444 let file =
445 ConfigFile::from_toml("template_dir = \"/abs\"\n", Path::new("/proj/cfg")).unwrap();
446 assert_eq!(file.template_dir.as_deref(), Some(Path::new("/abs")));
447 }
448
449 #[test]
450 fn from_path_resolves_against_the_files_directory_and_names_it_on_error() {
451 let dir = std::env::temp_dir().join(format!("roas-codegen-config-{}", std::process::id()));
452 std::fs::create_dir_all(&dir).unwrap();
453 let path = dir.join("codegen.toml");
454 std::fs::write(&path, "target = \"go\"\ntemplate_dir = \"tpl\"\n").unwrap();
455 let file = ConfigFile::from_path(&path).unwrap();
456 assert_eq!(
457 file.template_dir.as_deref(),
458 Some(dir.join("tpl").as_path())
459 );
460 std::fs::write(&path, "target = 1\n").unwrap();
461 let error = ConfigFile::from_path(&path).unwrap_err();
462 assert!(error.to_string().contains("codegen.toml"), "{error}");
463 let missing = ConfigFile::from_path(&dir.join("absent.toml")).unwrap_err();
464 assert!(matches!(missing, ConfigError::Read { .. }));
465 std::fs::remove_dir_all(&dir).unwrap();
466 }
467
468 #[test]
469 fn merge_lets_later_values_win_and_combines_collections() {
470 let base = ConfigFile::from_toml(
471 "target = \"rust\"\nvalidation = true\nextra_imports = [\"a\"]\n[rust]\nderives = [\"Eq\"]\n[types.Pet]\nrename = \"Animal\"\n",
472 Path::new("/"),
473 )
474 .unwrap();
475 let over = ConfigFile::from_toml(
476 "target = \"go\"\nextra_imports = [\"b\"]\n[types.Owner]\nrename = \"Person\"\n",
477 Path::new("/"),
478 )
479 .unwrap();
480 let merged = base.merge(over);
481 assert_eq!(merged.target, Some(Target::Go));
482 assert_eq!(merged.validation, Some(true));
483 assert_eq!(merged.extra_imports, vec!["a".to_owned(), "b".to_owned()]);
484 assert_eq!(merged.rust.derives, vec!["Eq".to_owned()]);
485 assert_eq!(merged.types.len(), 2);
486 }
487
488 #[test]
489 fn substitutions_and_layout_parse() {
490 let file = ConfigFile::from_toml(
491 "target = \"rust\"\nlayout = \"file_per_type\"\n[substitutions.uuid]\nrust = { name = \"uuid::Uuid\", import = \"uuid\" }\ngo = { name = \"uuid.UUID\" }\n",
492 Path::new("/"),
493 )
494 .unwrap();
495 let config = file.build().unwrap();
496 assert_eq!(config.layout, Layout::FilePerType);
497 let uuid = &config.substitutions["uuid"];
498 assert_eq!(uuid.rust.as_ref().unwrap().import.as_deref(), Some("uuid"));
499 assert_eq!(uuid.go.as_ref().unwrap().name, "uuid.UUID");
500 assert!(uuid.go.as_ref().unwrap().import.is_none());
501 }
502
503 #[test]
504 fn module_names_windows_resolves_elsewhere_are_avoided() {
505 assert_eq!(rust_module_name("aux"), "aux_types");
506 assert_eq!(rust_module_name("COM1"), "com1_types");
507 assert!(is_module_name(&rust_module_name("nul")));
508 assert!(!is_module_name("con"));
509 }
510
511 #[test]
512 fn module_names_never_shadow_a_crate() {
513 assert_eq!(rust_module_name("std"), "std_types");
514 assert_eq!(rust_module_name("serde"), "serde_types");
515 assert_eq!(rust_module_name("lib"), "lib_types");
516 assert!(!is_module_name("main"));
517 assert!(!is_module_name("core"));
518 }
519}