roas-codegen 0.2.0

Generate Rust and Go types from OpenAPI 2.0 / 3.0 / 3.1 / 3.2 descriptions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! What a configuration file may say, and what generation consumes.
//!
//! Two types, because "what the file may omit" and "what generation
//! needs" are different sets. [`ConfigFile`] is the serde type:
//! everything optional, unknown keys rejected, relative paths resolved
//! against the file's own directory. [`Config`] is fully resolved, with
//! no `Option` where the generator needs an answer, and
//! [`ConfigFile::build`] is the one place a missing `target` is refused.

use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use thiserror::Error;

/// The language to generate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Target {
    Rust,
    Go,
}

/// How generated types are spread over files.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Layout {
    /// One file per module or package. The default, and the only layout
    /// under which a "footer after all generated code" means what it
    /// says.
    #[default]
    OneFilePerModule,
    /// One file per generated type: in Rust, a file per type below the
    /// module file, which keeps the helpers and includes them; in Go, a
    /// file per type beside the package file.
    FilePerType,
}

/// How a substituted type is spelled in one language.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct TypeSpelling {
    /// The type as it appears in generated code, such as
    /// `chrono::DateTime<chrono::Utc>` or `time.Time`.
    pub name: String,
    /// The import that makes it available: a crate for Rust, an import
    /// path for Go.
    pub import: Option<String>,
}

/// A user-provided type standing in for a schema or a `format`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct Substitution {
    pub rust: Option<TypeSpelling>,
    pub go: Option<TypeSpelling>,
}

/// Per-field settings, addressed by the property name as written in
/// the description.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct FieldConfig {
    /// Extra Rust attributes, appended as separate lines.
    pub attrs: Vec<String>,
    /// Extra Go struct-tag keys, merged into the one tag.
    pub go_tags: BTreeMap<String, String>,
    /// The generated name, when the derived one is not wanted.
    pub rename: Option<String>,
}

/// Per-type settings, addressed by the component name as written in
/// the description.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct TypeConfig {
    /// Extra Rust container attributes.
    pub attrs: Vec<String>,
    /// The generated name, when the derived one is not wanted.
    pub rename: Option<String>,
    /// Opt this type out of generated validation, once validation is on.
    pub validation: Option<bool>,
    pub fields: BTreeMap<String, FieldConfig>,
}

/// Rust settings as a file may state them.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct RustConfigFile {
    /// The generated module's name: the file is `<module>.rs`. Default
    /// `types`. Targets sharing an output directory need different ones.
    pub module: Option<String>,
    pub edition: Option<String>,
    /// Derives added to every generated container.
    pub derives: Vec<String>,
}

/// Go settings as a file may state them.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct GoConfigFile {
    /// The package clause of the generated file. Default `api`.
    pub package: Option<String>,
    /// The generated file's stem: the file is `<file>.go`. Default
    /// `types`. Targets sharing an output directory need different ones.
    pub file: Option<String>,
}

/// What a configuration file may say. Everything optional; nothing
/// validated beyond the shape.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default, deny_unknown_fields, rename_all = "snake_case")]
#[non_exhaustive]
pub struct ConfigFile {
    pub target: Option<Target>,
    pub layout: Option<Layout>,
    pub validation: Option<bool>,
    pub exact_numbers: Option<bool>,
    pub header: Option<String>,
    pub extra_imports: Vec<String>,
    pub allow_codegen_extensions: Option<bool>,
    /// A directory of templates overriding the built-in ones. Relative
    /// paths resolve against the configuration file's directory.
    pub template_dir: Option<PathBuf>,
    pub rust: RustConfigFile,
    pub go: GoConfigFile,
    /// Keyed by `format` name or by component name.
    pub substitutions: BTreeMap<String, Substitution>,
    pub types: BTreeMap<String, TypeConfig>,
}

