oapi-codegen 1.5.0

Generate client and server boilerplate from OpenAPI 3 specifications
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! `oapi-codegen` — generate idiomatic Rust from OpenAPI 3 specifications.
//!
//! The pipeline is: load a spec ([`loader`]), lower its component schemas into
//! an intermediate representation ([`lower::schema`] → [`ir`]) and, for the server
//! generator, its operations ([`lower::paths`] → [`ir`]), then emit formatted Rust
//! source ([`emit`]). [`Config`] mirrors `oapi-codegen`'s YAML configuration.

pub mod cli;
pub mod config;
mod coverage;
pub mod deps;
mod diagnostic;
pub mod emit;
pub mod error;
pub mod filter;
pub mod ir;
pub mod loader;
pub mod lower;
pub mod naming;
pub mod package;

use std::path::Path;

pub use crate::config::Config;
pub use crate::error::Error;
pub use crate::error::Result;
use crate::ir::Module;
use crate::ir::ServerUrls;
use crate::ir::Service;
use crate::loader::Spec;
pub use crate::package::GeneratedFile;
pub use crate::package::GeneratedPackage;
pub use crate::package::PackageDrift;
pub use crate::package::check_package;
pub use crate::package::write_package;

/// The number of warnings this process reported, for the configuration and
/// for the spec together.
///
/// A warning goes to stderr and does not fail a run. The CLI reads this count
/// for `--deny-warnings`, which turns a warning into a failed run.
pub fn warnings_reported() -> usize {
    return diagnostic::reported_count();
}

/// Everything one run lowers from a spec, ready for either output layout.
enum Lowered {
    /// The run emits models, and optionally server-URL constants, only.
    Models {
        /// The component models to emit.
        module: Module,
        /// The server-URL items, when the feature is enabled.
        server_urls: Option<ServerUrls>,
    },
    /// The run emits a service: models, per-operation types, and at least one
    /// of the server and client interfaces.
    Service {
        /// The component models the service references.
        module: Module,
        /// The lowered operations.
        service: Service,
        /// The server-URL items, when the feature is enabled.
        server_urls: Option<ServerUrls>,
        /// Which generator interfaces the configuration asked for.
        targets: emit::Targets,
    },
}

