oapi-codegen 1.0.1

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
//! Computing the external crate dependencies the generated code requires.
//!
//! Unlike Go — where `go mod tidy` resolves imports from the generated source
//! automatically — Cargo never infers dependencies from `use` paths, and a path
//! like `http::StatusCode` reveals neither the crate version nor the Cargo
//! features a consumer must enable. The generator is the only component that
//! knows exactly what it emitted, so it reports the crates (with versions and
//! features) a consumer must add to `Cargo.toml`.
//!
//! The set is derived by scanning the generated source for the crate-root paths
//! and method calls the emitters produce. Deriving it from the actual output
//! (rather than re-deriving from the IR) keeps this report automatically in step
//! with the emitters: if they stop or start referencing a crate, the report
//! follows without a parallel rule set to maintain.
//!
//! The report lists every crate the generated file references. It deliberately
//! does not read the consumer's `Cargo.toml` to prune crates already present.
//! Interpreting a consumer manifest (workspace inheritance, dev/target scopes,
//! feature sufficiency) is Cargo's job — so on `--install-deps` the CLI
//! runs `cargo add`, which merges with any existing declaration.

/// This crate's own manifest, embedded at compile time so the versions the
/// report recommends always match the versions the generated code is compiled
/// and tested against here (see [`manifest_version`]).
const MANIFEST: &str = include_str!("../Cargo.toml");

/// The version requirement declared for `crate_name` in this crate's own
/// `[dependencies]` or `[dev-dependencies]`.
///
/// Deriving the recommended version from our manifest (rather than a hardcoded
/// constant) keeps the report in lockstep with the versions the generated
/// goldens actually compile against, so a dependency bump here updates the
/// report automatically. Every crate the report can name is a (dev-)dependency
/// of this crate — enforced by `reported_crates_have_manifest_versions` — so an
/// absent entry is a programming error, not runtime input.
fn manifest_version(crate_name: &str) -> &'static str {
    match parse_manifest_version(MANIFEST, crate_name) {
        Some(version) => return version,
        None => panic!(
            "crate `{crate_name}` is not a declared dependency of oapi-codegen; cannot determine its version for the dependency report"
        ),
    }
}

/// Find the version requirement declared for `crate_name` in `manifest`, or
/// `None` when it is not declared.
///
/// Two layouts have to work: the one-line form the repository manifest uses,
/// and the `[dependencies.name]` table that `cargo package` rewrites it into.
/// The published binary reads the second.
fn parse_manifest_version<'a>(manifest: &'a str, crate_name: &str) -> Option<&'a str> {
    let mut inside_table_for_crate = false;
    for line in manifest.lines() {
        let line = line.trim();

        if let Some(header) = line.strip_prefix('[').and_then(|rest| return rest.strip_suffix(']')) {
            inside_table_for_crate = is_dependency_table_for(header, crate_name);
            continue;
        }

        if inside_table_for_crate
            && let Some(rest) = line.strip_prefix("version")
            && let Some(value) = rest.trim_start().strip_prefix('=')
            && let Some(version) = first_quoted(value)
        {
            return Some(version);
        }

        let Some(rest) = line.strip_prefix(crate_name) else {
            continue;
        };
        // Require a token boundary so `serde` does not match `serde_json`.
        if !rest.starts_with([' ', '\t', '=']) {
            continue;
        }
        let Some(value) = rest.trim_start().strip_prefix('=') else {
            continue;
        };
        let value = value.trim_start();
        // `name = "x"` gives the version directly. `name = { version = "x", .. }`
        // needs the `version` *key* located — matched as a `version =` token so a
        // feature like `conversion` (which contains "version") is not mistaken
        // for it.
        let scan = match value.strip_prefix('{') {
            Some(table) => match table.find("version =").or_else(|| return table.find("version=")) {
                Some(index) => &table[index..],
                None => continue,
            },
            None => value,
        };
        if let Some(version) = first_quoted(scan) {
            return Some(version);
        }
    }
    return None;
}

/// Whether `header` names the dependency table for `crate_name`, in any of the
/// three dependency scopes `cargo package` can write.
fn is_dependency_table_for(header: &str, crate_name: &str) -> bool {
    for scope in ["dependencies.", "dev-dependencies.", "build-dependencies."] {
        if let Some(name) = header.strip_prefix(scope)
            && name == crate_name
        {
            return true;
        }
    }
    return false;
}