impl ConfigFile {
    /// Read and parse a file. Relative paths inside it resolve against
    /// the file's own directory, never the working directory, so a
    /// checked-in configuration means the same thing from every shell.
    pub fn from_path(path: &Path) -> Result<ConfigFile, ConfigError> {
        let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
            path: path.to_path_buf(),
            source,
        })?;
        let base = path.parent().unwrap_or_else(|| Path::new("."));
        ConfigFile::from_toml(&text, base).map_err(|error| match error {
            ConfigError::Parse { source, .. } => ConfigError::Parse {
                path: Some(path.to_path_buf()),
                source,
            },
            other => other,
        })
    }

    /// Parse TOML text. `base` is what relative paths resolve against;
    /// it is taken explicitly because text has no location of its own.
    pub fn from_toml(text: &str, base: &Path) -> Result<ConfigFile, ConfigError> {
        let mut file: ConfigFile =
            toml::from_str(text).map_err(|source| ConfigError::Parse { path: None, source })?;
        if let Some(dir) = file.template_dir.take() {
            file.template_dir = Some(if dir.is_absolute() {
                dir
            } else {
                base.join(dir)
            });
        }
        Ok(file)
    }

    /// Layer `over` on top of `self`: a value `over` sets wins, a value
    /// it leaves unset keeps `self`'s. Lists and maps combine, later
    /// entries winning on the same key. This is how a command line
    /// applies to a file: parse the file, build a `ConfigFile` from the
    /// flags, merge.
    pub fn merge(mut self, over: ConfigFile) -> ConfigFile {
        self.target = over.target.or(self.target);
        self.layout = over.layout.or(self.layout);
        self.validation = over.validation.or(self.validation);
        self.exact_numbers = over.exact_numbers.or(self.exact_numbers);
        self.header = over.header.or(self.header);
        self.extra_imports.extend(over.extra_imports);
        self.allow_codegen_extensions = over
            .allow_codegen_extensions
            .or(self.allow_codegen_extensions);
        self.template_dir = over.template_dir.or(self.template_dir);
        self.rust.module = over.rust.module.or(self.rust.module);
        self.rust.edition = over.rust.edition.or(self.rust.edition);
        self.rust.derives.extend(over.rust.derives);
        self.go.package = over.go.package.or(self.go.package);
        self.go.file = over.go.file.or(self.go.file);
        self.substitutions.extend(over.substitutions);
        self.types.extend(over.types);
        self
    }

    /// Resolve into what generation consumes. This is where "required"
    /// is enforced: a missing `target` is an error here and nowhere else.
    pub fn build(self) -> Result<Config, ConfigError> {
        let target = self.target.ok_or(ConfigError::MissingTarget)?;
        Ok(Config {
            target,
            layout: self.layout.unwrap_or_default(),
            validation: self.validation.unwrap_or(false),
            exact_numbers: self.exact_numbers.unwrap_or(false),
            header: self.header,
            extra_imports: self.extra_imports,
            allow_codegen_extensions: self.allow_codegen_extensions.unwrap_or(false),
            template_dir: self.template_dir,
            rust: RustConfig {
                module: match self.rust.module {
                    Some(module) => {
                        if !is_module_name(&module) {
                            return Err(ConfigError::InvalidModule(module));
                        }
                        module
                    }
                    None => "types".to_owned(),
                },
                edition: self.rust.edition.unwrap_or_else(|| "2024".to_owned()),
                derives: self.rust.derives,
            },
            go: GoConfig {
                package: match self.go.package {
                    Some(package) => {
                        if !crate::go::naming::is_package_name(&package) {
                            return Err(ConfigError::InvalidPackage(package));
                        }
                        package
                    }
                    None => "api".to_owned(),
                },
                file: match self.go.file {
                    Some(file) => {
                        if !crate::go::naming::is_file_stem(&file) {
                            return Err(ConfigError::InvalidGoFile(file));
                        }
                        file
                    }
                    None => "types".to_owned(),
                },
            },
            substitutions: self.substitutions,
            types: self.types,
        })
    }
}

/// A module named like a crate the user's code or the generated code
/// names (`std`, `core`, `serde`, ...) hides that crate for every path in
/// the file that declares it; one named `lib` or `main` would be a crate
/// root's file. Crates a substitution imports are checked in `generate`,
/// where the configuration is known.
fn shadows_a_crate(module: &str) -> bool {
    matches!(
        module,
        "std"
            | "core"
            | "alloc"
            | "proc_macro"
            | "test"
            | "serde"
            | "serde_json"
            | "regex"
            | "lib"
            | "main"
    )
}

