Skip to main content

roas_codegen/
config.rs

1//! What a configuration file may say, and what generation consumes.
2//!
3//! Two types, because "what the file may omit" and "what generation
4//! needs" are different sets. [`ConfigFile`] is the serde type:
5//! everything optional, unknown keys rejected, relative paths resolved
6//! against the file's own directory. [`Config`] is fully resolved, with
7//! no `Option` where the generator needs an answer, and
8//! [`ConfigFile::build`] is the one place a missing `target` is refused.
9
10use serde::Deserialize;
11use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13use thiserror::Error;
14
15/// The language to generate.
16#[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/// How generated types are spread over files.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Default)]
26#[serde(rename_all = "snake_case")]
27#[non_exhaustive]
28pub enum Layout {
29    /// One file per module or package. The default, and the only layout
30    /// under which a "footer after all generated code" means what it
31    /// says.
32    #[default]
33    OneFilePerModule,
34    /// One file per generated type: in Rust, a file per type below the
35    /// module file, which keeps the helpers and includes them; in Go, a
36    /// file per type beside the package file.
37    FilePerType,
38}
39
40/// How a substituted type is spelled in one language.
41#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
42#[serde(default, deny_unknown_fields)]
43#[non_exhaustive]
44pub struct TypeSpelling {
45    /// The type as it appears in generated code, such as
46    /// `chrono::DateTime<chrono::Utc>` or `time.Time`.
47    pub name: String,
48    /// The import that makes it available: a crate for Rust, an import
49    /// path for Go.
50    pub import: Option<String>,
51}
52
53/// A user-provided type standing in for a schema or a `format`.
54#[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/// Per-field settings, addressed by the property name as written in
63/// the description.
64#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
65#[serde(default, deny_unknown_fields)]
66#[non_exhaustive]
67pub struct FieldConfig {
68    /// Extra Rust attributes, appended as separate lines.
69    pub attrs: Vec<String>,
70    /// Extra Go struct-tag keys, merged into the one tag.
71    pub go_tags: BTreeMap<String, String>,
72    /// The generated name, when the derived one is not wanted.
73    pub rename: Option<String>,
74}
75
76/// Per-type settings, addressed by the component name as written in
77/// the description.
78#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
79#[serde(default, deny_unknown_fields)]
80#[non_exhaustive]
81pub struct TypeConfig {
82    /// Extra Rust container attributes.
83    pub attrs: Vec<String>,
84    /// The generated name, when the derived one is not wanted.
85    pub rename: Option<String>,
86    /// Opt this type out of generated validation, once validation is on.
87    pub validation: Option<bool>,
88    pub fields: BTreeMap<String, FieldConfig>,
89}
90
91/// Rust settings as a file may state them.
92#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
93#[serde(default, deny_unknown_fields)]
94#[non_exhaustive]
95pub struct RustConfigFile {
96    /// The generated module's name: the file is `<module>.rs`. Default
97    /// `types`. Targets sharing an output directory need different ones.
98    pub module: Option<String>,
99    pub edition: Option<String>,
100    /// Derives added to every generated container.
101    pub derives: Vec<String>,
102}
103
104/// Go settings as a file may state them.
105#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
106#[serde(default, deny_unknown_fields)]
107#[non_exhaustive]
108pub struct GoConfigFile {
109    /// The package clause of the generated file. Default `api`.
110    pub package: Option<String>,
111    /// The generated file's stem: the file is `<file>.go`. Default
112    /// `types`. Targets sharing an output directory need different ones.
113    pub file: Option<String>,
114}
115
116/// What a configuration file may say. Everything optional; nothing
117/// validated beyond the shape.
118#[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    /// A directory of templates overriding the built-in ones. Relative
130    /// paths resolve against the configuration file's directory.
131    pub template_dir: Option<PathBuf>,
132    pub rust: RustConfigFile,
133    pub go: GoConfigFile,
134    /// Keyed by `format` name or by component name.
135    pub substitutions: BTreeMap<String, Substitution>,
136    pub types: BTreeMap<String, TypeConfig>,
137}
138
139impl ConfigFile {
140    /// Read and parse a file. Relative paths inside it resolve against
141    /// the file's own directory, never the working directory, so a
142    /// checked-in configuration means the same thing from every shell.
143    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    /// Parse TOML text. `base` is what relative paths resolve against;
159    /// it is taken explicitly because text has no location of its own.
160    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    /// Layer `over` on top of `self`: a value `over` sets wins, a value
174    /// it leaves unset keeps `self`'s. Lists and maps combine, later
175    /// entries winning on the same key. This is how a command line
176    /// applies to a file: parse the file, build a `ConfigFile` from the
177    /// flags, merge.
178    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    /// Resolve into what generation consumes. This is where "required"
200    /// is enforced: a missing `target` is an error here and nowhere else.
201    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
251/// A module named like a crate the user's code or the generated code
252/// names (`std`, `core`, `serde`, ...) hides that crate for every path in
253/// the file that declares it; one named `lib` or `main` would be a crate
254/// root's file. Crates a substitution imports are checked in `generate`,
255/// where the configuration is known.
256fn 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
263/// A lowercase Rust module name: a letter, then letters, digits or `_`,
264/// and not a keyword, a crate's name or a Windows-reserved name. The file
265/// name the Rust backend writes.
266pub(crate) fn is_module_name(module: &str) -> bool {
267    // The module names the file: one Windows resolves elsewhere is refused.
268    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
277/// A Rust module name derived from free text such as a label or a file
278/// name: lowercase, other characters to `_`, never empty, never digit-led,
279/// never a keyword. Accepted as `rust.module` unless a substitution
280/// imports or names a crate of that name, which `generate` refuses.
281pub 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/// Rust settings, resolved.
312#[derive(Debug, Clone, PartialEq, Eq)]
313#[non_exhaustive]
314pub struct RustConfig {
315    /// The generated module's name; the file is `<module>.rs`.
316    pub module: String,
317    pub edition: String,
318    pub derives: Vec<String>,
319}
320
321/// Go settings, resolved.
322#[derive(Debug, Clone, PartialEq, Eq)]
323#[non_exhaustive]
324pub struct GoConfig {
325    /// The package clause of the generated file.
326    pub package: String,
327    /// The generated file's stem; the file is `<file>.go`.
328    pub file: String,
329}
330
331/// What generation consumes. Fully resolved: no `Option` where the
332/// generator needs an answer, no `Deserialize`, no `Default` — obtained
333/// only through [`ConfigFile::build`].
334#[derive(Debug, Clone, PartialEq, Eq)]
335#[non_exhaustive]
336pub struct Config {
337    pub target: Target,
338    pub layout: Layout,
339    pub validation: bool,
340    /// Cargo-gated: honoured only when this crate was built with the
341    /// `exact-numbers` feature and the source has exact fidelity.
342    pub exact_numbers: bool,
343    pub header: Option<String>,
344    pub extra_imports: Vec<String>,
345    pub allow_codegen_extensions: bool,
346    /// Absolute by now.
347    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/// Why a configuration could not be loaded or resolved.
355#[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}