/// Load a spec and lower it according to `config`, stopping before emission.
///
/// Both output layouts run exactly the same pipeline, so this holds every step
/// between loading and emitting: filtering, name resolution, lowering, pruning,
/// and the validation passes that reject a spec the emitter cannot express.
fn lower_spec(spec_path: &Path, config: &Config) -> Result<Lowered> {
    if config.generate.embedded_spec {
        return Err(Error::Unimplemented("embedded-spec".to_owned()));
    }
    let want_server = config.generate.std_http_server;
    let mut spec = Spec::load_for(spec_path, want_server, &config.output_options)?;
    spec.apply_filters(&config.output_options);
    let want_client = config.generate.client;
    let server_urls = if config.generate.server_urls {
        lower::lower_server_urls(&spec)?
    } else {
        None
    };
    // A run that emits no type resolves no type name. `server-urls` on its own
    // emits constants only, so it must not read `type-name-suffix` and must not
    // report a collision between two schemas that it never looks at. This matches
    // `response-type-suffix`, which only a server or client run reads.
    if !(config.generate.models || want_server || want_client) {
        return Ok(Lowered::Models {
            module: Module::default(),
            server_urls,
        });
    }
    // A set but useless suffix is an error, and not silently "unset". The
    // resolution checks it, so every caller of `type_renames` gets the check.
    // See `lower::rename::checked_suffix`.
    let type_name_suffix = config.output_options.type_name_suffix.as_deref();
    // Resolve the type names one time and share them. An unresolved collision is
    // held inside `names` and reported below, after pruning decides which models
    // the file holds.
    let names = lower::type_renames(&spec, type_name_suffix)?;
    let mut module = lower::generate_models(&spec, &names)?;
    if want_server || want_client {
        let response_type_suffix = config
            .output_options
            .response_type_suffix
            .as_deref()
            .filter(|suffix| return !suffix.is_empty())
            .unwrap_or(crate::config::DEFAULT_RESPONSE_SUFFIX);
        let mut service = lower::generate_service(&spec, &config.import_mapping, response_type_suffix)?;
        lower::rewrite_service(&mut service, names.renames());
        // Runs before the prune pass, which drops a shape no operation reaches,
        // and before the name checks, which then see the projected names.
        lower::split_by_direction(&mut module, Some(&mut service));
        if !config.output_options.skip_prune {
            lower::prune_unused_models(&mut module, &service);
        }
        // The module is final here, so a collision between two pruned schemas is
        // no longer a problem and only a surviving one is reported. With
        // `skip-prune` the module holds every schema, so every collision reports.
        names.check_emitted(&module)?;
        // A hoisted inline type carries no component name, so the resolution pass
        // above cannot see it. The final item names can still hold a duplicate.
        lower::check_duplicate_models(&module)?;
        // After pruning, so a cycle among dropped models is not reported.
        lower::box_recursive_types(&mut module)?;
        let targets = emit::Targets {
            server: want_server,
            client: want_client,
        };
        let mut reserved = emit::reserved_type_names(targets);
        if !emit::uses_nullable(&module, Some(&service)) {
            reserved.retain(|name| return name.name != "Nullable");
        }
        lower::check_type_name_collisions(&service, &module, &reserved)?;
        lower::check_prelude_shadowing(&module, targets)?;
        return Ok(Lowered::Service {
            module,
            service,
            server_urls,
            targets,
        });
    }
    // Models-only generation prunes nothing, so the module holds every schema and
    // every collision reports.
    lower::split_by_direction(&mut module, None);
    names.check_emitted(&module)?;
    lower::check_duplicate_models(&module)?;
    if emit::uses_nullable(&module, None) {
        lower::check_type_name_collisions(
            &Service::default(),
            &module,
            &emit::reserved_type_names(emit::Targets::default()),
        )?;
    }
    lower::check_prelude_shadowing(&module, emit::Targets::default())?;
    lower::box_recursive_types(&mut module)?;
    return Ok(Lowered::Models { module, server_urls });
}

/// Generate Rust from a spec file according to `configuration`, returning the source.
///
/// Models are emitted when `generate.models` is set, or implicitly when the
/// server or client is generated (so referenced types are in scope). The axum
/// server interface is appended when `generate.std-http-server` is set. The
/// blocking `reqwest` client is appended when `generate.client` is set. Models,
/// per-operation types, and both generators are emitted flat at the crate root,
/// so server and client can share one file.
///
/// Use [`generate_package`] for the layout the CLI writes, which splits the same
/// items across a module tree.
pub fn generate(spec_path: &Path, config: &Config) -> Result<String> {
    return match lower_spec(spec_path, config)? {
        Lowered::Models { module, server_urls } => emit::emit_module(&module, server_urls.as_ref()),
        Lowered::Service {
            module,
            service,
            server_urls,
            targets,
        } => emit::emit_flat(&module, &service, server_urls.as_ref(), targets),
    };
}

/// Generate Rust from a spec file according to `configuration`, returning every
/// file the run produces.
///
/// A run that lowers operations splits its output across a module tree: the file
/// at `output_path` becomes a facade of re-exports, and a companion directory
/// named after that file's stem holds one module per concern (`models`,
/// `operations`, `server`, `client`, `server_urls`) with one file per operation
/// underneath. Every generated name stays reachable from the root file, so a
/// consumer that already mounts it needs no change.
///
/// `output_path` is read for its file stem only, which names that companion
/// directory. Nothing is read from or written to disk here; see
/// [`write_package`] and [`check_package`].
///
/// A models-only run has no operations to split, so it produces the single file
/// it always has.
pub fn generate_package(spec_path: &Path, config: &Config, output_path: &Path) -> Result<GeneratedPackage> {
    return match lower_spec(spec_path, config)? {
        Lowered::Models { module, server_urls } => Ok(GeneratedPackage::new(
            emit::emit_module(&module, server_urls.as_ref())?,
            Vec::new(),
        )),
        Lowered::Service {
            module,
            service,
            server_urls,
            targets,
        } => {
            let stem = package::companion_of(output_path)?
                .file_name()
                .map(|stem| return stem.to_string_lossy().into_owned())
                .ok_or_else(|| {
                    return Error::UnsplittableOutput {
                        path: output_path.display().to_string(),
                    };
                })?;
            emit::emit_package(&module, &service, server_urls.as_ref(), targets, &stem)
        }
    };
}