/// A lowercase Rust module name: a letter, then letters, digits or `_`,
/// and not a keyword, a crate's name or a Windows-reserved name. The file
/// name the Rust backend writes.
pub(crate) fn is_module_name(module: &str) -> bool {
    // The module names the file: one Windows resolves elsewhere is refused.
    crate::write::windows_safe(module)
        && !shadows_a_crate(module)
        && !crate::rust::naming::is_keyword(module)
        && module.starts_with(|c: char| c.is_ascii_lowercase())
        && module
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
}

/// A Rust module name derived from free text such as a label or a file
/// name: lowercase, other characters to `_`, never empty, never digit-led,
/// never a keyword. Accepted as `rust.module` unless a substitution
/// imports or names a crate of that name, which `generate` refuses.
pub fn rust_module_name(text: &str) -> String {
    let mut module: String = text
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '_'
            }
        })
        .collect();
    while module.contains("__") {
        module = module.replace("__", "_");
    }
    let module = module.trim_matches('_').to_owned();
    let module = match module.chars().next() {
        None => "api".to_owned(),
        Some(c) if c.is_ascii_digit() => format!("m_{module}"),
        Some(_) => module,
    };
    if crate::rust::naming::is_keyword(&module)
        || !crate::write::windows_safe(&module)
        || shadows_a_crate(&module)
    {
        format!("{module}_types")
    } else {
        module
    }
}

/// Rust settings, resolved.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RustConfig {
    /// The generated module's name; the file is `<module>.rs`.
    pub module: String,
    pub edition: String,
    pub derives: Vec<String>,
}

/// Go settings, resolved.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct GoConfig {
    /// The package clause of the generated file.
    pub package: String,
    /// The generated file's stem; the file is `<file>.go`.
    pub file: String,
}

/// What generation consumes. Fully resolved: no `Option` where the
/// generator needs an answer, no `Deserialize`, no `Default` — obtained
/// only through [`ConfigFile::build`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Config {
    pub target: Target,
    pub layout: Layout,
    pub validation: bool,
    /// Cargo-gated: honoured only when this crate was built with the
    /// `exact-numbers` feature and the source has exact fidelity.
    pub exact_numbers: bool,
    pub header: Option<String>,
    pub extra_imports: Vec<String>,
    pub allow_codegen_extensions: bool,
    /// Directory of templates overriding the built-in ones. Resolved against
    /// the config file's directory when loaded via [`ConfigFile::from_toml`]
    /// or [`ConfigFile::from_path`].
    pub template_dir: Option<PathBuf>,
    pub rust: RustConfig,
    pub go: GoConfig,
    pub substitutions: BTreeMap<String, Substitution>,
    pub types: BTreeMap<String, TypeConfig>,
}

