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"
260            | "core"
261            | "alloc"
262            | "proc_macro"
263            | "test"
264            | "serde"
265            | "serde_json"
266            | "regex"
267            | "lib"
268            | "main"
269    )
270}
271
272/// A lowercase Rust module name: a letter, then letters, digits or `_`,
273/// and not a keyword, a crate's name or a Windows-reserved name. The file
274/// name the Rust backend writes.
275pub(crate) fn is_module_name(module: &str) -> bool {
276    // The module names the file: one Windows resolves elsewhere is refused.
277    crate::write::windows_safe(module)
278        && !shadows_a_crate(module)
279        && !crate::rust::naming::is_keyword(module)
280        && module.starts_with(|c: char| c.is_ascii_lowercase())
281        && module
282            .bytes()
283            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
284}
285
286/// A Rust module name derived from free text such as a label or a file
287/// name: lowercase, other characters to `_`, never empty, never digit-led,
288/// never a keyword. Accepted as `rust.module` unless a substitution
289/// imports or names a crate of that name, which `generate` refuses.
290pub fn rust_module_name(text: &str) -> String {
291    let mut module: String = text
292        .chars()
293        .map(|c| {
294            if c.is_ascii_alphanumeric() {
295                c.to_ascii_lowercase()
296            } else {
297                '_'
298            }
299        })
300        .collect();
301    while module.contains("__") {
302        module = module.replace("__", "_");
303    }
304    let module = module.trim_matches('_').to_owned();
305    let module = match module.chars().next() {
306        None => "api".to_owned(),
307        Some(c) if c.is_ascii_digit() => format!("m_{module}"),
308        Some(_) => module,
309    };
310    if crate::rust::naming::is_keyword(&module)
311        || !crate::write::windows_safe(&module)
312        || shadows_a_crate(&module)
313    {
314        format!("{module}_types")
315    } else {
316        module
317    }
318}
319
320/// Rust settings, resolved.
321#[derive(Debug, Clone, PartialEq, Eq)]
322#[non_exhaustive]
323pub struct RustConfig {
324    /// The generated module's name; the file is `<module>.rs`.
325    pub module: String,
326    pub edition: String,
327    pub derives: Vec<String>,
328}
329
330/// Go settings, resolved.
331#[derive(Debug, Clone, PartialEq, Eq)]
332#[non_exhaustive]
333pub struct GoConfig {
334    /// The package clause of the generated file.
335    pub package: String,
336    /// The generated file's stem; the file is `<file>.go`.
337    pub file: String,
338}
339
340/// What generation consumes. Fully resolved: no `Option` where the
341/// generator needs an answer, no `Deserialize`, no `Default` — obtained
342/// only through [`ConfigFile::build`].
343#[derive(Debug, Clone, PartialEq, Eq)]
344#[non_exhaustive]
345pub struct Config {
346    pub target: Target,
347    pub layout: Layout,
348    pub validation: bool,
349    /// Cargo-gated: honoured only when this crate was built with the
350    /// `exact-numbers` feature and the source has exact fidelity.
351    pub exact_numbers: bool,
352    pub header: Option<String>,
353    pub extra_imports: Vec<String>,
354    pub allow_codegen_extensions: bool,
355    /// Directory of templates overriding the built-in ones. Resolved against
356    /// the config file's directory when loaded via [`ConfigFile::from_toml`]
357    /// or [`ConfigFile::from_path`].
358    pub template_dir: Option<PathBuf>,
359    pub rust: RustConfig,
360    pub go: GoConfig,
361    pub substitutions: BTreeMap<String, Substitution>,
362    pub types: BTreeMap<String, TypeConfig>,
363}
364
365/// Why a configuration could not be loaded or resolved.
366#[derive(Debug, Error)]
367#[non_exhaustive]
368pub enum ConfigError {
369    #[error("cannot read configuration file {path}")]
370    Read {
371        path: PathBuf,
372        #[source]
373        source: std::io::Error,
374    },
375    #[error("configuration{} is not valid: {source}", match path { Some(p) => format!(" file {}", p.display()), None => String::new() })]
376    Parse {
377        path: Option<PathBuf>,
378        #[source]
379        source: toml::de::Error,
380    },
381    #[error("no target language: set `target`")]
382    MissingTarget,
383    #[error(
384        "`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"
385    )]
386    InvalidModule(String),
387    #[error(
388        "`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"
389    )]
390    InvalidPackage(String),
391    #[error(
392        "`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"
393    )]
394    InvalidGoFile(String),
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    #[test]
402    fn a_two_line_file_parses_and_builds_with_a_target() {
403        let file = ConfigFile::from_toml(
404            "[types.Pet.fields.tag]\nattrs = ['#[validate(length(min = 1))]']\n",
405            Path::new("/cfg"),
406        )
407        .unwrap();
408        assert_eq!(
409            file.types["Pet"].fields["tag"].attrs,
410            vec!["#[validate(length(min = 1))]".to_owned()]
411        );
412        assert!(matches!(
413            file.clone().build(),
414            Err(ConfigError::MissingTarget)
415        ));
416        let config = file
417            .merge(ConfigFile {
418                target: Some(Target::Rust),
419                ..Default::default()
420            })
421            .build()
422            .unwrap();
423        assert_eq!(config.target, Target::Rust);
424        assert_eq!(config.layout, Layout::OneFilePerModule);
425        assert!(!config.validation);
426        assert_eq!(config.rust.edition, "2024");
427        assert_eq!(config.go.package, "api");
428    }
429
430    #[test]
431    fn unknown_keys_are_rejected_at_every_level() {
432        for text in [
433            "validaton = true\n",
434            "[rust]\ncrate = \"x\"\n",
435            "[types.Pet]\nattr = []\n",
436            "[types.Pet.fields.tag]\nattr = []\n",
437            "[substitutions.uuid.rust]\ntype = \"x\"\n",
438        ] {
439            let error = ConfigFile::from_toml(text, Path::new("/cfg")).unwrap_err();
440            assert!(
441                matches!(error, ConfigError::Parse { .. }),
442                "{text:?} -> {error}"
443            );
444        }
445    }
446
447    #[test]
448    fn relative_template_dir_resolves_against_the_base() {
449        let file = ConfigFile::from_toml("template_dir = \"templates\"\n", Path::new("/proj/cfg"))
450            .unwrap();
451        assert_eq!(
452            file.template_dir.as_deref(),
453            Some(Path::new("/proj/cfg/templates"))
454        );
455        let file =
456            ConfigFile::from_toml("template_dir = \"/abs\"\n", Path::new("/proj/cfg")).unwrap();
457        assert_eq!(file.template_dir.as_deref(), Some(Path::new("/abs")));
458    }
459
460    #[test]
461    fn from_path_resolves_against_the_files_directory_and_names_it_on_error() {
462        let dir = std::env::temp_dir().join(format!("roas-codegen-config-{}", std::process::id()));
463        std::fs::create_dir_all(&dir).unwrap();
464        let path = dir.join("codegen.toml");
465        std::fs::write(&path, "target = \"go\"\ntemplate_dir = \"tpl\"\n").unwrap();
466        let file = ConfigFile::from_path(&path).unwrap();
467        assert_eq!(
468            file.template_dir.as_deref(),
469            Some(dir.join("tpl").as_path())
470        );
471        std::fs::write(&path, "target = 1\n").unwrap();
472        let error = ConfigFile::from_path(&path).unwrap_err();
473        assert!(error.to_string().contains("codegen.toml"), "{error}");
474        let missing = ConfigFile::from_path(&dir.join("absent.toml")).unwrap_err();
475        assert!(matches!(missing, ConfigError::Read { .. }));
476        std::fs::remove_dir_all(&dir).unwrap();
477    }
478
479    #[test]
480    fn merge_lets_later_values_win_and_combines_collections() {
481        let base = ConfigFile::from_toml(
482            "target = \"rust\"\nvalidation = true\nextra_imports = [\"a\"]\n[rust]\nderives = [\"Eq\"]\n[types.Pet]\nrename = \"Animal\"\n",
483            Path::new("/"),
484        )
485        .unwrap();
486        let over = ConfigFile::from_toml(
487            "target = \"go\"\nextra_imports = [\"b\"]\n[types.Owner]\nrename = \"Person\"\n",
488            Path::new("/"),
489        )
490        .unwrap();
491        let merged = base.merge(over);
492        assert_eq!(merged.target, Some(Target::Go));
493        assert_eq!(merged.validation, Some(true));
494        assert_eq!(merged.extra_imports, vec!["a".to_owned(), "b".to_owned()]);
495        assert_eq!(merged.rust.derives, vec!["Eq".to_owned()]);
496        assert_eq!(merged.types.len(), 2);
497    }
498
499    #[test]
500    fn substitutions_and_layout_parse() {
501        let file = ConfigFile::from_toml(
502            "target = \"rust\"\nlayout = \"file_per_type\"\n[substitutions.uuid]\nrust = { name = \"uuid::Uuid\", import = \"uuid\" }\ngo = { name = \"uuid.UUID\" }\n",
503            Path::new("/"),
504        )
505        .unwrap();
506        let config = file.build().unwrap();
507        assert_eq!(config.layout, Layout::FilePerType);
508        let uuid = &config.substitutions["uuid"];
509        assert_eq!(uuid.rust.as_ref().unwrap().import.as_deref(), Some("uuid"));
510        assert_eq!(uuid.go.as_ref().unwrap().name, "uuid.UUID");
511        assert!(uuid.go.as_ref().unwrap().import.is_none());
512    }
513
514    #[test]
515    fn module_names_windows_resolves_elsewhere_are_avoided() {
516        assert_eq!(rust_module_name("aux"), "aux_types");
517        assert_eq!(rust_module_name("COM1"), "com1_types");
518        assert!(is_module_name(&rust_module_name("nul")));
519        assert!(!is_module_name("con"));
520    }
521
522    #[test]
523    fn module_names_never_shadow_a_crate() {
524        assert_eq!(rust_module_name("std"), "std_types");
525        assert_eq!(rust_module_name("serde"), "serde_types");
526        assert_eq!(rust_module_name("lib"), "lib_types");
527        assert!(!is_module_name("main"));
528        assert!(!is_module_name("core"));
529    }
530}