/// Generate Rust from a spec file according to `configuration` and write it to
/// `output_path`, creating parent directories as needed.
pub fn generate_to_file(spec_path: &Path, config: &Config, output_path: &Path) -> Result<()> {
    let code = generate(spec_path, config)?;
    return write_output(output_path, &code);
}

/// Generate Rust models from a spec file and return the formatted source.
///
/// This entry point takes no config, so two schema names that collapse onto one
/// Rust identifier are an error. Every schema becomes an item, because no
/// operation exists to prune against. Use [`generate`] with
/// `output-options.type-name-suffix` to resolve such a collision by config.
pub fn generate_models_string(spec_path: &Path) -> Result<String> {
    let spec = Spec::load(spec_path)?;
    let names = lower::type_renames(&spec, None)?;
    let mut module = lower::generate_models(&spec, &names)?;
    lower::split_by_direction(&mut module, None);
    // Every schema becomes an item here, so every collision reaches the file.
    names.check_emitted(&module)?;
    lower::check_duplicate_models(&module)?;
    lower::check_prelude_shadowing(&module, emit::Targets::default())?;
    lower::box_recursive_types(&mut module)?;
    let code = emit::emit_module(&module, None)?;
    return Ok(code);
}

/// Generate Rust models from a spec file and write them to `output_path`,
/// creating parent directories as needed.
pub fn generate_models_to_file(spec_path: &Path, output_path: &Path) -> Result<()> {
    let code = generate_models_string(spec_path)?;
    return write_output(output_path, &code);
}

/// What a comparison of generated code against an output file found.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Drift {
    /// The output file holds the generated code.
    None,
    /// The output file does not exist. Generation creates it, so this is drift
    /// and not a read failure.
    Absent,
    /// The output file exists and holds different content.
    Differs,
}

/// Compare `code` with the content of `output_path` and report the difference.
///
/// This reads the file and writes nothing, so a caller can gate a build on stale
/// generated code. The comparison is exact, because the generator formats every
/// output through `prettyplease` and therefore produces one byte sequence for one
/// input.
///
/// The comparison reads bytes and not text. Generated Rust is always UTF-8, so a
/// file that is not gives [`Drift::Differs`]. That is what the file is, and it
/// also keeps a hand-edited or truncated file on the drift path where the remedy
/// applies, rather than on the error path where it does not.
///
/// # Errors
///
/// Returns [`Error::ReadOutput`] when the file exists and cannot be read, for
/// example a directory in place of a file. An absent file gives [`Drift::Absent`]
/// and not an error, because generation creates it.
pub fn check_output(output_path: &Path, code: &str) -> Result<Drift> {
    let existing = match std::fs::read(output_path) {
        Ok(existing) => existing,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
            return Ok(Drift::Absent);
        }
        Err(source) => {
            return Err(Error::ReadOutput {
                path: output_path.display().to_string(),
                source,
            });
        }
    };
    if existing == code.as_bytes() {
        return Ok(Drift::None);
    }
    return Ok(Drift::Differs);
}