/// Why a configuration could not be loaded or resolved.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ConfigError {
    #[error("cannot read configuration file {path}")]
    Read {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("configuration{} is not valid: {source}", match path { Some(p) => format!(" file {}", p.display()), None => String::new() })]
    Parse {
        path: Option<PathBuf>,
        #[source]
        source: toml::de::Error,
    },
    #[error("no target language: set `target`")]
    MissingTarget,
    #[error(
        "`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"
    )]
    InvalidModule(String),
    #[error(
        "`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"
    )]
    InvalidPackage(String),
    #[error(
        "`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"
    )]
    InvalidGoFile(String),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_two_line_file_parses_and_builds_with_a_target() {
        let file = ConfigFile::from_toml(
            "[types.Pet.fields.tag]\nattrs = ['#[validate(length(min = 1))]']\n",
            Path::new("/cfg"),
        )
        .unwrap();
        assert_eq!(
            file.types["Pet"].fields["tag"].attrs,
            vec!["#[validate(length(min = 1))]".to_owned()]
        );
        assert!(matches!(
            file.clone().build(),
            Err(ConfigError::MissingTarget)
        ));
        let config = file
            .merge(ConfigFile {
                target: Some(Target::Rust),
                ..Default::default()
            })
            .build()
            .unwrap();
        assert_eq!(config.target, Target::Rust);
        assert_eq!(config.layout, Layout::OneFilePerModule);
        assert!(!config.validation);
        assert_eq!(config.rust.edition, "2024");
        assert_eq!(config.go.package, "api");
    }

    #[test]
    fn unknown_keys_are_rejected_at_every_level() {
        for text in [
            "validaton = true\n",
            "[rust]\ncrate = \"x\"\n",
            "[types.Pet]\nattr = []\n",
            "[types.Pet.fields.tag]\nattr = []\n",
            "[substitutions.uuid.rust]\ntype = \"x\"\n",
        ] {
            let error = ConfigFile::from_toml(text, Path::new("/cfg")).unwrap_err();
            assert!(
                matches!(error, ConfigError::Parse { .. }),
                "{text:?} -> {error}"
            );
        }
    }

    #[test]
    fn relative_template_dir_resolves_against_the_base() {
        let file = ConfigFile::from_toml("template_dir = \"templates\"\n", Path::new("/proj/cfg"))
            .unwrap();
        assert_eq!(
            file.template_dir.as_deref(),
            Some(Path::new("/proj/cfg/templates"))
        );
        let file =
            ConfigFile::from_toml("template_dir = \"/abs\"\n", Path::new("/proj/cfg")).unwrap();
        assert_eq!(file.template_dir.as_deref(), Some(Path::new("/abs")));
    }

    #[test]
    fn from_path_resolves_against_the_files_directory_and_names_it_on_error() {
        let dir = std::env::temp_dir().join(format!("roas-codegen-config-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("codegen.toml");
        std::fs::write(&path, "target = \"go\"\ntemplate_dir = \"tpl\"\n").unwrap();
        let file = ConfigFile::from_path(&path).unwrap();
        assert_eq!(
            file.template_dir.as_deref(),
            Some(dir.join("tpl").as_path())
        );
        std::fs::write(&path, "target = 1\n").unwrap();
        let error = ConfigFile::from_path(&path).unwrap_err();
        assert!(error.to_string().contains("codegen.toml"), "{error}");
        let missing = ConfigFile::from_path(&dir.join("absent.toml")).unwrap_err();
        assert!(matches!(missing, ConfigError::Read { .. }));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn merge_lets_later_values_win_and_combines_collections() {
        let base = ConfigFile::from_toml(
            "target = \"rust\"\nvalidation = true\nextra_imports = [\"a\"]\n[rust]\nderives = [\"Eq\"]\n[types.Pet]\nrename = \"Animal\"\n",
            Path::new("/"),
        )
        .unwrap();
        let over = ConfigFile::from_toml(
            "target = \"go\"\nextra_imports = [\"b\"]\n[types.Owner]\nrename = \"Person\"\n",
            Path::new("/"),
        )
        .unwrap();
        let merged = base.merge(over);
        assert_eq!(merged.target, Some(Target::Go));
        assert_eq!(merged.validation, Some(true));
        assert_eq!(merged.extra_imports, vec!["a".to_owned(), "b".to_owned()]);
        assert_eq!(merged.rust.derives, vec!["Eq".to_owned()]);
        assert_eq!(merged.types.len(), 2);
    }

    #[test]
    fn substitutions_and_layout_parse() {
        let file = ConfigFile::from_toml(
            "target = \"rust\"\nlayout = \"file_per_type\"\n[substitutions.uuid]\nrust = { name = \"uuid::Uuid\", import = \"uuid\" }\ngo = { name = \"uuid.UUID\" }\n",
            Path::new("/"),
        )
        .unwrap();
        let config = file.build().unwrap();
        assert_eq!(config.layout, Layout::FilePerType);
        let uuid = &config.substitutions["uuid"];
        assert_eq!(uuid.rust.as_ref().unwrap().import.as_deref(), Some("uuid"));
        assert_eq!(uuid.go.as_ref().unwrap().name, "uuid.UUID");
        assert!(uuid.go.as_ref().unwrap().import.is_none());
    }

    #[test]
    fn module_names_windows_resolves_elsewhere_are_avoided() {
        assert_eq!(rust_module_name("aux"), "aux_types");
        assert_eq!(rust_module_name("COM1"), "com1_types");
        assert!(is_module_name(&rust_module_name("nul")));
        assert!(!is_module_name("con"));
    }

    #[test]
    fn module_names_never_shadow_a_crate() {
        assert_eq!(rust_module_name("std"), "std_types");
        assert_eq!(rust_module_name("serde"), "serde_types");
        assert_eq!(rust_module_name("lib"), "lib_types");
        assert!(!is_module_name("main"));
        assert!(!is_module_name("core"));
    }
}