/// The text between the first pair of double quotes in `text`.
fn first_quoted(text: &str) -> Option<&str> {
    let after = text.split_once('"')?.1;
    return after.split_once('"').map(|(value, _)| return value);
}

/// A crate the generated code references, with the version requirement and Cargo
/// features a consumer must declare in `Cargo.toml`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dependency {
    /// The crates.io crate name (for example `axum-extra`).
    pub name: &'static str,
    /// Recommended version requirement (taken from this crate's manifest, so it
    /// matches the version the generated code is built and tested against).
    pub version: &'static str,
    /// Whether the crate's default features are needed.
    pub default_features: bool,
    /// Cargo features the generated code relies on, in a stable order.
    pub features: Vec<&'static str>,
}

impl Dependency {
    /// Render the `Cargo.toml` `[dependencies]` entry for this crate.
    ///
    /// A crate needing neither features nor a `default-features` change renders
    /// as the short `name = "version"` form. Otherwise the inline-table form.
    pub fn toml(&self) -> String {
        if self.default_features && self.features.is_empty() {
            return format!("{} = \"{}\"", self.name, self.version);
        }
        let mut parts = vec![format!("version = \"{}\"", self.version)];
        if !self.default_features {
            parts.push("default-features = false".to_owned());
        }
        if !self.features.is_empty() {
            let features = self
                .features
                .iter()
                .map(|feature| return format!("\"{feature}\""))
                .collect::<Vec<_>>()
                .join(", ");
            parts.push(format!("features = [{features}]"));
        }
        return format!("{} = {{ {} }}", self.name, parts.join(", "));
    }

    /// Render the equivalent `cargo add` command.
    pub fn cargo_add(&self) -> String {
        let mut command = format!("cargo add {}@{}", self.name, self.version);
        if !self.default_features {
            command.push_str(" --no-default-features");
        }
        if !self.features.is_empty() {
            command.push_str(&format!(" --features {}", self.features.join(",")));
        }
        return command;
    }

    /// The `cargo` arguments that add this dependency, for `std::process::Command`.
    pub fn cargo_add_args(&self) -> Vec<String> {
        let mut args = vec!["add".to_owned(), format!("{}@{}", self.name, self.version)];
        if !self.default_features {
            args.push("--no-default-features".to_owned());
        }
        if !self.features.is_empty() {
            args.push("--features".to_owned());
            args.push(self.features.join(","));
        }
        return args;
    }
}

/// Inspect generated `code` and return the external crates it references, in a
/// stable order (shared model crates, then server crates, then client crates).
pub fn required_dependencies(code: &str) -> Vec<Dependency> {
    let has = |needle: &str| return code.contains(needle);
    let mut deps = Vec::new();

    if has("serde::Serialize") || has("serde::Deserialize") {
        deps.push(with_features("serde", true, vec!["derive"]));
    }
    if has("serde_json::") {
        deps.push(plain("serde_json"));
    }
    if has("chrono::") {
        deps.push(with_features("chrono", true, vec!["serde"]));
    }
    if has("uuid::") {
        deps.push(with_features("uuid", true, vec!["serde"]));
    }
    if has("regex::") {
        deps.push(with_features("regex", false, vec!["std", "perf", "unicode"]));
    }
    if has("http::") {
        deps.push(plain("http"));
    }
    if has("axum::") {
        let mut features = Vec::new();
        if has("axum::extract::Multipart") {
            features.push("multipart");
        }
        deps.push(with_features("axum", true, features));
    }
    if has("axum_extra::") {
        let mut features = Vec::new();
        if has("axum_extra::extract::Query") {
            features.push("query");
        }
        if has("axum_extra::extract::CookieJar") {
            features.push("cookie");
        }
        deps.push(with_features("axum-extra", true, features));
    }
    if has("reqwest::") {
        let mut features = Vec::new();
        if has("reqwest::blocking") {
            features.push("blocking");
        }
        if has(".json(") {
            features.push("json");
        }
        if has(".form(") {
            features.push("form");
        }
        if has(".query(") {
            features.push("query");
        }
        if has(".multipart(") || has("reqwest::blocking::multipart") {
            features.push("multipart");
        }
        deps.push(with_features("reqwest", false, features));
    }
    if has("percent_encoding::") {
        deps.push(plain("percent-encoding"));
    }
    if has("serde_urlencoded::") {
        deps.push(plain("serde_urlencoded"));
    }

    return deps;
}