/// Write generated source to `output_path`, creating parent directories.
pub fn write_output(output_path: &Path, code: &str) -> Result<()> {
    if let Some(parent) = output_path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent).map_err(|source| {
            return Error::WriteOutput {
                path: output_path.display().to_string(),
                source,
            };
        })?;
    }
    std::fs::write(output_path, code).map_err(|source| {
        return Error::WriteOutput {
            path: output_path.display().to_string(),
            source,
        };
    })?;
    return Ok(());
}

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

    /// A directory under the temp directory that goes away with the test.
    struct TestDir {
        path: std::path::PathBuf,
    }

    impl TestDir {
        fn new(test_name: &str) -> Self {
            let unique = format!(
                "oapi-codegen-check-{test_name}-{}-{}",
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .expect("system clock should be after Unix epoch")
                    .as_nanos(),
            );
            let path = std::env::temp_dir().join(unique);
            std::fs::create_dir_all(&path).expect("create test directory");
            return Self { path };
        }

        fn join(&self, file: &str) -> std::path::PathBuf {
            return self.path.join(file);
        }
    }

    impl Drop for TestDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }

    /// A one-member `allOf` exists to put a keyword beside a `$ref`. It must
    /// generate what the bare `$ref` generates, with the description added. A
    /// marked target is the case that once differed: the wrapped form lost the
    /// mark, so the model did not split by direction. A description written
    /// beside the `$ref` itself must give the same output as the wrapped form.
    #[test]
    fn a_wrapped_reference_generates_what_the_bare_reference_generates() {
        const NOTE: &str = "the note beside the reference";
        let spec = |property: &str| {
            return format!(
                "openapi: 3.0.3
info: {{title: Demo, version: 1.0.0}}
paths:
  /holders:
    post:
      operationId: putHolder
      requestBody:
        required: true
        content: {{application/json: {{schema: {{$ref: '#/components/schemas/Holder'}}}}}}
      responses:
        '200':
          description: ok
          content: {{application/json: {{schema: {{$ref: '#/components/schemas/Holder'}}}}}}
components:
  schemas:
    Plain: {{type: string, maxLength: 3}}
    Served: {{type: string, readOnly: true}}
    Sent: {{type: string, writeOnly: true}}
    Holder:
      type: object
      required: [plain, served]
      properties:
        plain: {}
        served: {}
        sent: {}
",
                property.replace("NAME", "Plain"),
                property.replace("NAME", "Served"),
                property.replace("NAME", "Sent"),
            );
        };
        let dir = TestDir::new("wrapped-reference");
        std::fs::write(
            dir.join("config.yaml"),
            "package: demo\ngenerate: {models: true, std-http-server: true, client: true}\n",
        )
        .expect("write the configuration");
        let config = Config::load(&dir.join("config.yaml")).expect("valid configuration");
        let generate_from = |property: &str| {
            std::fs::write(dir.join("spec.yaml"), spec(property)).expect("write the spec");
            return generate(&dir.join("spec.yaml"), &config).expect("the spec generates");
        };

        let bare = generate_from("{$ref: '#/components/schemas/NAME'}");
        let wrapped = generate_from(&format!(
            "{{allOf: [{{$ref: '#/components/schemas/NAME'}}], description: {NOTE}}}"
        ));

        assert!(bare.contains("HolderRequest"), "the marked targets split the model");
        let without_notes: Vec<&str> = wrapped.lines().filter(|line| return !line.contains(NOTE)).collect();
        assert_eq!(without_notes, bare.lines().collect::<Vec<&str>>());
        assert!(wrapped.contains(NOTE), "the description reaches the output");

        // A description beside the bare `$ref` is kept the same way.
        let beside = generate_from(&format!("{{$ref: '#/components/schemas/NAME', description: {NOTE}}}"));
        assert_eq!(beside, wrapped);
    }

    /// The two places that read a property on their own path, and not through
    /// the field lowering: an `allOf` that merges two members which both declare
    /// the property, and a multipart form field. A description beside the `$ref`
    /// must change neither.
    #[test]
    fn a_described_reference_merges_and_uploads_like_the_bare_reference() {
        const NOTE: &str = "the note beside the reference";
        const TARGET_NOTE: &str = "The kinds there are.";
        let spec = |property: &str, kind: &str| {
            // A nullable wrapper is written in full on both sides, and the note
            // beside the property is the only difference between the two forms.
            let wrapper_note = if property.contains(NOTE) {
                format!(", description: {NOTE}")
            } else {
                String::new()
            };
            return format!(
                "openapi: 3.0.3
info: {{title: Demo, version: 1.0.0}}
paths:
  /uploads:
    post:
      operationId: upload
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [kind]
              properties:
                kind: {property}
                file: {{type: string, format: binary}}
      responses:
        '200':
          description: ok
          content: {{application/json: {{schema: {{$ref: '#/components/schemas/Merged'}}}}}}
        '201':
          description: made
          content: {{application/json: {{schema: {{$ref: '#/components/schemas/Both'}}}}}}
        '202':
          description: queued
          content: {{application/json: {{schema: {{$ref: '#/components/schemas/Across'}}}}}}
components:
  schemas:
    Kind: {kind}
    SameKind: {{$ref: '#/components/schemas/Kind'}}
    Plain: {{type: string}}
    Base: {{type: object, properties: {{kind: {{$ref: '#/components/schemas/Kind'}}, other: {{$ref: '#/components/schemas/SameKind'}}, maybe: {{allOf: [{{$ref: '#/components/schemas/Plain'}}], nullable: true}}}}}}
    Extra: {{type: object, properties: {{kind: {property}, other: {property}, maybe: {{allOf: [{{$ref: '#/components/schemas/Plain'}}], nullable: true{wrapper_note}}}}}}}
    Third: {{type: object, properties: {{other: {{$ref: '#/components/schemas/Kind'}}}}}}
    Half: {{type: object, properties: {{h: {{type: string}}}}}}
    Pair: {{allOf: [{{$ref: '#/components/schemas/Half'}}, {{$ref: '#/components/schemas/Half'}}]}}
    Left: {{type: object, properties: {{pair: {{$ref: '#/components/schemas/Pair'}}}}}}
    Right: {{type: object, properties: {{pair: {{allOf: [{{$ref: '#/components/schemas/Half'}}, {{$ref: '#/components/schemas/Half'}}]{wrapper_note}}}}}}}
    Both: {{allOf: [{{$ref: '#/components/schemas/Left'}}, {{$ref: '#/components/schemas/Right'}}]}}
    CompA: {{allOf: [{{type: object, properties: {{p: {{$ref: '#/components/schemas/Kind'}}}}}}, {{$ref: '#/components/schemas/Half'}}]}}
    CompB: {{allOf: [{{type: object, properties: {{p: {property}}}}}, {{$ref: '#/components/schemas/Half'}}]}}
    Up: {{type: object, properties: {{comp: {{$ref: '#/components/schemas/CompA'}}}}}}
    Down: {{type: object, properties: {{comp: {{$ref: '#/components/schemas/CompB'}}}}}}
    Across: {{allOf: [{{$ref: '#/components/schemas/Up'}}, {{$ref: '#/components/schemas/Down'}}]}}
    Merged: {{allOf: [{{$ref: '#/components/schemas/Base'}}, {{$ref: '#/components/schemas/Extra'}}, {{$ref: '#/components/schemas/Third'}}]}}
"
            );
        };
        let dir = TestDir::new("described-reference");
        std::fs::write(
            dir.join("config.yaml"),
            "package: demo\ngenerate: {models: true, std-http-server: true}\n",
        )
        .expect("write the configuration");
        let config = Config::load(&dir.join("config.yaml")).expect("valid configuration");
        let generate_from = |property: &str, kind: &str| {
            std::fs::write(dir.join("spec.yaml"), spec(property, kind)).expect("write the spec");
            return generate(&dir.join("spec.yaml"), &config).expect("the spec generates");
        };
        let bare_ref = "{$ref: '#/components/schemas/Kind'}";
        let described_ref = format!("{{$ref: '#/components/schemas/Kind', description: {NOTE}}}");

        let plain_kind = "{type: string, enum: [a, b]}";
        let bare = generate_from(bare_ref, plain_kind);
        let described = generate_from(&described_ref, plain_kind);

        assert!(bare.contains("pub struct Merged"), "the overlap merges");
        let without_notes: Vec<&str> = described.lines().filter(|line| return !line.contains(NOTE)).collect();
        assert_eq!(without_notes, bare.lines().collect::<Vec<&str>>());
        // Three times on `Merged`: for the overlap on one name, for the overlap
        // through an alias, and for the overlap of two nullable wrappers; once on
        // the enum that the alias overlap merges into, where it survives the
        // third member; and once on `Both`, where a documented inline composite
        // overlaps a `$ref` to the same composite. A multipart part carries no
        // doc comment, and `Extra` and `Right` reach no operation, so they are
        // pruned.
        assert_eq!(described.matches(NOTE).count(), 5, "{described}");
        // `Across` overlaps two composites that differ only in a note beside a
        // nested `$ref`, and it keeps the first composite's name.
        assert!(described.contains("pub comp: Option<CompA>"), "{described}");

        // When `Kind` has a description of its own, the note beside the
        // property wins on the field, as it does on a plain field.
        let described_kind = format!("{{type: string, enum: [a, b], description: {TARGET_NOTE}}}");
        let documented = generate_from(&described_ref, &described_kind);
        assert!(
            documented.contains(&format!(
                "    /// {NOTE}\n    #[serde(skip_serializing_if = \"Option::is_none\")]\n    pub other"
            )),
            "{documented}"
        );
        assert!(
            !documented.contains(&format!(
                "    /// {TARGET_NOTE}\n    #[serde(skip_serializing_if = \"Option::is_none\")]\n    pub other"
            )),
            "{documented}"
        );
    }

    /// A wrapper around a multipart field's `$ref` keeps its own marks. A
    /// required field that a `readOnly` wrapper marks travels in no request, so
    /// the server reads no part for it.
    #[test]
    fn a_read_only_wrapper_keeps_a_multipart_field_out_of_the_request() {
        let dir = TestDir::new("multipart-wrapper-mark");
        std::fs::write(
            dir.join("spec.yaml"),
            "openapi: 3.0.3
info: {title: Demo, version: 1.0.0}
paths:
  /uploads:
    post:
      operationId: upload
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [served, sent, elsewhere]
              properties:
                served: {allOf: [{$ref: '#/components/schemas/Plain'}], readOnly: true}
                sent: {allOf: [{$ref: '#/components/schemas/Plain'}], description: a note}
                elsewhere: {allOf: [{$ref: 'other.yaml#/components/schemas/Plain'}], readOnly: true}
      responses:
        '204': {description: ok}
components:
  schemas:
    Plain: {type: string}
",
        )
        .expect("write the spec");
        // A part that is never sent is settled by its own mark, so the target
        // in another file, which no multipart field could read, is never reached.
        std::fs::write(
            dir.join("other.yaml"),
            "openapi: 3.0.3\ninfo: {title: Other, version: 1.0.0}\npaths: {}\ncomponents:\n  schemas:\n    Plain: {type: string}\n",
        )
        .expect("write the other document");
        std::fs::write(
            dir.join("config.yaml"),
            "package: demo\ngenerate: {models: true, std-http-server: true}\n",
        )
        .expect("write the configuration");
        let config = Config::load(&dir.join("config.yaml")).expect("valid configuration");

        let code = generate(&dir.join("spec.yaml"), &config).expect("the spec generates");

        assert!(code.contains("\"sent\""), "the plain field is a part: {code}");
        assert!(!code.contains("\"served\""), "the read-only field is no part: {code}");
        assert!(
            !code.contains("\"elsewhere\""),
            "the read-only cross-file field is no part: {code}"
        );

        // A wrapper mark and a target mark that leave no direction are an error
        // here, as they are on any field, whichever side carries which.
        for (wrapper, target) in [("readOnly", "writeOnly"), ("writeOnly", "readOnly")] {
            std::fs::write(
                dir.join("spec.yaml"),
                format!(
                    "openapi: 3.0.3
info: {{title: Demo, version: 1.0.0}}
paths:
  /uploads:
    post:
      operationId: upload
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                torn: {{allOf: [{{$ref: '#/components/schemas/Marked'}}], {wrapper}: true}}
      responses:
        '204': {{description: ok}}
components:
  schemas:
    Marked: {{type: string, {target}: true}}
"
                ),
            )
            .expect("write the spec");
            let error = generate(&dir.join("spec.yaml"), &config).expect_err("both marks leave no direction");
            assert!(error.to_string().contains("readOnly"), "{wrapper} on {target}: {error}");
        }
    }

    #[test]
    fn check_output_reports_an_absent_file_as_drift() {
        let dir = TestDir::new("absent");
        // Generation creates the file, so absence is drift and not a read failure.
        let drift = check_output(&dir.join("out.rs"), "pub struct Widget;\n").expect("check an absent file");
        assert_eq!(drift, Drift::Absent);
    }

    #[test]
    fn check_output_reports_equal_content_as_no_drift() {
        let dir = TestDir::new("equal");
        let path = dir.join("out.rs");
        let code = "pub struct Widget;\n";
        std::fs::write(&path, code).expect("write the output file");
        let drift = check_output(&path, code).expect("check an equal file");
        assert_eq!(drift, Drift::None);
    }

    #[test]
    fn check_output_reports_different_content_as_drift() {
        let dir = TestDir::new("differs");
        let path = dir.join("out.rs");
        std::fs::write(&path, "pub struct Widget;\n").expect("write the output file");
        let drift = check_output(&path, "pub struct Gadget;\n").expect("check a stale file");
        assert_eq!(drift, Drift::Differs);
    }

    #[test]
    fn check_output_compares_exactly() {
        let dir = TestDir::new("exact");
        let path = dir.join("out.rs");
        // The generator formats every output, so one input gives one byte
        // sequence. A trailing newline is therefore a real difference and not
        // noise to normalise away.
        std::fs::write(&path, "pub struct Widget;").expect("write the output file");
        let drift = check_output(&path, "pub struct Widget;\n").expect("check a file with no trailing newline");
        assert_eq!(drift, Drift::Differs);
    }

    #[test]
    fn check_output_reports_content_that_is_not_utf8_as_drift() {
        let dir = TestDir::new("not-utf8");
        let path = dir.join("out.rs");
        // Generated Rust is always UTF-8, so such a file is a differing file and
        // not an unreadable one. The remedy for drift applies, and the remedy for
        // a read failure does not.
        std::fs::write(&path, [0xFF_u8, 0xFE_u8]).expect("write the output file");
        let drift = check_output(&path, "pub struct Widget;\n").expect("check a file that is not UTF-8");
        assert_eq!(drift, Drift::Differs);
    }

    #[test]
    fn check_output_writes_nothing() {
        let dir = TestDir::new("readonly");
        let path = dir.join("out.rs");
        let existing = "pub struct Widget;\n";
        std::fs::write(&path, existing).expect("write the output file");
        let drift = check_output(&path, "pub struct Gadget;\n").expect("check a stale file");
        assert_eq!(drift, Drift::Differs);
        let after = std::fs::read_to_string(&path).expect("read the output file back");
        assert_eq!(after, existing, "`check_output` must not change the file");
    }

    #[test]
    fn check_output_fails_on_a_path_it_cannot_read() {
        let dir = TestDir::new("unreadable");
        let path = dir.join("out.rs");
        // A directory exists but holds no string content, so this is a read
        // failure and not drift.
        std::fs::create_dir(&path).expect("create a directory where a file belongs");
        let error = check_output(&path, "pub struct Widget;\n").expect_err("a directory is not readable as a file");
        assert!(
            matches!(error, Error::ReadOutput { .. }),
            "expected `ReadOutput`, got {error:?}"
        );
    }
}