/// A dependency whose version is taken from this crate's manifest, needing
/// default features and no extra features.
fn plain(name: &'static str) -> Dependency {
    return with_features(name, true, Vec::new());
}

/// A dependency whose version is taken from this crate's manifest, with the
/// given default-features flag and feature list.
fn with_features(name: &'static str, default_features: bool, features: Vec<&'static str>) -> Dependency {
    return Dependency {
        name,
        version: manifest_version(name),
        default_features,
        features,
    };
}

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

    #[test]
    fn version_key_matched_as_token_not_substring() {
        // The fixture declares `axum = { features = ["conversion"], version = "0.8.9" }`.
        // the `conversion` feature contains "version" but must not be matched.
        let manifest = include_str!("../tests/fixtures/manifests/reordered_version_key.toml");
        assert_eq!(parse_manifest_version(manifest, "axum"), Some("0.8.9"));
    }

    #[test]
    fn a_version_is_found_in_the_layout_cargo_publishes() {
        // The shape `cargo package` writes: a table per dependency, rather than
        // the one line per dependency the repository manifest uses. The crates
        // are invented, so no dependency bump reaches this.
        let manifest = r#"
            [package]
            name = "specimen"
            version = "9.9.9"

            [dependencies.plain]
            version = "1.2.3"

            [dependencies.with-features]
            version = "4.5.6"
            features = ["one", "two"]

            [dependencies.multi-line-features]
            version = "7.8.9"
            features = [
                "one",
                "two",
            ]

            [dependencies.prefix]
            version = "0.1.0"

            [dependencies.prefix_extended]
            version = "0.2.0"

            [dev-dependencies.only-for-tests]
            version = "5.0.0"

            [build-dependencies.only-for-build]
            version = "6.0.0"
        "#;

        for (crate_name, expected) in [
            ("plain", Some("1.2.3")),
            ("with-features", Some("4.5.6")),
            ("multi-line-features", Some("7.8.9")),
            ("prefix", Some("0.1.0")),
            ("prefix_extended", Some("0.2.0")),
            ("only-for-tests", Some("5.0.0")),
            ("only-for-build", Some("6.0.0")),
            ("absent", None),
            // The package table carries a `version` of its own.
            ("specimen", None),
        ] {
            assert_eq!(
                parse_manifest_version(manifest, crate_name),
                expected,
                "the published layout should report `{crate_name}` as {expected:?}"
            );
        }
    }

    #[test]
    fn toml_renders_short_and_table_forms() {
        assert_eq!(
            Dependency {
                name: "http",
                version: "1",
                default_features: true,
                features: vec![],
            }
            .toml(),
            "http = \"1\""
        );
        assert_eq!(
            Dependency {
                name: "serde",
                version: "1",
                default_features: true,
                features: vec!["derive"],
            }
            .toml(),
            "serde = { version = \"1\", features = [\"derive\"] }"
        );
        assert_eq!(
            Dependency {
                name: "reqwest",
                version: "0.13",
                default_features: false,
                features: vec!["blocking", "json"],
            }
            .toml(),
            "reqwest = { version = \"0.13\", default-features = false, features = [\"blocking\", \"json\"] }"
        );
    }

    #[test]
    fn cargo_add_renders_flags() {
        assert_eq!(
            Dependency {
                name: "http",
                version: "1",
                default_features: true,
                features: vec![],
            }
            .cargo_add(),
            "cargo add http@1"
        );
        assert_eq!(
            Dependency {
                name: "reqwest",
                version: "0.13",
                default_features: false,
                features: vec!["blocking", "json"],
            }
            .cargo_add(),
            "cargo add reqwest@0.13 --no-default-features --features blocking,json"
        );
    }

    #[test]
    fn cargo_add_args_split_for_process_execution() {
        assert_eq!(
            Dependency {
                name: "http",
                version: "1",
                default_features: true,
                features: vec![],
            }
            .cargo_add_args(),
            vec!["add", "http@1"]
        );
        assert_eq!(
            Dependency {
                name: "reqwest",
                version: "0.13",
                default_features: false,
                features: vec!["blocking", "json"],
            }
            .cargo_add_args(),
            vec![
                "add",
                "reqwest@0.13",
                "--no-default-features",
                "--features",
                "blocking,json"
            ]
        );
    }

    #[test]
    fn versions_come_from_the_manifest_not_hardcoded() {
        // The bare `name = "x"` form and the `{ version = "x", .. }` table form
        // are both read from this crate's own Cargo.toml.
        assert_eq!(manifest_version("http"), extract_manifest_version("http"));
        assert_eq!(manifest_version("axum"), extract_manifest_version("axum"));
        assert!(!manifest_version("serde_urlencoded").is_empty());
    }

    #[test]
    fn serde_prefix_does_not_match_serde_json_or_urlencoded() {
        // `serde` must resolve to the `serde` line, not `serde_json`/`serde_urlencoded`.
        assert_eq!(manifest_version("serde"), extract_manifest_version("serde"));
        assert_ne!(manifest_version("serde"), manifest_version("serde_json"));
    }

    #[test]
    fn every_reportable_crate_has_a_manifest_version() {
        // A code blob that trips every detection branch. if any reported crate
        // lacked a manifest entry, `manifest_version` will panic here.
        let code = "\
            serde::Serialize serde_json::Value chrono::DateTime uuid::Uuid http::StatusCode \
            axum::extract::Multipart axum_extra::extract::Query axum_extra::extract::CookieJar \
            reqwest::blocking::multipart .json( .form( .query( percent_encoding::utf8 serde_urlencoded::from_str";
        for dep in required_dependencies(code) {
            assert!(!dep.version.is_empty(), "{} has an empty version", dep.name);
        }
    }

    /// Independent re-implementation used only to cross-check [`manifest_version`]:
    /// find `name` in the embedded manifest and return the first quoted string
    /// after the `version` key (or the bare value).
    fn extract_manifest_version(name: &str) -> String {
        for line in MANIFEST.lines() {
            let line = line.trim();
            if let Some(rest) = line.strip_prefix(name)
                && rest.starts_with([' ', '\t', '='])
            {
                let quoted: Vec<&str> = line.split('"').collect();
                // `name = "x"` -> [.., "x", ..]. `{ version = "x", features = [..] }`
                // -> the version is the first quoted token.
                if quoted.len() >= 2 {
                    return quoted[1].to_owned();
                }
            }
        }
        panic!("`{name}` not found in manifest");
    }

    #[test]
    fn detects_server_stack_from_generated_paths() {
        let code = "axum::Json axum::extract::Multipart axum_extra::extract::Query http::StatusCode serde::Serialize serde_json::Value";
        let deps = required_dependencies(code);
        let names: Vec<&str> = deps.iter().map(|dep| return dep.name).collect();
        assert_eq!(names, vec!["serde", "serde_json", "http", "axum", "axum-extra"]);
        let axum = deps.iter().find(|dep| return dep.name == "axum").expect("axum present");
        assert_eq!(axum.features, vec!["multipart"]);
        let extra = deps
            .iter()
            .find(|dep| return dep.name == "axum-extra")
            .expect("axum-extra present");
        assert_eq!(extra.features, vec!["query"]);
    }

    #[test]
    fn detects_client_stack_from_generated_paths() {
        let code = "reqwest::blocking::Client request.json(&body) percent_encoding::utf8 serde::Deserialize";
        let deps = required_dependencies(code);
        let reqwest = deps
            .iter()
            .find(|dep| return dep.name == "reqwest")
            .expect("reqwest present");
        assert!(!reqwest.default_features);
        assert_eq!(reqwest.features, vec!["blocking", "json"]);
        assert!(deps.iter().any(|dep| return dep.name == "percent-encoding"));
    }

    #[test]
    fn axum_marker_does_not_match_axum_extra() {
        let deps = required_dependencies("axum_extra::extract::CookieJar");
        assert!(
            !deps.iter().any(|dep| return dep.name == "axum"),
            "`axum_extra::` must not be mistaken for the `axum` crate",
        );
        let extra = deps
            .iter()
            .find(|dep| return dep.name == "axum-extra")
            .expect("axum-extra present");
        assert_eq!(extra.features, vec!["cookie"]);
    }

    #[test]
    fn no_dependencies_for_dependency_free_output() {
        assert!(required_dependencies("pub const SERVER_URL: &str = \"https://x\";").is_empty());
    }
}